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, 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, 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, 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, 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, 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 NamedDecl *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 NamedDecl *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, 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, 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, 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(), 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, 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, 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(const NamedDecl *Old, SourceLocation New) { 3857 SourceManager &SrcMgr = getSourceManager(); 3858 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 3859 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 3860 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 3861 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 3862 auto &HSI = PP.getHeaderSearchInfo(); 3863 StringRef HdrFilename = 3864 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 3865 3866 auto noteFromModuleOrInclude = [&](Module *Mod, 3867 SourceLocation IncLoc) -> bool { 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 (IncLoc.isValid()) { 3873 if (Mod) { 3874 Diag(IncLoc, diag::note_redefinition_modules_same_file) 3875 << HdrFilename.str() << Mod->getFullModuleName(); 3876 if (!Mod->DefinitionLoc.isInvalid()) 3877 Diag(Mod->DefinitionLoc, diag::note_defined_here) 3878 << Mod->getFullModuleName(); 3879 } else { 3880 Diag(IncLoc, diag::note_redefinition_include_same_file) 3881 << HdrFilename.str(); 3882 } 3883 return true; 3884 } 3885 3886 return false; 3887 }; 3888 3889 // Is it the same file and same offset? Provide more information on why 3890 // this leads to a redefinition error. 3891 bool EmittedDiag = false; 3892 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 3893 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 3894 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 3895 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 3896 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 3897 3898 // If the header has no guards, emit a note suggesting one. 3899 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 3900 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 3901 3902 if (EmittedDiag) 3903 return; 3904 } 3905 3906 // Redefinition coming from different files or couldn't do better above. 3907 Diag(Old->getLocation(), diag::note_previous_definition); 3908 } 3909 3910 /// We've just determined that \p Old and \p New both appear to be definitions 3911 /// of the same variable. Either diagnose or fix the problem. 3912 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3913 if (!hasVisibleDefinition(Old) && 3914 (New->getFormalLinkage() == InternalLinkage || 3915 New->isInline() || 3916 New->getDescribedVarTemplate() || 3917 New->getNumTemplateParameterLists() || 3918 New->getDeclContext()->isDependentContext())) { 3919 // The previous definition is hidden, and multiple definitions are 3920 // permitted (in separate TUs). Demote this to a declaration. 3921 New->demoteThisDefinitionToDeclaration(); 3922 3923 // Make the canonical definition visible. 3924 if (auto *OldTD = Old->getDescribedVarTemplate()) 3925 makeMergedDefinitionVisible(OldTD); 3926 makeMergedDefinitionVisible(Old); 3927 return false; 3928 } else { 3929 Diag(New->getLocation(), diag::err_redefinition) << New; 3930 notePreviousDefinition(Old, New->getLocation()); 3931 New->setInvalidDecl(); 3932 return true; 3933 } 3934 } 3935 3936 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3937 /// no declarator (e.g. "struct foo;") is parsed. 3938 Decl * 3939 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3940 RecordDecl *&AnonRecord) { 3941 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3942 AnonRecord); 3943 } 3944 3945 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3946 // disambiguate entities defined in different scopes. 3947 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3948 // compatibility. 3949 // We will pick our mangling number depending on which version of MSVC is being 3950 // targeted. 3951 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3952 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3953 ? S->getMSCurManglingNumber() 3954 : S->getMSLastManglingNumber(); 3955 } 3956 3957 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3958 if (!Context.getLangOpts().CPlusPlus) 3959 return; 3960 3961 if (isa<CXXRecordDecl>(Tag->getParent())) { 3962 // If this tag is the direct child of a class, number it if 3963 // it is anonymous. 3964 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3965 return; 3966 MangleNumberingContext &MCtx = 3967 Context.getManglingNumberContext(Tag->getParent()); 3968 Context.setManglingNumber( 3969 Tag, MCtx.getManglingNumber( 3970 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3971 return; 3972 } 3973 3974 // If this tag isn't a direct child of a class, number it if it is local. 3975 Decl *ManglingContextDecl; 3976 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3977 Tag->getDeclContext(), ManglingContextDecl)) { 3978 Context.setManglingNumber( 3979 Tag, MCtx->getManglingNumber( 3980 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3981 } 3982 } 3983 3984 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3985 TypedefNameDecl *NewTD) { 3986 if (TagFromDeclSpec->isInvalidDecl()) 3987 return; 3988 3989 // Do nothing if the tag already has a name for linkage purposes. 3990 if (TagFromDeclSpec->hasNameForLinkage()) 3991 return; 3992 3993 // A well-formed anonymous tag must always be a TUK_Definition. 3994 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3995 3996 // The type must match the tag exactly; no qualifiers allowed. 3997 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3998 Context.getTagDeclType(TagFromDeclSpec))) { 3999 if (getLangOpts().CPlusPlus) 4000 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4001 return; 4002 } 4003 4004 // If we've already computed linkage for the anonymous tag, then 4005 // adding a typedef name for the anonymous decl can change that 4006 // linkage, which might be a serious problem. Diagnose this as 4007 // unsupported and ignore the typedef name. TODO: we should 4008 // pursue this as a language defect and establish a formal rule 4009 // for how to handle it. 4010 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4011 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4012 4013 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4014 tagLoc = getLocForEndOfToken(tagLoc); 4015 4016 llvm::SmallString<40> textToInsert; 4017 textToInsert += ' '; 4018 textToInsert += NewTD->getIdentifier()->getName(); 4019 Diag(tagLoc, diag::note_typedef_changes_linkage) 4020 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4021 return; 4022 } 4023 4024 // Otherwise, set this is the anon-decl typedef for the tag. 4025 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4026 } 4027 4028 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4029 switch (T) { 4030 case DeclSpec::TST_class: 4031 return 0; 4032 case DeclSpec::TST_struct: 4033 return 1; 4034 case DeclSpec::TST_interface: 4035 return 2; 4036 case DeclSpec::TST_union: 4037 return 3; 4038 case DeclSpec::TST_enum: 4039 return 4; 4040 default: 4041 llvm_unreachable("unexpected type specifier"); 4042 } 4043 } 4044 4045 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4046 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4047 /// parameters to cope with template friend declarations. 4048 Decl * 4049 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4050 MultiTemplateParamsArg TemplateParams, 4051 bool IsExplicitInstantiation, 4052 RecordDecl *&AnonRecord) { 4053 Decl *TagD = nullptr; 4054 TagDecl *Tag = nullptr; 4055 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4056 DS.getTypeSpecType() == DeclSpec::TST_struct || 4057 DS.getTypeSpecType() == DeclSpec::TST_interface || 4058 DS.getTypeSpecType() == DeclSpec::TST_union || 4059 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4060 TagD = DS.getRepAsDecl(); 4061 4062 if (!TagD) // We probably had an error 4063 return nullptr; 4064 4065 // Note that the above type specs guarantee that the 4066 // type rep is a Decl, whereas in many of the others 4067 // it's a Type. 4068 if (isa<TagDecl>(TagD)) 4069 Tag = cast<TagDecl>(TagD); 4070 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4071 Tag = CTD->getTemplatedDecl(); 4072 } 4073 4074 if (Tag) { 4075 handleTagNumbering(Tag, S); 4076 Tag->setFreeStanding(); 4077 if (Tag->isInvalidDecl()) 4078 return Tag; 4079 } 4080 4081 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4082 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4083 // or incomplete types shall not be restrict-qualified." 4084 if (TypeQuals & DeclSpec::TQ_restrict) 4085 Diag(DS.getRestrictSpecLoc(), 4086 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4087 << DS.getSourceRange(); 4088 } 4089 4090 if (DS.isInlineSpecified()) 4091 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4092 << getLangOpts().CPlusPlus1z; 4093 4094 if (DS.isConstexprSpecified()) { 4095 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4096 // and definitions of functions and variables. 4097 if (Tag) 4098 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4099 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4100 else 4101 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4102 // Don't emit warnings after this error. 4103 return TagD; 4104 } 4105 4106 if (DS.isConceptSpecified()) { 4107 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 4108 // either a function concept and its definition or a variable concept and 4109 // its initializer. 4110 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 4111 return TagD; 4112 } 4113 4114 DiagnoseFunctionSpecifiers(DS); 4115 4116 if (DS.isFriendSpecified()) { 4117 // If we're dealing with a decl but not a TagDecl, assume that 4118 // whatever routines created it handled the friendship aspect. 4119 if (TagD && !Tag) 4120 return nullptr; 4121 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4122 } 4123 4124 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4125 bool IsExplicitSpecialization = 4126 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4127 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4128 !IsExplicitInstantiation && !IsExplicitSpecialization && 4129 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4130 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4131 // nested-name-specifier unless it is an explicit instantiation 4132 // or an explicit specialization. 4133 // 4134 // FIXME: We allow class template partial specializations here too, per the 4135 // obvious intent of DR1819. 4136 // 4137 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4138 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4139 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4140 return nullptr; 4141 } 4142 4143 // Track whether this decl-specifier declares anything. 4144 bool DeclaresAnything = true; 4145 4146 // Handle anonymous struct definitions. 4147 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4148 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4149 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4150 if (getLangOpts().CPlusPlus || 4151 Record->getDeclContext()->isRecord()) { 4152 // If CurContext is a DeclContext that can contain statements, 4153 // RecursiveASTVisitor won't visit the decls that 4154 // BuildAnonymousStructOrUnion() will put into CurContext. 4155 // Also store them here so that they can be part of the 4156 // DeclStmt that gets created in this case. 4157 // FIXME: Also return the IndirectFieldDecls created by 4158 // BuildAnonymousStructOr union, for the same reason? 4159 if (CurContext->isFunctionOrMethod()) 4160 AnonRecord = Record; 4161 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4162 Context.getPrintingPolicy()); 4163 } 4164 4165 DeclaresAnything = false; 4166 } 4167 } 4168 4169 // C11 6.7.2.1p2: 4170 // A struct-declaration that does not declare an anonymous structure or 4171 // anonymous union shall contain a struct-declarator-list. 4172 // 4173 // This rule also existed in C89 and C99; the grammar for struct-declaration 4174 // did not permit a struct-declaration without a struct-declarator-list. 4175 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4176 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4177 // Check for Microsoft C extension: anonymous struct/union member. 4178 // Handle 2 kinds of anonymous struct/union: 4179 // struct STRUCT; 4180 // union UNION; 4181 // and 4182 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4183 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4184 if ((Tag && Tag->getDeclName()) || 4185 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4186 RecordDecl *Record = nullptr; 4187 if (Tag) 4188 Record = dyn_cast<RecordDecl>(Tag); 4189 else if (const RecordType *RT = 4190 DS.getRepAsType().get()->getAsStructureType()) 4191 Record = RT->getDecl(); 4192 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4193 Record = UT->getDecl(); 4194 4195 if (Record && getLangOpts().MicrosoftExt) { 4196 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4197 << Record->isUnion() << DS.getSourceRange(); 4198 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4199 } 4200 4201 DeclaresAnything = false; 4202 } 4203 } 4204 4205 // Skip all the checks below if we have a type error. 4206 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4207 (TagD && TagD->isInvalidDecl())) 4208 return TagD; 4209 4210 if (getLangOpts().CPlusPlus && 4211 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4212 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4213 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4214 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4215 DeclaresAnything = false; 4216 4217 if (!DS.isMissingDeclaratorOk()) { 4218 // Customize diagnostic for a typedef missing a name. 4219 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4220 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4221 << DS.getSourceRange(); 4222 else 4223 DeclaresAnything = false; 4224 } 4225 4226 if (DS.isModulePrivateSpecified() && 4227 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4228 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4229 << Tag->getTagKind() 4230 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4231 4232 ActOnDocumentableDecl(TagD); 4233 4234 // C 6.7/2: 4235 // A declaration [...] shall declare at least a declarator [...], a tag, 4236 // or the members of an enumeration. 4237 // C++ [dcl.dcl]p3: 4238 // [If there are no declarators], and except for the declaration of an 4239 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4240 // names into the program, or shall redeclare a name introduced by a 4241 // previous declaration. 4242 if (!DeclaresAnything) { 4243 // In C, we allow this as a (popular) extension / bug. Don't bother 4244 // producing further diagnostics for redundant qualifiers after this. 4245 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4246 return TagD; 4247 } 4248 4249 // C++ [dcl.stc]p1: 4250 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4251 // init-declarator-list of the declaration shall not be empty. 4252 // C++ [dcl.fct.spec]p1: 4253 // If a cv-qualifier appears in a decl-specifier-seq, the 4254 // init-declarator-list of the declaration shall not be empty. 4255 // 4256 // Spurious qualifiers here appear to be valid in C. 4257 unsigned DiagID = diag::warn_standalone_specifier; 4258 if (getLangOpts().CPlusPlus) 4259 DiagID = diag::ext_standalone_specifier; 4260 4261 // Note that a linkage-specification sets a storage class, but 4262 // 'extern "C" struct foo;' is actually valid and not theoretically 4263 // useless. 4264 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4265 if (SCS == DeclSpec::SCS_mutable) 4266 // Since mutable is not a viable storage class specifier in C, there is 4267 // no reason to treat it as an extension. Instead, diagnose as an error. 4268 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4269 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4270 Diag(DS.getStorageClassSpecLoc(), DiagID) 4271 << DeclSpec::getSpecifierName(SCS); 4272 } 4273 4274 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4275 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4276 << DeclSpec::getSpecifierName(TSCS); 4277 if (DS.getTypeQualifiers()) { 4278 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4279 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4280 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4281 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4282 // Restrict is covered above. 4283 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4284 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4285 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4286 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4287 } 4288 4289 // Warn about ignored type attributes, for example: 4290 // __attribute__((aligned)) struct A; 4291 // Attributes should be placed after tag to apply to type declaration. 4292 if (!DS.getAttributes().empty()) { 4293 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4294 if (TypeSpecType == DeclSpec::TST_class || 4295 TypeSpecType == DeclSpec::TST_struct || 4296 TypeSpecType == DeclSpec::TST_interface || 4297 TypeSpecType == DeclSpec::TST_union || 4298 TypeSpecType == DeclSpec::TST_enum) { 4299 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4300 attrs = attrs->getNext()) 4301 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4302 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4303 } 4304 } 4305 4306 return TagD; 4307 } 4308 4309 /// We are trying to inject an anonymous member into the given scope; 4310 /// check if there's an existing declaration that can't be overloaded. 4311 /// 4312 /// \return true if this is a forbidden redeclaration 4313 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4314 Scope *S, 4315 DeclContext *Owner, 4316 DeclarationName Name, 4317 SourceLocation NameLoc, 4318 bool IsUnion) { 4319 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4320 Sema::ForRedeclaration); 4321 if (!SemaRef.LookupName(R, S)) return false; 4322 4323 // Pick a representative declaration. 4324 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4325 assert(PrevDecl && "Expected a non-null Decl"); 4326 4327 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4328 return false; 4329 4330 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4331 << IsUnion << Name; 4332 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4333 4334 return true; 4335 } 4336 4337 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4338 /// anonymous struct or union AnonRecord into the owning context Owner 4339 /// and scope S. This routine will be invoked just after we realize 4340 /// that an unnamed union or struct is actually an anonymous union or 4341 /// struct, e.g., 4342 /// 4343 /// @code 4344 /// union { 4345 /// int i; 4346 /// float f; 4347 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4348 /// // f into the surrounding scope.x 4349 /// @endcode 4350 /// 4351 /// This routine is recursive, injecting the names of nested anonymous 4352 /// structs/unions into the owning context and scope as well. 4353 static bool 4354 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4355 RecordDecl *AnonRecord, AccessSpecifier AS, 4356 SmallVectorImpl<NamedDecl *> &Chaining) { 4357 bool Invalid = false; 4358 4359 // Look every FieldDecl and IndirectFieldDecl with a name. 4360 for (auto *D : AnonRecord->decls()) { 4361 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4362 cast<NamedDecl>(D)->getDeclName()) { 4363 ValueDecl *VD = cast<ValueDecl>(D); 4364 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4365 VD->getLocation(), 4366 AnonRecord->isUnion())) { 4367 // C++ [class.union]p2: 4368 // The names of the members of an anonymous union shall be 4369 // distinct from the names of any other entity in the 4370 // scope in which the anonymous union is declared. 4371 Invalid = true; 4372 } else { 4373 // C++ [class.union]p2: 4374 // For the purpose of name lookup, after the anonymous union 4375 // definition, the members of the anonymous union are 4376 // considered to have been defined in the scope in which the 4377 // anonymous union is declared. 4378 unsigned OldChainingSize = Chaining.size(); 4379 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4380 Chaining.append(IF->chain_begin(), IF->chain_end()); 4381 else 4382 Chaining.push_back(VD); 4383 4384 assert(Chaining.size() >= 2); 4385 NamedDecl **NamedChain = 4386 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4387 for (unsigned i = 0; i < Chaining.size(); i++) 4388 NamedChain[i] = Chaining[i]; 4389 4390 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4391 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4392 VD->getType(), {NamedChain, Chaining.size()}); 4393 4394 for (const auto *Attr : VD->attrs()) 4395 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4396 4397 IndirectField->setAccess(AS); 4398 IndirectField->setImplicit(); 4399 SemaRef.PushOnScopeChains(IndirectField, S); 4400 4401 // That includes picking up the appropriate access specifier. 4402 if (AS != AS_none) IndirectField->setAccess(AS); 4403 4404 Chaining.resize(OldChainingSize); 4405 } 4406 } 4407 } 4408 4409 return Invalid; 4410 } 4411 4412 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4413 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4414 /// illegal input values are mapped to SC_None. 4415 static StorageClass 4416 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4417 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4418 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4419 "Parser allowed 'typedef' as storage class VarDecl."); 4420 switch (StorageClassSpec) { 4421 case DeclSpec::SCS_unspecified: return SC_None; 4422 case DeclSpec::SCS_extern: 4423 if (DS.isExternInLinkageSpec()) 4424 return SC_None; 4425 return SC_Extern; 4426 case DeclSpec::SCS_static: return SC_Static; 4427 case DeclSpec::SCS_auto: return SC_Auto; 4428 case DeclSpec::SCS_register: return SC_Register; 4429 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4430 // Illegal SCSs map to None: error reporting is up to the caller. 4431 case DeclSpec::SCS_mutable: // Fall through. 4432 case DeclSpec::SCS_typedef: return SC_None; 4433 } 4434 llvm_unreachable("unknown storage class specifier"); 4435 } 4436 4437 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4438 assert(Record->hasInClassInitializer()); 4439 4440 for (const auto *I : Record->decls()) { 4441 const auto *FD = dyn_cast<FieldDecl>(I); 4442 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4443 FD = IFD->getAnonField(); 4444 if (FD && FD->hasInClassInitializer()) 4445 return FD->getLocation(); 4446 } 4447 4448 llvm_unreachable("couldn't find in-class initializer"); 4449 } 4450 4451 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4452 SourceLocation DefaultInitLoc) { 4453 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4454 return; 4455 4456 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4457 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4458 } 4459 4460 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4461 CXXRecordDecl *AnonUnion) { 4462 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4463 return; 4464 4465 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4466 } 4467 4468 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4469 /// anonymous structure or union. Anonymous unions are a C++ feature 4470 /// (C++ [class.union]) and a C11 feature; anonymous structures 4471 /// are a C11 feature and GNU C++ extension. 4472 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4473 AccessSpecifier AS, 4474 RecordDecl *Record, 4475 const PrintingPolicy &Policy) { 4476 DeclContext *Owner = Record->getDeclContext(); 4477 4478 // Diagnose whether this anonymous struct/union is an extension. 4479 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4480 Diag(Record->getLocation(), diag::ext_anonymous_union); 4481 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4482 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4483 else if (!Record->isUnion() && !getLangOpts().C11) 4484 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4485 4486 // C and C++ require different kinds of checks for anonymous 4487 // structs/unions. 4488 bool Invalid = false; 4489 if (getLangOpts().CPlusPlus) { 4490 const char *PrevSpec = nullptr; 4491 unsigned DiagID; 4492 if (Record->isUnion()) { 4493 // C++ [class.union]p6: 4494 // Anonymous unions declared in a named namespace or in the 4495 // global namespace shall be declared static. 4496 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4497 (isa<TranslationUnitDecl>(Owner) || 4498 (isa<NamespaceDecl>(Owner) && 4499 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4500 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4501 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4502 4503 // Recover by adding 'static'. 4504 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4505 PrevSpec, DiagID, Policy); 4506 } 4507 // C++ [class.union]p6: 4508 // A storage class is not allowed in a declaration of an 4509 // anonymous union in a class scope. 4510 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4511 isa<RecordDecl>(Owner)) { 4512 Diag(DS.getStorageClassSpecLoc(), 4513 diag::err_anonymous_union_with_storage_spec) 4514 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4515 4516 // Recover by removing the storage specifier. 4517 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4518 SourceLocation(), 4519 PrevSpec, DiagID, Context.getPrintingPolicy()); 4520 } 4521 } 4522 4523 // Ignore const/volatile/restrict qualifiers. 4524 if (DS.getTypeQualifiers()) { 4525 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4526 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4527 << Record->isUnion() << "const" 4528 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4529 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4530 Diag(DS.getVolatileSpecLoc(), 4531 diag::ext_anonymous_struct_union_qualified) 4532 << Record->isUnion() << "volatile" 4533 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4534 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4535 Diag(DS.getRestrictSpecLoc(), 4536 diag::ext_anonymous_struct_union_qualified) 4537 << Record->isUnion() << "restrict" 4538 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4539 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4540 Diag(DS.getAtomicSpecLoc(), 4541 diag::ext_anonymous_struct_union_qualified) 4542 << Record->isUnion() << "_Atomic" 4543 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4544 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4545 Diag(DS.getUnalignedSpecLoc(), 4546 diag::ext_anonymous_struct_union_qualified) 4547 << Record->isUnion() << "__unaligned" 4548 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4549 4550 DS.ClearTypeQualifiers(); 4551 } 4552 4553 // C++ [class.union]p2: 4554 // The member-specification of an anonymous union shall only 4555 // define non-static data members. [Note: nested types and 4556 // functions cannot be declared within an anonymous union. ] 4557 for (auto *Mem : Record->decls()) { 4558 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4559 // C++ [class.union]p3: 4560 // An anonymous union shall not have private or protected 4561 // members (clause 11). 4562 assert(FD->getAccess() != AS_none); 4563 if (FD->getAccess() != AS_public) { 4564 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4565 << Record->isUnion() << (FD->getAccess() == AS_protected); 4566 Invalid = true; 4567 } 4568 4569 // C++ [class.union]p1 4570 // An object of a class with a non-trivial constructor, a non-trivial 4571 // copy constructor, a non-trivial destructor, or a non-trivial copy 4572 // assignment operator cannot be a member of a union, nor can an 4573 // array of such objects. 4574 if (CheckNontrivialField(FD)) 4575 Invalid = true; 4576 } else if (Mem->isImplicit()) { 4577 // Any implicit members are fine. 4578 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4579 // This is a type that showed up in an 4580 // elaborated-type-specifier inside the anonymous struct or 4581 // union, but which actually declares a type outside of the 4582 // anonymous struct or union. It's okay. 4583 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4584 if (!MemRecord->isAnonymousStructOrUnion() && 4585 MemRecord->getDeclName()) { 4586 // Visual C++ allows type definition in anonymous struct or union. 4587 if (getLangOpts().MicrosoftExt) 4588 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4589 << Record->isUnion(); 4590 else { 4591 // This is a nested type declaration. 4592 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4593 << Record->isUnion(); 4594 Invalid = true; 4595 } 4596 } else { 4597 // This is an anonymous type definition within another anonymous type. 4598 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4599 // not part of standard C++. 4600 Diag(MemRecord->getLocation(), 4601 diag::ext_anonymous_record_with_anonymous_type) 4602 << Record->isUnion(); 4603 } 4604 } else if (isa<AccessSpecDecl>(Mem)) { 4605 // Any access specifier is fine. 4606 } else if (isa<StaticAssertDecl>(Mem)) { 4607 // In C++1z, static_assert declarations are also fine. 4608 } else { 4609 // We have something that isn't a non-static data 4610 // member. Complain about it. 4611 unsigned DK = diag::err_anonymous_record_bad_member; 4612 if (isa<TypeDecl>(Mem)) 4613 DK = diag::err_anonymous_record_with_type; 4614 else if (isa<FunctionDecl>(Mem)) 4615 DK = diag::err_anonymous_record_with_function; 4616 else if (isa<VarDecl>(Mem)) 4617 DK = diag::err_anonymous_record_with_static; 4618 4619 // Visual C++ allows type definition in anonymous struct or union. 4620 if (getLangOpts().MicrosoftExt && 4621 DK == diag::err_anonymous_record_with_type) 4622 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4623 << Record->isUnion(); 4624 else { 4625 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4626 Invalid = true; 4627 } 4628 } 4629 } 4630 4631 // C++11 [class.union]p8 (DR1460): 4632 // At most one variant member of a union may have a 4633 // brace-or-equal-initializer. 4634 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4635 Owner->isRecord()) 4636 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4637 cast<CXXRecordDecl>(Record)); 4638 } 4639 4640 if (!Record->isUnion() && !Owner->isRecord()) { 4641 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4642 << getLangOpts().CPlusPlus; 4643 Invalid = true; 4644 } 4645 4646 // Mock up a declarator. 4647 Declarator Dc(DS, Declarator::MemberContext); 4648 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4649 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4650 4651 // Create a declaration for this anonymous struct/union. 4652 NamedDecl *Anon = nullptr; 4653 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4654 Anon = FieldDecl::Create(Context, OwningClass, 4655 DS.getLocStart(), 4656 Record->getLocation(), 4657 /*IdentifierInfo=*/nullptr, 4658 Context.getTypeDeclType(Record), 4659 TInfo, 4660 /*BitWidth=*/nullptr, /*Mutable=*/false, 4661 /*InitStyle=*/ICIS_NoInit); 4662 Anon->setAccess(AS); 4663 if (getLangOpts().CPlusPlus) 4664 FieldCollector->Add(cast<FieldDecl>(Anon)); 4665 } else { 4666 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4667 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4668 if (SCSpec == DeclSpec::SCS_mutable) { 4669 // mutable can only appear on non-static class members, so it's always 4670 // an error here 4671 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4672 Invalid = true; 4673 SC = SC_None; 4674 } 4675 4676 Anon = VarDecl::Create(Context, Owner, 4677 DS.getLocStart(), 4678 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4679 Context.getTypeDeclType(Record), 4680 TInfo, SC); 4681 4682 // Default-initialize the implicit variable. This initialization will be 4683 // trivial in almost all cases, except if a union member has an in-class 4684 // initializer: 4685 // union { int n = 0; }; 4686 ActOnUninitializedDecl(Anon); 4687 } 4688 Anon->setImplicit(); 4689 4690 // Mark this as an anonymous struct/union type. 4691 Record->setAnonymousStructOrUnion(true); 4692 4693 // Add the anonymous struct/union object to the current 4694 // context. We'll be referencing this object when we refer to one of 4695 // its members. 4696 Owner->addDecl(Anon); 4697 4698 // Inject the members of the anonymous struct/union into the owning 4699 // context and into the identifier resolver chain for name lookup 4700 // purposes. 4701 SmallVector<NamedDecl*, 2> Chain; 4702 Chain.push_back(Anon); 4703 4704 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4705 Invalid = true; 4706 4707 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4708 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4709 Decl *ManglingContextDecl; 4710 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4711 NewVD->getDeclContext(), ManglingContextDecl)) { 4712 Context.setManglingNumber( 4713 NewVD, MCtx->getManglingNumber( 4714 NewVD, getMSManglingNumber(getLangOpts(), S))); 4715 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4716 } 4717 } 4718 } 4719 4720 if (Invalid) 4721 Anon->setInvalidDecl(); 4722 4723 return Anon; 4724 } 4725 4726 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4727 /// Microsoft C anonymous structure. 4728 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4729 /// Example: 4730 /// 4731 /// struct A { int a; }; 4732 /// struct B { struct A; int b; }; 4733 /// 4734 /// void foo() { 4735 /// B var; 4736 /// var.a = 3; 4737 /// } 4738 /// 4739 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4740 RecordDecl *Record) { 4741 assert(Record && "expected a record!"); 4742 4743 // Mock up a declarator. 4744 Declarator Dc(DS, Declarator::TypeNameContext); 4745 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4746 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4747 4748 auto *ParentDecl = cast<RecordDecl>(CurContext); 4749 QualType RecTy = Context.getTypeDeclType(Record); 4750 4751 // Create a declaration for this anonymous struct. 4752 NamedDecl *Anon = FieldDecl::Create(Context, 4753 ParentDecl, 4754 DS.getLocStart(), 4755 DS.getLocStart(), 4756 /*IdentifierInfo=*/nullptr, 4757 RecTy, 4758 TInfo, 4759 /*BitWidth=*/nullptr, /*Mutable=*/false, 4760 /*InitStyle=*/ICIS_NoInit); 4761 Anon->setImplicit(); 4762 4763 // Add the anonymous struct object to the current context. 4764 CurContext->addDecl(Anon); 4765 4766 // Inject the members of the anonymous struct into the current 4767 // context and into the identifier resolver chain for name lookup 4768 // purposes. 4769 SmallVector<NamedDecl*, 2> Chain; 4770 Chain.push_back(Anon); 4771 4772 RecordDecl *RecordDef = Record->getDefinition(); 4773 if (RequireCompleteType(Anon->getLocation(), RecTy, 4774 diag::err_field_incomplete) || 4775 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4776 AS_none, Chain)) { 4777 Anon->setInvalidDecl(); 4778 ParentDecl->setInvalidDecl(); 4779 } 4780 4781 return Anon; 4782 } 4783 4784 /// GetNameForDeclarator - Determine the full declaration name for the 4785 /// given Declarator. 4786 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4787 return GetNameFromUnqualifiedId(D.getName()); 4788 } 4789 4790 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4791 DeclarationNameInfo 4792 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4793 DeclarationNameInfo NameInfo; 4794 NameInfo.setLoc(Name.StartLocation); 4795 4796 switch (Name.getKind()) { 4797 4798 case UnqualifiedId::IK_ImplicitSelfParam: 4799 case UnqualifiedId::IK_Identifier: 4800 NameInfo.setName(Name.Identifier); 4801 NameInfo.setLoc(Name.StartLocation); 4802 return NameInfo; 4803 4804 case UnqualifiedId::IK_DeductionGuideName: { 4805 // C++ [temp.deduct.guide]p3: 4806 // The simple-template-id shall name a class template specialization. 4807 // The template-name shall be the same identifier as the template-name 4808 // of the simple-template-id. 4809 // These together intend to imply that the template-name shall name a 4810 // class template. 4811 // FIXME: template<typename T> struct X {}; 4812 // template<typename T> using Y = X<T>; 4813 // Y(int) -> Y<int>; 4814 // satisfies these rules but does not name a class template. 4815 TemplateName TN = Name.TemplateName.get().get(); 4816 auto *Template = TN.getAsTemplateDecl(); 4817 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4818 Diag(Name.StartLocation, 4819 diag::err_deduction_guide_name_not_class_template) 4820 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4821 if (Template) 4822 Diag(Template->getLocation(), diag::note_template_decl_here); 4823 return DeclarationNameInfo(); 4824 } 4825 4826 NameInfo.setName( 4827 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4828 NameInfo.setLoc(Name.StartLocation); 4829 return NameInfo; 4830 } 4831 4832 case UnqualifiedId::IK_OperatorFunctionId: 4833 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4834 Name.OperatorFunctionId.Operator)); 4835 NameInfo.setLoc(Name.StartLocation); 4836 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4837 = Name.OperatorFunctionId.SymbolLocations[0]; 4838 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4839 = Name.EndLocation.getRawEncoding(); 4840 return NameInfo; 4841 4842 case UnqualifiedId::IK_LiteralOperatorId: 4843 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4844 Name.Identifier)); 4845 NameInfo.setLoc(Name.StartLocation); 4846 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4847 return NameInfo; 4848 4849 case UnqualifiedId::IK_ConversionFunctionId: { 4850 TypeSourceInfo *TInfo; 4851 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4852 if (Ty.isNull()) 4853 return DeclarationNameInfo(); 4854 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4855 Context.getCanonicalType(Ty))); 4856 NameInfo.setLoc(Name.StartLocation); 4857 NameInfo.setNamedTypeInfo(TInfo); 4858 return NameInfo; 4859 } 4860 4861 case UnqualifiedId::IK_ConstructorName: { 4862 TypeSourceInfo *TInfo; 4863 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4864 if (Ty.isNull()) 4865 return DeclarationNameInfo(); 4866 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4867 Context.getCanonicalType(Ty))); 4868 NameInfo.setLoc(Name.StartLocation); 4869 NameInfo.setNamedTypeInfo(TInfo); 4870 return NameInfo; 4871 } 4872 4873 case UnqualifiedId::IK_ConstructorTemplateId: { 4874 // In well-formed code, we can only have a constructor 4875 // template-id that refers to the current context, so go there 4876 // to find the actual type being constructed. 4877 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4878 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4879 return DeclarationNameInfo(); 4880 4881 // Determine the type of the class being constructed. 4882 QualType CurClassType = Context.getTypeDeclType(CurClass); 4883 4884 // FIXME: Check two things: that the template-id names the same type as 4885 // CurClassType, and that the template-id does not occur when the name 4886 // was qualified. 4887 4888 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4889 Context.getCanonicalType(CurClassType))); 4890 NameInfo.setLoc(Name.StartLocation); 4891 // FIXME: should we retrieve TypeSourceInfo? 4892 NameInfo.setNamedTypeInfo(nullptr); 4893 return NameInfo; 4894 } 4895 4896 case UnqualifiedId::IK_DestructorName: { 4897 TypeSourceInfo *TInfo; 4898 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4899 if (Ty.isNull()) 4900 return DeclarationNameInfo(); 4901 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4902 Context.getCanonicalType(Ty))); 4903 NameInfo.setLoc(Name.StartLocation); 4904 NameInfo.setNamedTypeInfo(TInfo); 4905 return NameInfo; 4906 } 4907 4908 case UnqualifiedId::IK_TemplateId: { 4909 TemplateName TName = Name.TemplateId->Template.get(); 4910 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4911 return Context.getNameForTemplate(TName, TNameLoc); 4912 } 4913 4914 } // switch (Name.getKind()) 4915 4916 llvm_unreachable("Unknown name kind"); 4917 } 4918 4919 static QualType getCoreType(QualType Ty) { 4920 do { 4921 if (Ty->isPointerType() || Ty->isReferenceType()) 4922 Ty = Ty->getPointeeType(); 4923 else if (Ty->isArrayType()) 4924 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4925 else 4926 return Ty.withoutLocalFastQualifiers(); 4927 } while (true); 4928 } 4929 4930 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4931 /// and Definition have "nearly" matching parameters. This heuristic is 4932 /// used to improve diagnostics in the case where an out-of-line function 4933 /// definition doesn't match any declaration within the class or namespace. 4934 /// Also sets Params to the list of indices to the parameters that differ 4935 /// between the declaration and the definition. If hasSimilarParameters 4936 /// returns true and Params is empty, then all of the parameters match. 4937 static bool hasSimilarParameters(ASTContext &Context, 4938 FunctionDecl *Declaration, 4939 FunctionDecl *Definition, 4940 SmallVectorImpl<unsigned> &Params) { 4941 Params.clear(); 4942 if (Declaration->param_size() != Definition->param_size()) 4943 return false; 4944 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4945 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4946 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4947 4948 // The parameter types are identical 4949 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4950 continue; 4951 4952 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4953 QualType DefParamBaseTy = getCoreType(DefParamTy); 4954 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4955 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4956 4957 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4958 (DeclTyName && DeclTyName == DefTyName)) 4959 Params.push_back(Idx); 4960 else // The two parameters aren't even close 4961 return false; 4962 } 4963 4964 return true; 4965 } 4966 4967 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4968 /// declarator needs to be rebuilt in the current instantiation. 4969 /// Any bits of declarator which appear before the name are valid for 4970 /// consideration here. That's specifically the type in the decl spec 4971 /// and the base type in any member-pointer chunks. 4972 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4973 DeclarationName Name) { 4974 // The types we specifically need to rebuild are: 4975 // - typenames, typeofs, and decltypes 4976 // - types which will become injected class names 4977 // Of course, we also need to rebuild any type referencing such a 4978 // type. It's safest to just say "dependent", but we call out a 4979 // few cases here. 4980 4981 DeclSpec &DS = D.getMutableDeclSpec(); 4982 switch (DS.getTypeSpecType()) { 4983 case DeclSpec::TST_typename: 4984 case DeclSpec::TST_typeofType: 4985 case DeclSpec::TST_underlyingType: 4986 case DeclSpec::TST_atomic: { 4987 // Grab the type from the parser. 4988 TypeSourceInfo *TSI = nullptr; 4989 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4990 if (T.isNull() || !T->isDependentType()) break; 4991 4992 // Make sure there's a type source info. This isn't really much 4993 // of a waste; most dependent types should have type source info 4994 // attached already. 4995 if (!TSI) 4996 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4997 4998 // Rebuild the type in the current instantiation. 4999 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5000 if (!TSI) return true; 5001 5002 // Store the new type back in the decl spec. 5003 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5004 DS.UpdateTypeRep(LocType); 5005 break; 5006 } 5007 5008 case DeclSpec::TST_decltype: 5009 case DeclSpec::TST_typeofExpr: { 5010 Expr *E = DS.getRepAsExpr(); 5011 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5012 if (Result.isInvalid()) return true; 5013 DS.UpdateExprRep(Result.get()); 5014 break; 5015 } 5016 5017 default: 5018 // Nothing to do for these decl specs. 5019 break; 5020 } 5021 5022 // It doesn't matter what order we do this in. 5023 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5024 DeclaratorChunk &Chunk = D.getTypeObject(I); 5025 5026 // The only type information in the declarator which can come 5027 // before the declaration name is the base type of a member 5028 // pointer. 5029 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5030 continue; 5031 5032 // Rebuild the scope specifier in-place. 5033 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5034 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5035 return true; 5036 } 5037 5038 return false; 5039 } 5040 5041 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5042 D.setFunctionDefinitionKind(FDK_Declaration); 5043 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5044 5045 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5046 Dcl && Dcl->getDeclContext()->isFileContext()) 5047 Dcl->setTopLevelDeclInObjCContainer(); 5048 5049 if (getLangOpts().OpenCL) 5050 setCurrentOpenCLExtensionForDecl(Dcl); 5051 5052 return Dcl; 5053 } 5054 5055 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5056 /// If T is the name of a class, then each of the following shall have a 5057 /// name different from T: 5058 /// - every static data member of class T; 5059 /// - every member function of class T 5060 /// - every member of class T that is itself a type; 5061 /// \returns true if the declaration name violates these rules. 5062 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5063 DeclarationNameInfo NameInfo) { 5064 DeclarationName Name = NameInfo.getName(); 5065 5066 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5067 while (Record && Record->isAnonymousStructOrUnion()) 5068 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5069 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5070 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5071 return true; 5072 } 5073 5074 return false; 5075 } 5076 5077 /// \brief Diagnose a declaration whose declarator-id has the given 5078 /// nested-name-specifier. 5079 /// 5080 /// \param SS The nested-name-specifier of the declarator-id. 5081 /// 5082 /// \param DC The declaration context to which the nested-name-specifier 5083 /// resolves. 5084 /// 5085 /// \param Name The name of the entity being declared. 5086 /// 5087 /// \param Loc The location of the name of the entity being declared. 5088 /// 5089 /// \returns true if we cannot safely recover from this error, false otherwise. 5090 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5091 DeclarationName Name, 5092 SourceLocation Loc) { 5093 DeclContext *Cur = CurContext; 5094 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5095 Cur = Cur->getParent(); 5096 5097 // If the user provided a superfluous scope specifier that refers back to the 5098 // class in which the entity is already declared, diagnose and ignore it. 5099 // 5100 // class X { 5101 // void X::f(); 5102 // }; 5103 // 5104 // Note, it was once ill-formed to give redundant qualification in all 5105 // contexts, but that rule was removed by DR482. 5106 if (Cur->Equals(DC)) { 5107 if (Cur->isRecord()) { 5108 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5109 : diag::err_member_extra_qualification) 5110 << Name << FixItHint::CreateRemoval(SS.getRange()); 5111 SS.clear(); 5112 } else { 5113 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5114 } 5115 return false; 5116 } 5117 5118 // Check whether the qualifying scope encloses the scope of the original 5119 // declaration. 5120 if (!Cur->Encloses(DC)) { 5121 if (Cur->isRecord()) 5122 Diag(Loc, diag::err_member_qualification) 5123 << Name << SS.getRange(); 5124 else if (isa<TranslationUnitDecl>(DC)) 5125 Diag(Loc, diag::err_invalid_declarator_global_scope) 5126 << Name << SS.getRange(); 5127 else if (isa<FunctionDecl>(Cur)) 5128 Diag(Loc, diag::err_invalid_declarator_in_function) 5129 << Name << SS.getRange(); 5130 else if (isa<BlockDecl>(Cur)) 5131 Diag(Loc, diag::err_invalid_declarator_in_block) 5132 << Name << SS.getRange(); 5133 else 5134 Diag(Loc, diag::err_invalid_declarator_scope) 5135 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5136 5137 return true; 5138 } 5139 5140 if (Cur->isRecord()) { 5141 // Cannot qualify members within a class. 5142 Diag(Loc, diag::err_member_qualification) 5143 << Name << SS.getRange(); 5144 SS.clear(); 5145 5146 // C++ constructors and destructors with incorrect scopes can break 5147 // our AST invariants by having the wrong underlying types. If 5148 // that's the case, then drop this declaration entirely. 5149 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5150 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5151 !Context.hasSameType(Name.getCXXNameType(), 5152 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5153 return true; 5154 5155 return false; 5156 } 5157 5158 // C++11 [dcl.meaning]p1: 5159 // [...] "The nested-name-specifier of the qualified declarator-id shall 5160 // not begin with a decltype-specifer" 5161 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5162 while (SpecLoc.getPrefix()) 5163 SpecLoc = SpecLoc.getPrefix(); 5164 if (dyn_cast_or_null<DecltypeType>( 5165 SpecLoc.getNestedNameSpecifier()->getAsType())) 5166 Diag(Loc, diag::err_decltype_in_declarator) 5167 << SpecLoc.getTypeLoc().getSourceRange(); 5168 5169 return false; 5170 } 5171 5172 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5173 MultiTemplateParamsArg TemplateParamLists) { 5174 // TODO: consider using NameInfo for diagnostic. 5175 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5176 DeclarationName Name = NameInfo.getName(); 5177 5178 // All of these full declarators require an identifier. If it doesn't have 5179 // one, the ParsedFreeStandingDeclSpec action should be used. 5180 if (D.isDecompositionDeclarator()) { 5181 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5182 } else if (!Name) { 5183 if (!D.isInvalidType()) // Reject this if we think it is valid. 5184 Diag(D.getDeclSpec().getLocStart(), 5185 diag::err_declarator_need_ident) 5186 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5187 return nullptr; 5188 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5189 return nullptr; 5190 5191 // The scope passed in may not be a decl scope. Zip up the scope tree until 5192 // we find one that is. 5193 while ((S->getFlags() & Scope::DeclScope) == 0 || 5194 (S->getFlags() & Scope::TemplateParamScope) != 0) 5195 S = S->getParent(); 5196 5197 DeclContext *DC = CurContext; 5198 if (D.getCXXScopeSpec().isInvalid()) 5199 D.setInvalidType(); 5200 else if (D.getCXXScopeSpec().isSet()) { 5201 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5202 UPPC_DeclarationQualifier)) 5203 return nullptr; 5204 5205 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5206 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5207 if (!DC || isa<EnumDecl>(DC)) { 5208 // If we could not compute the declaration context, it's because the 5209 // declaration context is dependent but does not refer to a class, 5210 // class template, or class template partial specialization. Complain 5211 // and return early, to avoid the coming semantic disaster. 5212 Diag(D.getIdentifierLoc(), 5213 diag::err_template_qualified_declarator_no_match) 5214 << D.getCXXScopeSpec().getScopeRep() 5215 << D.getCXXScopeSpec().getRange(); 5216 return nullptr; 5217 } 5218 bool IsDependentContext = DC->isDependentContext(); 5219 5220 if (!IsDependentContext && 5221 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5222 return nullptr; 5223 5224 // If a class is incomplete, do not parse entities inside it. 5225 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5226 Diag(D.getIdentifierLoc(), 5227 diag::err_member_def_undefined_record) 5228 << Name << DC << D.getCXXScopeSpec().getRange(); 5229 return nullptr; 5230 } 5231 if (!D.getDeclSpec().isFriendSpecified()) { 5232 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5233 Name, D.getIdentifierLoc())) { 5234 if (DC->isRecord()) 5235 return nullptr; 5236 5237 D.setInvalidType(); 5238 } 5239 } 5240 5241 // Check whether we need to rebuild the type of the given 5242 // declaration in the current instantiation. 5243 if (EnteringContext && IsDependentContext && 5244 TemplateParamLists.size() != 0) { 5245 ContextRAII SavedContext(*this, DC); 5246 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5247 D.setInvalidType(); 5248 } 5249 } 5250 5251 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5252 QualType R = TInfo->getType(); 5253 5254 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5255 // If this is a typedef, we'll end up spewing multiple diagnostics. 5256 // Just return early; it's safer. If this is a function, let the 5257 // "constructor cannot have a return type" diagnostic handle it. 5258 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5259 return nullptr; 5260 5261 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5262 UPPC_DeclarationType)) 5263 D.setInvalidType(); 5264 5265 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5266 ForRedeclaration); 5267 5268 // See if this is a redefinition of a variable in the same scope. 5269 if (!D.getCXXScopeSpec().isSet()) { 5270 bool IsLinkageLookup = false; 5271 bool CreateBuiltins = false; 5272 5273 // If the declaration we're planning to build will be a function 5274 // or object with linkage, then look for another declaration with 5275 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5276 // 5277 // If the declaration we're planning to build will be declared with 5278 // external linkage in the translation unit, create any builtin with 5279 // the same name. 5280 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5281 /* Do nothing*/; 5282 else if (CurContext->isFunctionOrMethod() && 5283 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5284 R->isFunctionType())) { 5285 IsLinkageLookup = true; 5286 CreateBuiltins = 5287 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5288 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5289 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5290 CreateBuiltins = true; 5291 5292 if (IsLinkageLookup) 5293 Previous.clear(LookupRedeclarationWithLinkage); 5294 5295 LookupName(Previous, S, CreateBuiltins); 5296 } else { // Something like "int foo::x;" 5297 LookupQualifiedName(Previous, DC); 5298 5299 // C++ [dcl.meaning]p1: 5300 // When the declarator-id is qualified, the declaration shall refer to a 5301 // previously declared member of the class or namespace to which the 5302 // qualifier refers (or, in the case of a namespace, of an element of the 5303 // inline namespace set of that namespace (7.3.1)) or to a specialization 5304 // thereof; [...] 5305 // 5306 // Note that we already checked the context above, and that we do not have 5307 // enough information to make sure that Previous contains the declaration 5308 // we want to match. For example, given: 5309 // 5310 // class X { 5311 // void f(); 5312 // void f(float); 5313 // }; 5314 // 5315 // void X::f(int) { } // ill-formed 5316 // 5317 // In this case, Previous will point to the overload set 5318 // containing the two f's declared in X, but neither of them 5319 // matches. 5320 5321 // C++ [dcl.meaning]p1: 5322 // [...] the member shall not merely have been introduced by a 5323 // using-declaration in the scope of the class or namespace nominated by 5324 // the nested-name-specifier of the declarator-id. 5325 RemoveUsingDecls(Previous); 5326 } 5327 5328 if (Previous.isSingleResult() && 5329 Previous.getFoundDecl()->isTemplateParameter()) { 5330 // Maybe we will complain about the shadowed template parameter. 5331 if (!D.isInvalidType()) 5332 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5333 Previous.getFoundDecl()); 5334 5335 // Just pretend that we didn't see the previous declaration. 5336 Previous.clear(); 5337 } 5338 5339 // In C++, the previous declaration we find might be a tag type 5340 // (class or enum). In this case, the new declaration will hide the 5341 // tag type. Note that this does does not apply if we're declaring a 5342 // typedef (C++ [dcl.typedef]p4). 5343 if (Previous.isSingleTagDecl() && 5344 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5345 Previous.clear(); 5346 5347 // Check that there are no default arguments other than in the parameters 5348 // of a function declaration (C++ only). 5349 if (getLangOpts().CPlusPlus) 5350 CheckExtraCXXDefaultArguments(D); 5351 5352 if (D.getDeclSpec().isConceptSpecified()) { 5353 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5354 // applied only to the definition of a function template or variable 5355 // template, declared in namespace scope 5356 if (!TemplateParamLists.size()) { 5357 Diag(D.getDeclSpec().getConceptSpecLoc(), 5358 diag:: err_concept_wrong_decl_kind); 5359 return nullptr; 5360 } 5361 5362 if (!DC->getRedeclContext()->isFileContext()) { 5363 Diag(D.getIdentifierLoc(), 5364 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5365 return nullptr; 5366 } 5367 } 5368 5369 NamedDecl *New; 5370 5371 bool AddToScope = true; 5372 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5373 if (TemplateParamLists.size()) { 5374 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5375 return nullptr; 5376 } 5377 5378 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5379 } else if (R->isFunctionType()) { 5380 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5381 TemplateParamLists, 5382 AddToScope); 5383 } else { 5384 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5385 AddToScope); 5386 } 5387 5388 if (!New) 5389 return nullptr; 5390 5391 // If this has an identifier and is not a function template specialization, 5392 // add it to the scope stack. 5393 if (New->getDeclName() && AddToScope) { 5394 // Only make a locally-scoped extern declaration visible if it is the first 5395 // declaration of this entity. Qualified lookup for such an entity should 5396 // only find this declaration if there is no visible declaration of it. 5397 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5398 PushOnScopeChains(New, S, AddToContext); 5399 if (!AddToContext) 5400 CurContext->addHiddenDecl(New); 5401 } 5402 5403 if (isInOpenMPDeclareTargetContext()) 5404 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5405 5406 return New; 5407 } 5408 5409 /// Helper method to turn variable array types into constant array 5410 /// types in certain situations which would otherwise be errors (for 5411 /// GCC compatibility). 5412 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5413 ASTContext &Context, 5414 bool &SizeIsNegative, 5415 llvm::APSInt &Oversized) { 5416 // This method tries to turn a variable array into a constant 5417 // array even when the size isn't an ICE. This is necessary 5418 // for compatibility with code that depends on gcc's buggy 5419 // constant expression folding, like struct {char x[(int)(char*)2];} 5420 SizeIsNegative = false; 5421 Oversized = 0; 5422 5423 if (T->isDependentType()) 5424 return QualType(); 5425 5426 QualifierCollector Qs; 5427 const Type *Ty = Qs.strip(T); 5428 5429 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5430 QualType Pointee = PTy->getPointeeType(); 5431 QualType FixedType = 5432 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5433 Oversized); 5434 if (FixedType.isNull()) return FixedType; 5435 FixedType = Context.getPointerType(FixedType); 5436 return Qs.apply(Context, FixedType); 5437 } 5438 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5439 QualType Inner = PTy->getInnerType(); 5440 QualType FixedType = 5441 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5442 Oversized); 5443 if (FixedType.isNull()) return FixedType; 5444 FixedType = Context.getParenType(FixedType); 5445 return Qs.apply(Context, FixedType); 5446 } 5447 5448 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5449 if (!VLATy) 5450 return QualType(); 5451 // FIXME: We should probably handle this case 5452 if (VLATy->getElementType()->isVariablyModifiedType()) 5453 return QualType(); 5454 5455 llvm::APSInt Res; 5456 if (!VLATy->getSizeExpr() || 5457 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5458 return QualType(); 5459 5460 // Check whether the array size is negative. 5461 if (Res.isSigned() && Res.isNegative()) { 5462 SizeIsNegative = true; 5463 return QualType(); 5464 } 5465 5466 // Check whether the array is too large to be addressed. 5467 unsigned ActiveSizeBits 5468 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5469 Res); 5470 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5471 Oversized = Res; 5472 return QualType(); 5473 } 5474 5475 return Context.getConstantArrayType(VLATy->getElementType(), 5476 Res, ArrayType::Normal, 0); 5477 } 5478 5479 static void 5480 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5481 SrcTL = SrcTL.getUnqualifiedLoc(); 5482 DstTL = DstTL.getUnqualifiedLoc(); 5483 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5484 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5485 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5486 DstPTL.getPointeeLoc()); 5487 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5488 return; 5489 } 5490 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5491 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5492 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5493 DstPTL.getInnerLoc()); 5494 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5495 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5496 return; 5497 } 5498 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5499 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5500 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5501 TypeLoc DstElemTL = DstATL.getElementLoc(); 5502 DstElemTL.initializeFullCopy(SrcElemTL); 5503 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5504 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5505 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5506 } 5507 5508 /// Helper method to turn variable array types into constant array 5509 /// types in certain situations which would otherwise be errors (for 5510 /// GCC compatibility). 5511 static TypeSourceInfo* 5512 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5513 ASTContext &Context, 5514 bool &SizeIsNegative, 5515 llvm::APSInt &Oversized) { 5516 QualType FixedTy 5517 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5518 SizeIsNegative, Oversized); 5519 if (FixedTy.isNull()) 5520 return nullptr; 5521 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5522 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5523 FixedTInfo->getTypeLoc()); 5524 return FixedTInfo; 5525 } 5526 5527 /// \brief Register the given locally-scoped extern "C" declaration so 5528 /// that it can be found later for redeclarations. We include any extern "C" 5529 /// declaration that is not visible in the translation unit here, not just 5530 /// function-scope declarations. 5531 void 5532 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5533 if (!getLangOpts().CPlusPlus && 5534 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5535 // Don't need to track declarations in the TU in C. 5536 return; 5537 5538 // Note that we have a locally-scoped external with this name. 5539 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5540 } 5541 5542 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5543 // FIXME: We can have multiple results via __attribute__((overloadable)). 5544 auto Result = Context.getExternCContextDecl()->lookup(Name); 5545 return Result.empty() ? nullptr : *Result.begin(); 5546 } 5547 5548 /// \brief Diagnose function specifiers on a declaration of an identifier that 5549 /// does not identify a function. 5550 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5551 // FIXME: We should probably indicate the identifier in question to avoid 5552 // confusion for constructs like "virtual int a(), b;" 5553 if (DS.isVirtualSpecified()) 5554 Diag(DS.getVirtualSpecLoc(), 5555 diag::err_virtual_non_function); 5556 5557 if (DS.isExplicitSpecified()) 5558 Diag(DS.getExplicitSpecLoc(), 5559 diag::err_explicit_non_function); 5560 5561 if (DS.isNoreturnSpecified()) 5562 Diag(DS.getNoreturnSpecLoc(), 5563 diag::err_noreturn_non_function); 5564 } 5565 5566 NamedDecl* 5567 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5568 TypeSourceInfo *TInfo, LookupResult &Previous) { 5569 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5570 if (D.getCXXScopeSpec().isSet()) { 5571 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5572 << D.getCXXScopeSpec().getRange(); 5573 D.setInvalidType(); 5574 // Pretend we didn't see the scope specifier. 5575 DC = CurContext; 5576 Previous.clear(); 5577 } 5578 5579 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5580 5581 if (D.getDeclSpec().isInlineSpecified()) 5582 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5583 << getLangOpts().CPlusPlus1z; 5584 if (D.getDeclSpec().isConstexprSpecified()) 5585 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5586 << 1; 5587 if (D.getDeclSpec().isConceptSpecified()) 5588 Diag(D.getDeclSpec().getConceptSpecLoc(), 5589 diag::err_concept_wrong_decl_kind); 5590 5591 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5592 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName) 5593 Diag(D.getName().StartLocation, 5594 diag::err_deduction_guide_invalid_specifier) 5595 << "typedef"; 5596 else 5597 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5598 << D.getName().getSourceRange(); 5599 return nullptr; 5600 } 5601 5602 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5603 if (!NewTD) return nullptr; 5604 5605 // Handle attributes prior to checking for duplicates in MergeVarDecl 5606 ProcessDeclAttributes(S, NewTD, D); 5607 5608 CheckTypedefForVariablyModifiedType(S, NewTD); 5609 5610 bool Redeclaration = D.isRedeclaration(); 5611 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5612 D.setRedeclaration(Redeclaration); 5613 return ND; 5614 } 5615 5616 void 5617 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5618 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5619 // then it shall have block scope. 5620 // Note that variably modified types must be fixed before merging the decl so 5621 // that redeclarations will match. 5622 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5623 QualType T = TInfo->getType(); 5624 if (T->isVariablyModifiedType()) { 5625 getCurFunction()->setHasBranchProtectedScope(); 5626 5627 if (S->getFnParent() == nullptr) { 5628 bool SizeIsNegative; 5629 llvm::APSInt Oversized; 5630 TypeSourceInfo *FixedTInfo = 5631 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5632 SizeIsNegative, 5633 Oversized); 5634 if (FixedTInfo) { 5635 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5636 NewTD->setTypeSourceInfo(FixedTInfo); 5637 } else { 5638 if (SizeIsNegative) 5639 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5640 else if (T->isVariableArrayType()) 5641 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5642 else if (Oversized.getBoolValue()) 5643 Diag(NewTD->getLocation(), diag::err_array_too_large) 5644 << Oversized.toString(10); 5645 else 5646 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5647 NewTD->setInvalidDecl(); 5648 } 5649 } 5650 } 5651 } 5652 5653 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5654 /// declares a typedef-name, either using the 'typedef' type specifier or via 5655 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5656 NamedDecl* 5657 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5658 LookupResult &Previous, bool &Redeclaration) { 5659 5660 // Find the shadowed declaration before filtering for scope. 5661 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5662 5663 // Merge the decl with the existing one if appropriate. If the decl is 5664 // in an outer scope, it isn't the same thing. 5665 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5666 /*AllowInlineNamespace*/false); 5667 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5668 if (!Previous.empty()) { 5669 Redeclaration = true; 5670 MergeTypedefNameDecl(S, NewTD, Previous); 5671 } 5672 5673 if (ShadowedDecl && !Redeclaration) 5674 CheckShadow(NewTD, ShadowedDecl, Previous); 5675 5676 // If this is the C FILE type, notify the AST context. 5677 if (IdentifierInfo *II = NewTD->getIdentifier()) 5678 if (!NewTD->isInvalidDecl() && 5679 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5680 if (II->isStr("FILE")) 5681 Context.setFILEDecl(NewTD); 5682 else if (II->isStr("jmp_buf")) 5683 Context.setjmp_bufDecl(NewTD); 5684 else if (II->isStr("sigjmp_buf")) 5685 Context.setsigjmp_bufDecl(NewTD); 5686 else if (II->isStr("ucontext_t")) 5687 Context.setucontext_tDecl(NewTD); 5688 } 5689 5690 return NewTD; 5691 } 5692 5693 /// \brief Determines whether the given declaration is an out-of-scope 5694 /// previous declaration. 5695 /// 5696 /// This routine should be invoked when name lookup has found a 5697 /// previous declaration (PrevDecl) that is not in the scope where a 5698 /// new declaration by the same name is being introduced. If the new 5699 /// declaration occurs in a local scope, previous declarations with 5700 /// linkage may still be considered previous declarations (C99 5701 /// 6.2.2p4-5, C++ [basic.link]p6). 5702 /// 5703 /// \param PrevDecl the previous declaration found by name 5704 /// lookup 5705 /// 5706 /// \param DC the context in which the new declaration is being 5707 /// declared. 5708 /// 5709 /// \returns true if PrevDecl is an out-of-scope previous declaration 5710 /// for a new delcaration with the same name. 5711 static bool 5712 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5713 ASTContext &Context) { 5714 if (!PrevDecl) 5715 return false; 5716 5717 if (!PrevDecl->hasLinkage()) 5718 return false; 5719 5720 if (Context.getLangOpts().CPlusPlus) { 5721 // C++ [basic.link]p6: 5722 // If there is a visible declaration of an entity with linkage 5723 // having the same name and type, ignoring entities declared 5724 // outside the innermost enclosing namespace scope, the block 5725 // scope declaration declares that same entity and receives the 5726 // linkage of the previous declaration. 5727 DeclContext *OuterContext = DC->getRedeclContext(); 5728 if (!OuterContext->isFunctionOrMethod()) 5729 // This rule only applies to block-scope declarations. 5730 return false; 5731 5732 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5733 if (PrevOuterContext->isRecord()) 5734 // We found a member function: ignore it. 5735 return false; 5736 5737 // Find the innermost enclosing namespace for the new and 5738 // previous declarations. 5739 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5740 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5741 5742 // The previous declaration is in a different namespace, so it 5743 // isn't the same function. 5744 if (!OuterContext->Equals(PrevOuterContext)) 5745 return false; 5746 } 5747 5748 return true; 5749 } 5750 5751 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5752 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5753 if (!SS.isSet()) return; 5754 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5755 } 5756 5757 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5758 QualType type = decl->getType(); 5759 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5760 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5761 // Various kinds of declaration aren't allowed to be __autoreleasing. 5762 unsigned kind = -1U; 5763 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5764 if (var->hasAttr<BlocksAttr>()) 5765 kind = 0; // __block 5766 else if (!var->hasLocalStorage()) 5767 kind = 1; // global 5768 } else if (isa<ObjCIvarDecl>(decl)) { 5769 kind = 3; // ivar 5770 } else if (isa<FieldDecl>(decl)) { 5771 kind = 2; // field 5772 } 5773 5774 if (kind != -1U) { 5775 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5776 << kind; 5777 } 5778 } else if (lifetime == Qualifiers::OCL_None) { 5779 // Try to infer lifetime. 5780 if (!type->isObjCLifetimeType()) 5781 return false; 5782 5783 lifetime = type->getObjCARCImplicitLifetime(); 5784 type = Context.getLifetimeQualifiedType(type, lifetime); 5785 decl->setType(type); 5786 } 5787 5788 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5789 // Thread-local variables cannot have lifetime. 5790 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5791 var->getTLSKind()) { 5792 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5793 << var->getType(); 5794 return true; 5795 } 5796 } 5797 5798 return false; 5799 } 5800 5801 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5802 // Ensure that an auto decl is deduced otherwise the checks below might cache 5803 // the wrong linkage. 5804 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5805 5806 // 'weak' only applies to declarations with external linkage. 5807 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5808 if (!ND.isExternallyVisible()) { 5809 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5810 ND.dropAttr<WeakAttr>(); 5811 } 5812 } 5813 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5814 if (ND.isExternallyVisible()) { 5815 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5816 ND.dropAttr<WeakRefAttr>(); 5817 ND.dropAttr<AliasAttr>(); 5818 } 5819 } 5820 5821 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5822 if (VD->hasInit()) { 5823 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5824 assert(VD->isThisDeclarationADefinition() && 5825 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5826 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5827 VD->dropAttr<AliasAttr>(); 5828 } 5829 } 5830 } 5831 5832 // 'selectany' only applies to externally visible variable declarations. 5833 // It does not apply to functions. 5834 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5835 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5836 S.Diag(Attr->getLocation(), 5837 diag::err_attribute_selectany_non_extern_data); 5838 ND.dropAttr<SelectAnyAttr>(); 5839 } 5840 } 5841 5842 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5843 // dll attributes require external linkage. Static locals may have external 5844 // linkage but still cannot be explicitly imported or exported. 5845 auto *VD = dyn_cast<VarDecl>(&ND); 5846 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5847 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5848 << &ND << Attr; 5849 ND.setInvalidDecl(); 5850 } 5851 } 5852 5853 // Virtual functions cannot be marked as 'notail'. 5854 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5855 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5856 if (MD->isVirtual()) { 5857 S.Diag(ND.getLocation(), 5858 diag::err_invalid_attribute_on_virtual_function) 5859 << Attr; 5860 ND.dropAttr<NotTailCalledAttr>(); 5861 } 5862 } 5863 5864 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5865 NamedDecl *NewDecl, 5866 bool IsSpecialization, 5867 bool IsDefinition) { 5868 if (OldDecl->isInvalidDecl()) 5869 return; 5870 5871 bool IsTemplate = false; 5872 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5873 OldDecl = OldTD->getTemplatedDecl(); 5874 IsTemplate = true; 5875 if (!IsSpecialization) 5876 IsDefinition = false; 5877 } 5878 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5879 NewDecl = NewTD->getTemplatedDecl(); 5880 IsTemplate = true; 5881 } 5882 5883 if (!OldDecl || !NewDecl) 5884 return; 5885 5886 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5887 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5888 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5889 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5890 5891 // dllimport and dllexport are inheritable attributes so we have to exclude 5892 // inherited attribute instances. 5893 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5894 (NewExportAttr && !NewExportAttr->isInherited()); 5895 5896 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5897 // the only exception being explicit specializations. 5898 // Implicitly generated declarations are also excluded for now because there 5899 // is no other way to switch these to use dllimport or dllexport. 5900 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5901 5902 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5903 // Allow with a warning for free functions and global variables. 5904 bool JustWarn = false; 5905 if (!OldDecl->isCXXClassMember()) { 5906 auto *VD = dyn_cast<VarDecl>(OldDecl); 5907 if (VD && !VD->getDescribedVarTemplate()) 5908 JustWarn = true; 5909 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5910 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5911 JustWarn = true; 5912 } 5913 5914 // We cannot change a declaration that's been used because IR has already 5915 // been emitted. Dllimported functions will still work though (modulo 5916 // address equality) as they can use the thunk. 5917 if (OldDecl->isUsed()) 5918 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5919 JustWarn = false; 5920 5921 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5922 : diag::err_attribute_dll_redeclaration; 5923 S.Diag(NewDecl->getLocation(), DiagID) 5924 << NewDecl 5925 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5926 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5927 if (!JustWarn) { 5928 NewDecl->setInvalidDecl(); 5929 return; 5930 } 5931 } 5932 5933 // A redeclaration is not allowed to drop a dllimport attribute, the only 5934 // exceptions being inline function definitions (except for function 5935 // templates), local extern declarations, qualified friend declarations or 5936 // special MSVC extension: in the last case, the declaration is treated as if 5937 // it were marked dllexport. 5938 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5939 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5940 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5941 // Ignore static data because out-of-line definitions are diagnosed 5942 // separately. 5943 IsStaticDataMember = VD->isStaticDataMember(); 5944 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5945 VarDecl::DeclarationOnly; 5946 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5947 IsInline = FD->isInlined(); 5948 IsQualifiedFriend = FD->getQualifier() && 5949 FD->getFriendObjectKind() == Decl::FOK_Declared; 5950 } 5951 5952 if (OldImportAttr && !HasNewAttr && 5953 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 5954 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5955 if (IsMicrosoft && IsDefinition) { 5956 S.Diag(NewDecl->getLocation(), 5957 diag::warn_redeclaration_without_import_attribute) 5958 << NewDecl; 5959 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5960 NewDecl->dropAttr<DLLImportAttr>(); 5961 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5962 NewImportAttr->getRange(), S.Context, 5963 NewImportAttr->getSpellingListIndex())); 5964 } else { 5965 S.Diag(NewDecl->getLocation(), 5966 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5967 << NewDecl << OldImportAttr; 5968 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5969 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5970 OldDecl->dropAttr<DLLImportAttr>(); 5971 NewDecl->dropAttr<DLLImportAttr>(); 5972 } 5973 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5974 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5975 OldDecl->dropAttr<DLLImportAttr>(); 5976 NewDecl->dropAttr<DLLImportAttr>(); 5977 S.Diag(NewDecl->getLocation(), 5978 diag::warn_dllimport_dropped_from_inline_function) 5979 << NewDecl << OldImportAttr; 5980 } 5981 } 5982 5983 /// Given that we are within the definition of the given function, 5984 /// will that definition behave like C99's 'inline', where the 5985 /// definition is discarded except for optimization purposes? 5986 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5987 // Try to avoid calling GetGVALinkageForFunction. 5988 5989 // All cases of this require the 'inline' keyword. 5990 if (!FD->isInlined()) return false; 5991 5992 // This is only possible in C++ with the gnu_inline attribute. 5993 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5994 return false; 5995 5996 // Okay, go ahead and call the relatively-more-expensive function. 5997 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5998 } 5999 6000 /// Determine whether a variable is extern "C" prior to attaching 6001 /// an initializer. We can't just call isExternC() here, because that 6002 /// will also compute and cache whether the declaration is externally 6003 /// visible, which might change when we attach the initializer. 6004 /// 6005 /// This can only be used if the declaration is known to not be a 6006 /// redeclaration of an internal linkage declaration. 6007 /// 6008 /// For instance: 6009 /// 6010 /// auto x = []{}; 6011 /// 6012 /// Attaching the initializer here makes this declaration not externally 6013 /// visible, because its type has internal linkage. 6014 /// 6015 /// FIXME: This is a hack. 6016 template<typename T> 6017 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6018 if (S.getLangOpts().CPlusPlus) { 6019 // In C++, the overloadable attribute negates the effects of extern "C". 6020 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6021 return false; 6022 6023 // So do CUDA's host/device attributes. 6024 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6025 D->template hasAttr<CUDAHostAttr>())) 6026 return false; 6027 } 6028 return D->isExternC(); 6029 } 6030 6031 static bool shouldConsiderLinkage(const VarDecl *VD) { 6032 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6033 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6034 return VD->hasExternalStorage(); 6035 if (DC->isFileContext()) 6036 return true; 6037 if (DC->isRecord()) 6038 return false; 6039 llvm_unreachable("Unexpected context"); 6040 } 6041 6042 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6043 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6044 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6045 isa<OMPDeclareReductionDecl>(DC)) 6046 return true; 6047 if (DC->isRecord()) 6048 return false; 6049 llvm_unreachable("Unexpected context"); 6050 } 6051 6052 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6053 AttributeList::Kind Kind) { 6054 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6055 if (L->getKind() == Kind) 6056 return true; 6057 return false; 6058 } 6059 6060 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6061 AttributeList::Kind Kind) { 6062 // Check decl attributes on the DeclSpec. 6063 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6064 return true; 6065 6066 // Walk the declarator structure, checking decl attributes that were in a type 6067 // position to the decl itself. 6068 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6069 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6070 return true; 6071 } 6072 6073 // Finally, check attributes on the decl itself. 6074 return hasParsedAttr(S, PD.getAttributes(), Kind); 6075 } 6076 6077 /// Adjust the \c DeclContext for a function or variable that might be a 6078 /// function-local external declaration. 6079 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6080 if (!DC->isFunctionOrMethod()) 6081 return false; 6082 6083 // If this is a local extern function or variable declared within a function 6084 // template, don't add it into the enclosing namespace scope until it is 6085 // instantiated; it might have a dependent type right now. 6086 if (DC->isDependentContext()) 6087 return true; 6088 6089 // C++11 [basic.link]p7: 6090 // When a block scope declaration of an entity with linkage is not found to 6091 // refer to some other declaration, then that entity is a member of the 6092 // innermost enclosing namespace. 6093 // 6094 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6095 // semantically-enclosing namespace, not a lexically-enclosing one. 6096 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6097 DC = DC->getParent(); 6098 return true; 6099 } 6100 6101 /// \brief Returns true if given declaration has external C language linkage. 6102 static bool isDeclExternC(const Decl *D) { 6103 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6104 return FD->isExternC(); 6105 if (const auto *VD = dyn_cast<VarDecl>(D)) 6106 return VD->isExternC(); 6107 6108 llvm_unreachable("Unknown type of decl!"); 6109 } 6110 6111 NamedDecl *Sema::ActOnVariableDeclarator( 6112 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6113 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6114 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6115 QualType R = TInfo->getType(); 6116 DeclarationName Name = GetNameForDeclarator(D).getName(); 6117 6118 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6119 6120 if (D.isDecompositionDeclarator()) { 6121 AddToScope = false; 6122 // Take the name of the first declarator as our name for diagnostic 6123 // purposes. 6124 auto &Decomp = D.getDecompositionDeclarator(); 6125 if (!Decomp.bindings().empty()) { 6126 II = Decomp.bindings()[0].Name; 6127 Name = II; 6128 } 6129 } else if (!II) { 6130 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6131 return nullptr; 6132 } 6133 6134 if (getLangOpts().OpenCL) { 6135 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6136 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6137 // argument. 6138 if (R->isImageType() || R->isPipeType()) { 6139 Diag(D.getIdentifierLoc(), 6140 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6141 << R; 6142 D.setInvalidType(); 6143 return nullptr; 6144 } 6145 6146 // OpenCL v1.2 s6.9.r: 6147 // The event type cannot be used to declare a program scope variable. 6148 // OpenCL v2.0 s6.9.q: 6149 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6150 if (NULL == S->getParent()) { 6151 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6152 Diag(D.getIdentifierLoc(), 6153 diag::err_invalid_type_for_program_scope_var) << R; 6154 D.setInvalidType(); 6155 return nullptr; 6156 } 6157 } 6158 6159 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6160 QualType NR = R; 6161 while (NR->isPointerType()) { 6162 if (NR->isFunctionPointerType()) { 6163 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 6164 D.setInvalidType(); 6165 break; 6166 } 6167 NR = NR->getPointeeType(); 6168 } 6169 6170 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6171 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6172 // half array type (unless the cl_khr_fp16 extension is enabled). 6173 if (Context.getBaseElementType(R)->isHalfType()) { 6174 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6175 D.setInvalidType(); 6176 } 6177 } 6178 6179 if (R->isSamplerT()) { 6180 // OpenCL v1.2 s6.9.b p4: 6181 // The sampler type cannot be used with the __local and __global address 6182 // space qualifiers. 6183 if (R.getAddressSpace() == LangAS::opencl_local || 6184 R.getAddressSpace() == LangAS::opencl_global) { 6185 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6186 } 6187 6188 // OpenCL v1.2 s6.12.14.1: 6189 // A global sampler must be declared with either the constant address 6190 // space qualifier or with the const qualifier. 6191 if (DC->isTranslationUnit() && 6192 !(R.getAddressSpace() == LangAS::opencl_constant || 6193 R.isConstQualified())) { 6194 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6195 D.setInvalidType(); 6196 } 6197 } 6198 6199 // OpenCL v1.2 s6.9.r: 6200 // The event type cannot be used with the __local, __constant and __global 6201 // address space qualifiers. 6202 if (R->isEventT()) { 6203 if (R.getAddressSpace()) { 6204 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6205 D.setInvalidType(); 6206 } 6207 } 6208 } 6209 6210 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6211 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6212 6213 // dllimport globals without explicit storage class are treated as extern. We 6214 // have to change the storage class this early to get the right DeclContext. 6215 if (SC == SC_None && !DC->isRecord() && 6216 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6217 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6218 SC = SC_Extern; 6219 6220 DeclContext *OriginalDC = DC; 6221 bool IsLocalExternDecl = SC == SC_Extern && 6222 adjustContextForLocalExternDecl(DC); 6223 6224 if (SCSpec == DeclSpec::SCS_mutable) { 6225 // mutable can only appear on non-static class members, so it's always 6226 // an error here 6227 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6228 D.setInvalidType(); 6229 SC = SC_None; 6230 } 6231 6232 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6233 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6234 D.getDeclSpec().getStorageClassSpecLoc())) { 6235 // In C++11, the 'register' storage class specifier is deprecated. 6236 // Suppress the warning in system macros, it's used in macros in some 6237 // popular C system headers, such as in glibc's htonl() macro. 6238 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6239 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6240 : diag::warn_deprecated_register) 6241 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6242 } 6243 6244 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6245 6246 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6247 // C99 6.9p2: The storage-class specifiers auto and register shall not 6248 // appear in the declaration specifiers in an external declaration. 6249 // Global Register+Asm is a GNU extension we support. 6250 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6251 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6252 D.setInvalidType(); 6253 } 6254 } 6255 6256 bool IsMemberSpecialization = false; 6257 bool IsVariableTemplateSpecialization = false; 6258 bool IsPartialSpecialization = false; 6259 bool IsVariableTemplate = false; 6260 VarDecl *NewVD = nullptr; 6261 VarTemplateDecl *NewTemplate = nullptr; 6262 TemplateParameterList *TemplateParams = nullptr; 6263 if (!getLangOpts().CPlusPlus) { 6264 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6265 D.getIdentifierLoc(), II, 6266 R, TInfo, SC); 6267 6268 if (R->getContainedDeducedType()) 6269 ParsingInitForAutoVars.insert(NewVD); 6270 6271 if (D.isInvalidType()) 6272 NewVD->setInvalidDecl(); 6273 } else { 6274 bool Invalid = false; 6275 6276 if (DC->isRecord() && !CurContext->isRecord()) { 6277 // This is an out-of-line definition of a static data member. 6278 switch (SC) { 6279 case SC_None: 6280 break; 6281 case SC_Static: 6282 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6283 diag::err_static_out_of_line) 6284 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6285 break; 6286 case SC_Auto: 6287 case SC_Register: 6288 case SC_Extern: 6289 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6290 // to names of variables declared in a block or to function parameters. 6291 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6292 // of class members 6293 6294 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6295 diag::err_storage_class_for_static_member) 6296 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6297 break; 6298 case SC_PrivateExtern: 6299 llvm_unreachable("C storage class in c++!"); 6300 } 6301 } 6302 6303 if (SC == SC_Static && CurContext->isRecord()) { 6304 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6305 if (RD->isLocalClass()) 6306 Diag(D.getIdentifierLoc(), 6307 diag::err_static_data_member_not_allowed_in_local_class) 6308 << Name << RD->getDeclName(); 6309 6310 // C++98 [class.union]p1: If a union contains a static data member, 6311 // the program is ill-formed. C++11 drops this restriction. 6312 if (RD->isUnion()) 6313 Diag(D.getIdentifierLoc(), 6314 getLangOpts().CPlusPlus11 6315 ? diag::warn_cxx98_compat_static_data_member_in_union 6316 : diag::ext_static_data_member_in_union) << Name; 6317 // We conservatively disallow static data members in anonymous structs. 6318 else if (!RD->getDeclName()) 6319 Diag(D.getIdentifierLoc(), 6320 diag::err_static_data_member_not_allowed_in_anon_struct) 6321 << Name << RD->isUnion(); 6322 } 6323 } 6324 6325 // Match up the template parameter lists with the scope specifier, then 6326 // determine whether we have a template or a template specialization. 6327 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6328 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6329 D.getCXXScopeSpec(), 6330 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6331 ? D.getName().TemplateId 6332 : nullptr, 6333 TemplateParamLists, 6334 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6335 6336 if (TemplateParams) { 6337 if (!TemplateParams->size() && 6338 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6339 // There is an extraneous 'template<>' for this variable. Complain 6340 // about it, but allow the declaration of the variable. 6341 Diag(TemplateParams->getTemplateLoc(), 6342 diag::err_template_variable_noparams) 6343 << II 6344 << SourceRange(TemplateParams->getTemplateLoc(), 6345 TemplateParams->getRAngleLoc()); 6346 TemplateParams = nullptr; 6347 } else { 6348 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6349 // This is an explicit specialization or a partial specialization. 6350 // FIXME: Check that we can declare a specialization here. 6351 IsVariableTemplateSpecialization = true; 6352 IsPartialSpecialization = TemplateParams->size() > 0; 6353 } else { // if (TemplateParams->size() > 0) 6354 // This is a template declaration. 6355 IsVariableTemplate = true; 6356 6357 // Check that we can declare a template here. 6358 if (CheckTemplateDeclScope(S, TemplateParams)) 6359 return nullptr; 6360 6361 // Only C++1y supports variable templates (N3651). 6362 Diag(D.getIdentifierLoc(), 6363 getLangOpts().CPlusPlus14 6364 ? diag::warn_cxx11_compat_variable_template 6365 : diag::ext_variable_template); 6366 } 6367 } 6368 } else { 6369 assert( 6370 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6371 "should have a 'template<>' for this decl"); 6372 } 6373 6374 if (IsVariableTemplateSpecialization) { 6375 SourceLocation TemplateKWLoc = 6376 TemplateParamLists.size() > 0 6377 ? TemplateParamLists[0]->getTemplateLoc() 6378 : SourceLocation(); 6379 DeclResult Res = ActOnVarTemplateSpecialization( 6380 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6381 IsPartialSpecialization); 6382 if (Res.isInvalid()) 6383 return nullptr; 6384 NewVD = cast<VarDecl>(Res.get()); 6385 AddToScope = false; 6386 } else if (D.isDecompositionDeclarator()) { 6387 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6388 D.getIdentifierLoc(), R, TInfo, SC, 6389 Bindings); 6390 } else 6391 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6392 D.getIdentifierLoc(), II, R, TInfo, SC); 6393 6394 // If this is supposed to be a variable template, create it as such. 6395 if (IsVariableTemplate) { 6396 NewTemplate = 6397 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6398 TemplateParams, NewVD); 6399 NewVD->setDescribedVarTemplate(NewTemplate); 6400 } 6401 6402 // If this decl has an auto type in need of deduction, make a note of the 6403 // Decl so we can diagnose uses of it in its own initializer. 6404 if (R->getContainedDeducedType()) 6405 ParsingInitForAutoVars.insert(NewVD); 6406 6407 if (D.isInvalidType() || Invalid) { 6408 NewVD->setInvalidDecl(); 6409 if (NewTemplate) 6410 NewTemplate->setInvalidDecl(); 6411 } 6412 6413 SetNestedNameSpecifier(NewVD, D); 6414 6415 // If we have any template parameter lists that don't directly belong to 6416 // the variable (matching the scope specifier), store them. 6417 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6418 if (TemplateParamLists.size() > VDTemplateParamLists) 6419 NewVD->setTemplateParameterListsInfo( 6420 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6421 6422 if (D.getDeclSpec().isConstexprSpecified()) { 6423 NewVD->setConstexpr(true); 6424 // C++1z [dcl.spec.constexpr]p1: 6425 // A static data member declared with the constexpr specifier is 6426 // implicitly an inline variable. 6427 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6428 NewVD->setImplicitlyInline(); 6429 } 6430 6431 if (D.getDeclSpec().isConceptSpecified()) { 6432 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6433 VTD->setConcept(); 6434 6435 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6436 // be declared with the thread_local, inline, friend, or constexpr 6437 // specifiers, [...] 6438 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6439 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6440 diag::err_concept_decl_invalid_specifiers) 6441 << 0 << 0; 6442 NewVD->setInvalidDecl(true); 6443 } 6444 6445 if (D.getDeclSpec().isConstexprSpecified()) { 6446 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6447 diag::err_concept_decl_invalid_specifiers) 6448 << 0 << 3; 6449 NewVD->setInvalidDecl(true); 6450 } 6451 6452 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6453 // applied only to the definition of a function template or variable 6454 // template, declared in namespace scope. 6455 if (IsVariableTemplateSpecialization) { 6456 Diag(D.getDeclSpec().getConceptSpecLoc(), 6457 diag::err_concept_specified_specialization) 6458 << (IsPartialSpecialization ? 2 : 1); 6459 } 6460 6461 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6462 // following restrictions: 6463 // - The declared type shall have the type bool. 6464 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6465 !NewVD->isInvalidDecl()) { 6466 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6467 NewVD->setInvalidDecl(true); 6468 } 6469 } 6470 } 6471 6472 if (D.getDeclSpec().isInlineSpecified()) { 6473 if (!getLangOpts().CPlusPlus) { 6474 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6475 << 0; 6476 } else if (CurContext->isFunctionOrMethod()) { 6477 // 'inline' is not allowed on block scope variable declaration. 6478 Diag(D.getDeclSpec().getInlineSpecLoc(), 6479 diag::err_inline_declaration_block_scope) << Name 6480 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6481 } else { 6482 Diag(D.getDeclSpec().getInlineSpecLoc(), 6483 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6484 : diag::ext_inline_variable); 6485 NewVD->setInlineSpecified(); 6486 } 6487 } 6488 6489 // Set the lexical context. If the declarator has a C++ scope specifier, the 6490 // lexical context will be different from the semantic context. 6491 NewVD->setLexicalDeclContext(CurContext); 6492 if (NewTemplate) 6493 NewTemplate->setLexicalDeclContext(CurContext); 6494 6495 if (IsLocalExternDecl) { 6496 if (D.isDecompositionDeclarator()) 6497 for (auto *B : Bindings) 6498 B->setLocalExternDecl(); 6499 else 6500 NewVD->setLocalExternDecl(); 6501 } 6502 6503 bool EmitTLSUnsupportedError = false; 6504 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6505 // C++11 [dcl.stc]p4: 6506 // When thread_local is applied to a variable of block scope the 6507 // storage-class-specifier static is implied if it does not appear 6508 // explicitly. 6509 // Core issue: 'static' is not implied if the variable is declared 6510 // 'extern'. 6511 if (NewVD->hasLocalStorage() && 6512 (SCSpec != DeclSpec::SCS_unspecified || 6513 TSCS != DeclSpec::TSCS_thread_local || 6514 !DC->isFunctionOrMethod())) 6515 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6516 diag::err_thread_non_global) 6517 << DeclSpec::getSpecifierName(TSCS); 6518 else if (!Context.getTargetInfo().isTLSSupported()) { 6519 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6520 // Postpone error emission until we've collected attributes required to 6521 // figure out whether it's a host or device variable and whether the 6522 // error should be ignored. 6523 EmitTLSUnsupportedError = true; 6524 // We still need to mark the variable as TLS so it shows up in AST with 6525 // proper storage class for other tools to use even if we're not going 6526 // to emit any code for it. 6527 NewVD->setTSCSpec(TSCS); 6528 } else 6529 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6530 diag::err_thread_unsupported); 6531 } else 6532 NewVD->setTSCSpec(TSCS); 6533 } 6534 6535 // C99 6.7.4p3 6536 // An inline definition of a function with external linkage shall 6537 // not contain a definition of a modifiable object with static or 6538 // thread storage duration... 6539 // We only apply this when the function is required to be defined 6540 // elsewhere, i.e. when the function is not 'extern inline'. Note 6541 // that a local variable with thread storage duration still has to 6542 // be marked 'static'. Also note that it's possible to get these 6543 // semantics in C++ using __attribute__((gnu_inline)). 6544 if (SC == SC_Static && S->getFnParent() != nullptr && 6545 !NewVD->getType().isConstQualified()) { 6546 FunctionDecl *CurFD = getCurFunctionDecl(); 6547 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6548 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6549 diag::warn_static_local_in_extern_inline); 6550 MaybeSuggestAddingStaticToDecl(CurFD); 6551 } 6552 } 6553 6554 if (D.getDeclSpec().isModulePrivateSpecified()) { 6555 if (IsVariableTemplateSpecialization) 6556 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6557 << (IsPartialSpecialization ? 1 : 0) 6558 << FixItHint::CreateRemoval( 6559 D.getDeclSpec().getModulePrivateSpecLoc()); 6560 else if (IsMemberSpecialization) 6561 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6562 << 2 6563 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6564 else if (NewVD->hasLocalStorage()) 6565 Diag(NewVD->getLocation(), diag::err_module_private_local) 6566 << 0 << NewVD->getDeclName() 6567 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6568 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6569 else { 6570 NewVD->setModulePrivate(); 6571 if (NewTemplate) 6572 NewTemplate->setModulePrivate(); 6573 for (auto *B : Bindings) 6574 B->setModulePrivate(); 6575 } 6576 } 6577 6578 // Handle attributes prior to checking for duplicates in MergeVarDecl 6579 ProcessDeclAttributes(S, NewVD, D); 6580 6581 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6582 if (EmitTLSUnsupportedError && 6583 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6584 (getLangOpts().OpenMPIsDevice && 6585 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6586 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6587 diag::err_thread_unsupported); 6588 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6589 // storage [duration]." 6590 if (SC == SC_None && S->getFnParent() != nullptr && 6591 (NewVD->hasAttr<CUDASharedAttr>() || 6592 NewVD->hasAttr<CUDAConstantAttr>())) { 6593 NewVD->setStorageClass(SC_Static); 6594 } 6595 } 6596 6597 // Ensure that dllimport globals without explicit storage class are treated as 6598 // extern. The storage class is set above using parsed attributes. Now we can 6599 // check the VarDecl itself. 6600 assert(!NewVD->hasAttr<DLLImportAttr>() || 6601 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6602 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6603 6604 // In auto-retain/release, infer strong retension for variables of 6605 // retainable type. 6606 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6607 NewVD->setInvalidDecl(); 6608 6609 // Handle GNU asm-label extension (encoded as an attribute). 6610 if (Expr *E = (Expr*)D.getAsmLabel()) { 6611 // The parser guarantees this is a string. 6612 StringLiteral *SE = cast<StringLiteral>(E); 6613 StringRef Label = SE->getString(); 6614 if (S->getFnParent() != nullptr) { 6615 switch (SC) { 6616 case SC_None: 6617 case SC_Auto: 6618 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6619 break; 6620 case SC_Register: 6621 // Local Named register 6622 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6623 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6624 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6625 break; 6626 case SC_Static: 6627 case SC_Extern: 6628 case SC_PrivateExtern: 6629 break; 6630 } 6631 } else if (SC == SC_Register) { 6632 // Global Named register 6633 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6634 const auto &TI = Context.getTargetInfo(); 6635 bool HasSizeMismatch; 6636 6637 if (!TI.isValidGCCRegisterName(Label)) 6638 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6639 else if (!TI.validateGlobalRegisterVariable(Label, 6640 Context.getTypeSize(R), 6641 HasSizeMismatch)) 6642 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6643 else if (HasSizeMismatch) 6644 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6645 } 6646 6647 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6648 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6649 NewVD->setInvalidDecl(true); 6650 } 6651 } 6652 6653 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6654 Context, Label, 0)); 6655 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6656 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6657 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6658 if (I != ExtnameUndeclaredIdentifiers.end()) { 6659 if (isDeclExternC(NewVD)) { 6660 NewVD->addAttr(I->second); 6661 ExtnameUndeclaredIdentifiers.erase(I); 6662 } else 6663 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6664 << /*Variable*/1 << NewVD; 6665 } 6666 } 6667 6668 // Find the shadowed declaration before filtering for scope. 6669 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6670 ? getShadowedDeclaration(NewVD, Previous) 6671 : nullptr; 6672 6673 // Don't consider existing declarations that are in a different 6674 // scope and are out-of-semantic-context declarations (if the new 6675 // declaration has linkage). 6676 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6677 D.getCXXScopeSpec().isNotEmpty() || 6678 IsMemberSpecialization || 6679 IsVariableTemplateSpecialization); 6680 6681 // Check whether the previous declaration is in the same block scope. This 6682 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6683 if (getLangOpts().CPlusPlus && 6684 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6685 NewVD->setPreviousDeclInSameBlockScope( 6686 Previous.isSingleResult() && !Previous.isShadowed() && 6687 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6688 6689 if (!getLangOpts().CPlusPlus) { 6690 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6691 } else { 6692 // If this is an explicit specialization of a static data member, check it. 6693 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6694 CheckMemberSpecialization(NewVD, Previous)) 6695 NewVD->setInvalidDecl(); 6696 6697 // Merge the decl with the existing one if appropriate. 6698 if (!Previous.empty()) { 6699 if (Previous.isSingleResult() && 6700 isa<FieldDecl>(Previous.getFoundDecl()) && 6701 D.getCXXScopeSpec().isSet()) { 6702 // The user tried to define a non-static data member 6703 // out-of-line (C++ [dcl.meaning]p1). 6704 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6705 << D.getCXXScopeSpec().getRange(); 6706 Previous.clear(); 6707 NewVD->setInvalidDecl(); 6708 } 6709 } else if (D.getCXXScopeSpec().isSet()) { 6710 // No previous declaration in the qualifying scope. 6711 Diag(D.getIdentifierLoc(), diag::err_no_member) 6712 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6713 << D.getCXXScopeSpec().getRange(); 6714 NewVD->setInvalidDecl(); 6715 } 6716 6717 if (!IsVariableTemplateSpecialization) 6718 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6719 6720 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6721 // an explicit specialization (14.8.3) or a partial specialization of a 6722 // concept definition. 6723 if (IsVariableTemplateSpecialization && 6724 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6725 Previous.isSingleResult()) { 6726 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6727 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6728 if (VarTmpl->isConcept()) { 6729 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6730 << 1 /*variable*/ 6731 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6732 : 1 /*explicitly specialized*/); 6733 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6734 NewVD->setInvalidDecl(); 6735 } 6736 } 6737 } 6738 6739 if (NewTemplate) { 6740 VarTemplateDecl *PrevVarTemplate = 6741 NewVD->getPreviousDecl() 6742 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6743 : nullptr; 6744 6745 // Check the template parameter list of this declaration, possibly 6746 // merging in the template parameter list from the previous variable 6747 // template declaration. 6748 if (CheckTemplateParameterList( 6749 TemplateParams, 6750 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6751 : nullptr, 6752 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6753 DC->isDependentContext()) 6754 ? TPC_ClassTemplateMember 6755 : TPC_VarTemplate)) 6756 NewVD->setInvalidDecl(); 6757 6758 // If we are providing an explicit specialization of a static variable 6759 // template, make a note of that. 6760 if (PrevVarTemplate && 6761 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6762 PrevVarTemplate->setMemberSpecialization(); 6763 } 6764 } 6765 6766 // Diagnose shadowed variables iff this isn't a redeclaration. 6767 if (ShadowedDecl && !D.isRedeclaration()) 6768 CheckShadow(NewVD, ShadowedDecl, Previous); 6769 6770 ProcessPragmaWeak(S, NewVD); 6771 6772 // If this is the first declaration of an extern C variable, update 6773 // the map of such variables. 6774 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6775 isIncompleteDeclExternC(*this, NewVD)) 6776 RegisterLocallyScopedExternCDecl(NewVD, S); 6777 6778 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6779 Decl *ManglingContextDecl; 6780 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6781 NewVD->getDeclContext(), ManglingContextDecl)) { 6782 Context.setManglingNumber( 6783 NewVD, MCtx->getManglingNumber( 6784 NewVD, getMSManglingNumber(getLangOpts(), S))); 6785 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6786 } 6787 } 6788 6789 // Special handling of variable named 'main'. 6790 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6791 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6792 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6793 6794 // C++ [basic.start.main]p3 6795 // A program that declares a variable main at global scope is ill-formed. 6796 if (getLangOpts().CPlusPlus) 6797 Diag(D.getLocStart(), diag::err_main_global_variable); 6798 6799 // In C, and external-linkage variable named main results in undefined 6800 // behavior. 6801 else if (NewVD->hasExternalFormalLinkage()) 6802 Diag(D.getLocStart(), diag::warn_main_redefined); 6803 } 6804 6805 if (D.isRedeclaration() && !Previous.empty()) { 6806 checkDLLAttributeRedeclaration( 6807 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6808 IsMemberSpecialization, D.isFunctionDefinition()); 6809 } 6810 6811 if (NewTemplate) { 6812 if (NewVD->isInvalidDecl()) 6813 NewTemplate->setInvalidDecl(); 6814 ActOnDocumentableDecl(NewTemplate); 6815 return NewTemplate; 6816 } 6817 6818 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6819 CompleteMemberSpecialization(NewVD, Previous); 6820 6821 return NewVD; 6822 } 6823 6824 /// Enum describing the %select options in diag::warn_decl_shadow. 6825 enum ShadowedDeclKind { 6826 SDK_Local, 6827 SDK_Global, 6828 SDK_StaticMember, 6829 SDK_Field, 6830 SDK_Typedef, 6831 SDK_Using 6832 }; 6833 6834 /// Determine what kind of declaration we're shadowing. 6835 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6836 const DeclContext *OldDC) { 6837 if (isa<TypeAliasDecl>(ShadowedDecl)) 6838 return SDK_Using; 6839 else if (isa<TypedefDecl>(ShadowedDecl)) 6840 return SDK_Typedef; 6841 else if (isa<RecordDecl>(OldDC)) 6842 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6843 6844 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6845 } 6846 6847 /// Return the location of the capture if the given lambda captures the given 6848 /// variable \p VD, or an invalid source location otherwise. 6849 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6850 const VarDecl *VD) { 6851 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6852 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6853 return Capture.getLocation(); 6854 } 6855 return SourceLocation(); 6856 } 6857 6858 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6859 const LookupResult &R) { 6860 // Only diagnose if we're shadowing an unambiguous field or variable. 6861 if (R.getResultKind() != LookupResult::Found) 6862 return false; 6863 6864 // Return false if warning is ignored. 6865 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6866 } 6867 6868 /// \brief Return the declaration shadowed by the given variable \p D, or null 6869 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6870 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6871 const LookupResult &R) { 6872 if (!shouldWarnIfShadowedDecl(Diags, R)) 6873 return nullptr; 6874 6875 // Don't diagnose declarations at file scope. 6876 if (D->hasGlobalStorage()) 6877 return nullptr; 6878 6879 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6880 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6881 ? ShadowedDecl 6882 : nullptr; 6883 } 6884 6885 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6886 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6887 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6888 const LookupResult &R) { 6889 // Don't warn if typedef declaration is part of a class 6890 if (D->getDeclContext()->isRecord()) 6891 return nullptr; 6892 6893 if (!shouldWarnIfShadowedDecl(Diags, R)) 6894 return nullptr; 6895 6896 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6897 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6898 } 6899 6900 /// \brief Diagnose variable or built-in function shadowing. Implements 6901 /// -Wshadow. 6902 /// 6903 /// This method is called whenever a VarDecl is added to a "useful" 6904 /// scope. 6905 /// 6906 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6907 /// \param R the lookup of the name 6908 /// 6909 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 6910 const LookupResult &R) { 6911 DeclContext *NewDC = D->getDeclContext(); 6912 6913 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6914 // Fields are not shadowed by variables in C++ static methods. 6915 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6916 if (MD->isStatic()) 6917 return; 6918 6919 // Fields shadowed by constructor parameters are a special case. Usually 6920 // the constructor initializes the field with the parameter. 6921 if (isa<CXXConstructorDecl>(NewDC)) 6922 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 6923 // Remember that this was shadowed so we can either warn about its 6924 // modification or its existence depending on warning settings. 6925 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 6926 return; 6927 } 6928 } 6929 6930 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6931 if (shadowedVar->isExternC()) { 6932 // For shadowing external vars, make sure that we point to the global 6933 // declaration, not a locally scoped extern declaration. 6934 for (auto I : shadowedVar->redecls()) 6935 if (I->isFileVarDecl()) { 6936 ShadowedDecl = I; 6937 break; 6938 } 6939 } 6940 6941 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 6942 6943 unsigned WarningDiag = diag::warn_decl_shadow; 6944 SourceLocation CaptureLoc; 6945 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 6946 isa<CXXMethodDecl>(NewDC)) { 6947 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6948 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6949 if (RD->getLambdaCaptureDefault() == LCD_None) { 6950 // Try to avoid warnings for lambdas with an explicit capture list. 6951 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6952 // Warn only when the lambda captures the shadowed decl explicitly. 6953 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 6954 if (CaptureLoc.isInvalid()) 6955 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 6956 } else { 6957 // Remember that this was shadowed so we can avoid the warning if the 6958 // shadowed decl isn't captured and the warning settings allow it. 6959 cast<LambdaScopeInfo>(getCurFunction()) 6960 ->ShadowingDecls.push_back( 6961 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 6962 return; 6963 } 6964 } 6965 } 6966 } 6967 6968 // Only warn about certain kinds of shadowing for class members. 6969 if (NewDC && NewDC->isRecord()) { 6970 // In particular, don't warn about shadowing non-class members. 6971 if (!OldDC->isRecord()) 6972 return; 6973 6974 // TODO: should we warn about static data members shadowing 6975 // static data members from base classes? 6976 6977 // TODO: don't diagnose for inaccessible shadowed members. 6978 // This is hard to do perfectly because we might friend the 6979 // shadowing context, but that's just a false negative. 6980 } 6981 6982 6983 DeclarationName Name = R.getLookupName(); 6984 6985 // Emit warning and note. 6986 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6987 return; 6988 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6989 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 6990 if (!CaptureLoc.isInvalid()) 6991 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6992 << Name << /*explicitly*/ 1; 6993 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6994 } 6995 6996 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 6997 /// when these variables are captured by the lambda. 6998 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 6999 for (const auto &Shadow : LSI->ShadowingDecls) { 7000 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7001 // Try to avoid the warning when the shadowed decl isn't captured. 7002 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7003 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7004 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7005 ? diag::warn_decl_shadow_uncaptured_local 7006 : diag::warn_decl_shadow) 7007 << Shadow.VD->getDeclName() 7008 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7009 if (!CaptureLoc.isInvalid()) 7010 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7011 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7012 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7013 } 7014 } 7015 7016 /// \brief Check -Wshadow without the advantage of a previous lookup. 7017 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7018 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7019 return; 7020 7021 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7022 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 7023 LookupName(R, S); 7024 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7025 CheckShadow(D, ShadowedDecl, R); 7026 } 7027 7028 /// Check if 'E', which is an expression that is about to be modified, refers 7029 /// to a constructor parameter that shadows a field. 7030 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7031 // Quickly ignore expressions that can't be shadowing ctor parameters. 7032 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7033 return; 7034 E = E->IgnoreParenImpCasts(); 7035 auto *DRE = dyn_cast<DeclRefExpr>(E); 7036 if (!DRE) 7037 return; 7038 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7039 auto I = ShadowingDecls.find(D); 7040 if (I == ShadowingDecls.end()) 7041 return; 7042 const NamedDecl *ShadowedDecl = I->second; 7043 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7044 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7045 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7046 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7047 7048 // Avoid issuing multiple warnings about the same decl. 7049 ShadowingDecls.erase(I); 7050 } 7051 7052 /// Check for conflict between this global or extern "C" declaration and 7053 /// previous global or extern "C" declarations. This is only used in C++. 7054 template<typename T> 7055 static bool checkGlobalOrExternCConflict( 7056 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7057 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7058 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7059 7060 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7061 // The common case: this global doesn't conflict with any extern "C" 7062 // declaration. 7063 return false; 7064 } 7065 7066 if (Prev) { 7067 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7068 // Both the old and new declarations have C language linkage. This is a 7069 // redeclaration. 7070 Previous.clear(); 7071 Previous.addDecl(Prev); 7072 return true; 7073 } 7074 7075 // This is a global, non-extern "C" declaration, and there is a previous 7076 // non-global extern "C" declaration. Diagnose if this is a variable 7077 // declaration. 7078 if (!isa<VarDecl>(ND)) 7079 return false; 7080 } else { 7081 // The declaration is extern "C". Check for any declaration in the 7082 // translation unit which might conflict. 7083 if (IsGlobal) { 7084 // We have already performed the lookup into the translation unit. 7085 IsGlobal = false; 7086 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7087 I != E; ++I) { 7088 if (isa<VarDecl>(*I)) { 7089 Prev = *I; 7090 break; 7091 } 7092 } 7093 } else { 7094 DeclContext::lookup_result R = 7095 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7096 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7097 I != E; ++I) { 7098 if (isa<VarDecl>(*I)) { 7099 Prev = *I; 7100 break; 7101 } 7102 // FIXME: If we have any other entity with this name in global scope, 7103 // the declaration is ill-formed, but that is a defect: it breaks the 7104 // 'stat' hack, for instance. Only variables can have mangled name 7105 // clashes with extern "C" declarations, so only they deserve a 7106 // diagnostic. 7107 } 7108 } 7109 7110 if (!Prev) 7111 return false; 7112 } 7113 7114 // Use the first declaration's location to ensure we point at something which 7115 // is lexically inside an extern "C" linkage-spec. 7116 assert(Prev && "should have found a previous declaration to diagnose"); 7117 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7118 Prev = FD->getFirstDecl(); 7119 else 7120 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7121 7122 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7123 << IsGlobal << ND; 7124 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7125 << IsGlobal; 7126 return false; 7127 } 7128 7129 /// Apply special rules for handling extern "C" declarations. Returns \c true 7130 /// if we have found that this is a redeclaration of some prior entity. 7131 /// 7132 /// Per C++ [dcl.link]p6: 7133 /// Two declarations [for a function or variable] with C language linkage 7134 /// with the same name that appear in different scopes refer to the same 7135 /// [entity]. An entity with C language linkage shall not be declared with 7136 /// the same name as an entity in global scope. 7137 template<typename T> 7138 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7139 LookupResult &Previous) { 7140 if (!S.getLangOpts().CPlusPlus) { 7141 // In C, when declaring a global variable, look for a corresponding 'extern' 7142 // variable declared in function scope. We don't need this in C++, because 7143 // we find local extern decls in the surrounding file-scope DeclContext. 7144 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7145 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7146 Previous.clear(); 7147 Previous.addDecl(Prev); 7148 return true; 7149 } 7150 } 7151 return false; 7152 } 7153 7154 // A declaration in the translation unit can conflict with an extern "C" 7155 // declaration. 7156 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7157 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7158 7159 // An extern "C" declaration can conflict with a declaration in the 7160 // translation unit or can be a redeclaration of an extern "C" declaration 7161 // in another scope. 7162 if (isIncompleteDeclExternC(S,ND)) 7163 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7164 7165 // Neither global nor extern "C": nothing to do. 7166 return false; 7167 } 7168 7169 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7170 // If the decl is already known invalid, don't check it. 7171 if (NewVD->isInvalidDecl()) 7172 return; 7173 7174 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7175 QualType T = TInfo->getType(); 7176 7177 // Defer checking an 'auto' type until its initializer is attached. 7178 if (T->isUndeducedType()) 7179 return; 7180 7181 if (NewVD->hasAttrs()) 7182 CheckAlignasUnderalignment(NewVD); 7183 7184 if (T->isObjCObjectType()) { 7185 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7186 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7187 T = Context.getObjCObjectPointerType(T); 7188 NewVD->setType(T); 7189 } 7190 7191 // Emit an error if an address space was applied to decl with local storage. 7192 // This includes arrays of objects with address space qualifiers, but not 7193 // automatic variables that point to other address spaces. 7194 // ISO/IEC TR 18037 S5.1.2 7195 if (!getLangOpts().OpenCL 7196 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 7197 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7198 NewVD->setInvalidDecl(); 7199 return; 7200 } 7201 7202 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7203 // scope. 7204 if (getLangOpts().OpenCLVersion == 120 && 7205 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7206 NewVD->isStaticLocal()) { 7207 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7208 NewVD->setInvalidDecl(); 7209 return; 7210 } 7211 7212 if (getLangOpts().OpenCL) { 7213 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7214 if (NewVD->hasAttr<BlocksAttr>()) { 7215 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7216 return; 7217 } 7218 7219 if (T->isBlockPointerType()) { 7220 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7221 // can't use 'extern' storage class. 7222 if (!T.isConstQualified()) { 7223 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7224 << 0 /*const*/; 7225 NewVD->setInvalidDecl(); 7226 return; 7227 } 7228 if (NewVD->hasExternalStorage()) { 7229 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7230 NewVD->setInvalidDecl(); 7231 return; 7232 } 7233 } 7234 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7235 // __constant address space. 7236 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7237 // variables inside a function can also be declared in the global 7238 // address space. 7239 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7240 NewVD->hasExternalStorage()) { 7241 if (!T->isSamplerT() && 7242 !(T.getAddressSpace() == LangAS::opencl_constant || 7243 (T.getAddressSpace() == LangAS::opencl_global && 7244 getLangOpts().OpenCLVersion == 200))) { 7245 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7246 if (getLangOpts().OpenCLVersion == 200) 7247 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7248 << Scope << "global or constant"; 7249 else 7250 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7251 << Scope << "constant"; 7252 NewVD->setInvalidDecl(); 7253 return; 7254 } 7255 } else { 7256 if (T.getAddressSpace() == LangAS::opencl_global) { 7257 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7258 << 1 /*is any function*/ << "global"; 7259 NewVD->setInvalidDecl(); 7260 return; 7261 } 7262 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 7263 // in functions. 7264 if (T.getAddressSpace() == LangAS::opencl_constant || 7265 T.getAddressSpace() == LangAS::opencl_local) { 7266 FunctionDecl *FD = getCurFunctionDecl(); 7267 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7268 if (T.getAddressSpace() == LangAS::opencl_constant) 7269 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7270 << 0 /*non-kernel only*/ << "constant"; 7271 else 7272 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7273 << 0 /*non-kernel only*/ << "local"; 7274 NewVD->setInvalidDecl(); 7275 return; 7276 } 7277 } else if (T.getAddressSpace() != LangAS::Default) { 7278 // Do not allow other address spaces on automatic variable. 7279 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7280 NewVD->setInvalidDecl(); 7281 return; 7282 } 7283 } 7284 } 7285 7286 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7287 && !NewVD->hasAttr<BlocksAttr>()) { 7288 if (getLangOpts().getGC() != LangOptions::NonGC) 7289 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7290 else { 7291 assert(!getLangOpts().ObjCAutoRefCount); 7292 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7293 } 7294 } 7295 7296 bool isVM = T->isVariablyModifiedType(); 7297 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7298 NewVD->hasAttr<BlocksAttr>()) 7299 getCurFunction()->setHasBranchProtectedScope(); 7300 7301 if ((isVM && NewVD->hasLinkage()) || 7302 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7303 bool SizeIsNegative; 7304 llvm::APSInt Oversized; 7305 TypeSourceInfo *FixedTInfo = 7306 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7307 SizeIsNegative, Oversized); 7308 if (!FixedTInfo && T->isVariableArrayType()) { 7309 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7310 // FIXME: This won't give the correct result for 7311 // int a[10][n]; 7312 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7313 7314 if (NewVD->isFileVarDecl()) 7315 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7316 << SizeRange; 7317 else if (NewVD->isStaticLocal()) 7318 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7319 << SizeRange; 7320 else 7321 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7322 << SizeRange; 7323 NewVD->setInvalidDecl(); 7324 return; 7325 } 7326 7327 if (!FixedTInfo) { 7328 if (NewVD->isFileVarDecl()) 7329 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7330 else 7331 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7332 NewVD->setInvalidDecl(); 7333 return; 7334 } 7335 7336 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7337 NewVD->setType(FixedTInfo->getType()); 7338 NewVD->setTypeSourceInfo(FixedTInfo); 7339 } 7340 7341 if (T->isVoidType()) { 7342 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7343 // of objects and functions. 7344 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7345 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7346 << T; 7347 NewVD->setInvalidDecl(); 7348 return; 7349 } 7350 } 7351 7352 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7353 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7354 NewVD->setInvalidDecl(); 7355 return; 7356 } 7357 7358 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7359 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7360 NewVD->setInvalidDecl(); 7361 return; 7362 } 7363 7364 if (NewVD->isConstexpr() && !T->isDependentType() && 7365 RequireLiteralType(NewVD->getLocation(), T, 7366 diag::err_constexpr_var_non_literal)) { 7367 NewVD->setInvalidDecl(); 7368 return; 7369 } 7370 } 7371 7372 /// \brief Perform semantic checking on a newly-created variable 7373 /// declaration. 7374 /// 7375 /// This routine performs all of the type-checking required for a 7376 /// variable declaration once it has been built. It is used both to 7377 /// check variables after they have been parsed and their declarators 7378 /// have been translated into a declaration, and to check variables 7379 /// that have been instantiated from a template. 7380 /// 7381 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7382 /// 7383 /// Returns true if the variable declaration is a redeclaration. 7384 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7385 CheckVariableDeclarationType(NewVD); 7386 7387 // If the decl is already known invalid, don't check it. 7388 if (NewVD->isInvalidDecl()) 7389 return false; 7390 7391 // If we did not find anything by this name, look for a non-visible 7392 // extern "C" declaration with the same name. 7393 if (Previous.empty() && 7394 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7395 Previous.setShadowed(); 7396 7397 if (!Previous.empty()) { 7398 MergeVarDecl(NewVD, Previous); 7399 return true; 7400 } 7401 return false; 7402 } 7403 7404 namespace { 7405 struct FindOverriddenMethod { 7406 Sema *S; 7407 CXXMethodDecl *Method; 7408 7409 /// Member lookup function that determines whether a given C++ 7410 /// method overrides a method in a base class, to be used with 7411 /// CXXRecordDecl::lookupInBases(). 7412 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7413 RecordDecl *BaseRecord = 7414 Specifier->getType()->getAs<RecordType>()->getDecl(); 7415 7416 DeclarationName Name = Method->getDeclName(); 7417 7418 // FIXME: Do we care about other names here too? 7419 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7420 // We really want to find the base class destructor here. 7421 QualType T = S->Context.getTypeDeclType(BaseRecord); 7422 CanQualType CT = S->Context.getCanonicalType(T); 7423 7424 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7425 } 7426 7427 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7428 Path.Decls = Path.Decls.slice(1)) { 7429 NamedDecl *D = Path.Decls.front(); 7430 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7431 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7432 return true; 7433 } 7434 } 7435 7436 return false; 7437 } 7438 }; 7439 7440 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7441 } // end anonymous namespace 7442 7443 /// \brief Report an error regarding overriding, along with any relevant 7444 /// overriden methods. 7445 /// 7446 /// \param DiagID the primary error to report. 7447 /// \param MD the overriding method. 7448 /// \param OEK which overrides to include as notes. 7449 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7450 OverrideErrorKind OEK = OEK_All) { 7451 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7452 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7453 E = MD->end_overridden_methods(); 7454 I != E; ++I) { 7455 // This check (& the OEK parameter) could be replaced by a predicate, but 7456 // without lambdas that would be overkill. This is still nicer than writing 7457 // out the diag loop 3 times. 7458 if ((OEK == OEK_All) || 7459 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7460 (OEK == OEK_Deleted && (*I)->isDeleted())) 7461 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7462 } 7463 } 7464 7465 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7466 /// and if so, check that it's a valid override and remember it. 7467 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7468 // Look for methods in base classes that this method might override. 7469 CXXBasePaths Paths; 7470 FindOverriddenMethod FOM; 7471 FOM.Method = MD; 7472 FOM.S = this; 7473 bool hasDeletedOverridenMethods = false; 7474 bool hasNonDeletedOverridenMethods = false; 7475 bool AddedAny = false; 7476 if (DC->lookupInBases(FOM, Paths)) { 7477 for (auto *I : Paths.found_decls()) { 7478 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7479 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7480 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7481 !CheckOverridingFunctionAttributes(MD, OldMD) && 7482 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7483 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7484 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7485 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7486 AddedAny = true; 7487 } 7488 } 7489 } 7490 } 7491 7492 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7493 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7494 } 7495 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7496 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7497 } 7498 7499 return AddedAny; 7500 } 7501 7502 namespace { 7503 // Struct for holding all of the extra arguments needed by 7504 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7505 struct ActOnFDArgs { 7506 Scope *S; 7507 Declarator &D; 7508 MultiTemplateParamsArg TemplateParamLists; 7509 bool AddToScope; 7510 }; 7511 } // end anonymous namespace 7512 7513 namespace { 7514 7515 // Callback to only accept typo corrections that have a non-zero edit distance. 7516 // Also only accept corrections that have the same parent decl. 7517 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7518 public: 7519 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7520 CXXRecordDecl *Parent) 7521 : Context(Context), OriginalFD(TypoFD), 7522 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7523 7524 bool ValidateCandidate(const TypoCorrection &candidate) override { 7525 if (candidate.getEditDistance() == 0) 7526 return false; 7527 7528 SmallVector<unsigned, 1> MismatchedParams; 7529 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7530 CDeclEnd = candidate.end(); 7531 CDecl != CDeclEnd; ++CDecl) { 7532 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7533 7534 if (FD && !FD->hasBody() && 7535 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7536 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7537 CXXRecordDecl *Parent = MD->getParent(); 7538 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7539 return true; 7540 } else if (!ExpectedParent) { 7541 return true; 7542 } 7543 } 7544 } 7545 7546 return false; 7547 } 7548 7549 private: 7550 ASTContext &Context; 7551 FunctionDecl *OriginalFD; 7552 CXXRecordDecl *ExpectedParent; 7553 }; 7554 7555 } // end anonymous namespace 7556 7557 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7558 TypoCorrectedFunctionDefinitions.insert(F); 7559 } 7560 7561 /// \brief Generate diagnostics for an invalid function redeclaration. 7562 /// 7563 /// This routine handles generating the diagnostic messages for an invalid 7564 /// function redeclaration, including finding possible similar declarations 7565 /// or performing typo correction if there are no previous declarations with 7566 /// the same name. 7567 /// 7568 /// Returns a NamedDecl iff typo correction was performed and substituting in 7569 /// the new declaration name does not cause new errors. 7570 static NamedDecl *DiagnoseInvalidRedeclaration( 7571 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7572 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7573 DeclarationName Name = NewFD->getDeclName(); 7574 DeclContext *NewDC = NewFD->getDeclContext(); 7575 SmallVector<unsigned, 1> MismatchedParams; 7576 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7577 TypoCorrection Correction; 7578 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7579 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7580 : diag::err_member_decl_does_not_match; 7581 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7582 IsLocalFriend ? Sema::LookupLocalFriendName 7583 : Sema::LookupOrdinaryName, 7584 Sema::ForRedeclaration); 7585 7586 NewFD->setInvalidDecl(); 7587 if (IsLocalFriend) 7588 SemaRef.LookupName(Prev, S); 7589 else 7590 SemaRef.LookupQualifiedName(Prev, NewDC); 7591 assert(!Prev.isAmbiguous() && 7592 "Cannot have an ambiguity in previous-declaration lookup"); 7593 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7594 if (!Prev.empty()) { 7595 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7596 Func != FuncEnd; ++Func) { 7597 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7598 if (FD && 7599 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7600 // Add 1 to the index so that 0 can mean the mismatch didn't 7601 // involve a parameter 7602 unsigned ParamNum = 7603 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7604 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7605 } 7606 } 7607 // If the qualified name lookup yielded nothing, try typo correction 7608 } else if ((Correction = SemaRef.CorrectTypo( 7609 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7610 &ExtraArgs.D.getCXXScopeSpec(), 7611 llvm::make_unique<DifferentNameValidatorCCC>( 7612 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7613 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7614 // Set up everything for the call to ActOnFunctionDeclarator 7615 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7616 ExtraArgs.D.getIdentifierLoc()); 7617 Previous.clear(); 7618 Previous.setLookupName(Correction.getCorrection()); 7619 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7620 CDeclEnd = Correction.end(); 7621 CDecl != CDeclEnd; ++CDecl) { 7622 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7623 if (FD && !FD->hasBody() && 7624 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7625 Previous.addDecl(FD); 7626 } 7627 } 7628 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7629 7630 NamedDecl *Result; 7631 // Retry building the function declaration with the new previous 7632 // declarations, and with errors suppressed. 7633 { 7634 // Trap errors. 7635 Sema::SFINAETrap Trap(SemaRef); 7636 7637 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7638 // pieces need to verify the typo-corrected C++ declaration and hopefully 7639 // eliminate the need for the parameter pack ExtraArgs. 7640 Result = SemaRef.ActOnFunctionDeclarator( 7641 ExtraArgs.S, ExtraArgs.D, 7642 Correction.getCorrectionDecl()->getDeclContext(), 7643 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7644 ExtraArgs.AddToScope); 7645 7646 if (Trap.hasErrorOccurred()) 7647 Result = nullptr; 7648 } 7649 7650 if (Result) { 7651 // Determine which correction we picked. 7652 Decl *Canonical = Result->getCanonicalDecl(); 7653 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7654 I != E; ++I) 7655 if ((*I)->getCanonicalDecl() == Canonical) 7656 Correction.setCorrectionDecl(*I); 7657 7658 // Let Sema know about the correction. 7659 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7660 SemaRef.diagnoseTypo( 7661 Correction, 7662 SemaRef.PDiag(IsLocalFriend 7663 ? diag::err_no_matching_local_friend_suggest 7664 : diag::err_member_decl_does_not_match_suggest) 7665 << Name << NewDC << IsDefinition); 7666 return Result; 7667 } 7668 7669 // Pretend the typo correction never occurred 7670 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7671 ExtraArgs.D.getIdentifierLoc()); 7672 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7673 Previous.clear(); 7674 Previous.setLookupName(Name); 7675 } 7676 7677 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7678 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7679 7680 bool NewFDisConst = false; 7681 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7682 NewFDisConst = NewMD->isConst(); 7683 7684 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7685 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7686 NearMatch != NearMatchEnd; ++NearMatch) { 7687 FunctionDecl *FD = NearMatch->first; 7688 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7689 bool FDisConst = MD && MD->isConst(); 7690 bool IsMember = MD || !IsLocalFriend; 7691 7692 // FIXME: These notes are poorly worded for the local friend case. 7693 if (unsigned Idx = NearMatch->second) { 7694 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7695 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7696 if (Loc.isInvalid()) Loc = FD->getLocation(); 7697 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7698 : diag::note_local_decl_close_param_match) 7699 << Idx << FDParam->getType() 7700 << NewFD->getParamDecl(Idx - 1)->getType(); 7701 } else if (FDisConst != NewFDisConst) { 7702 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7703 << NewFDisConst << FD->getSourceRange().getEnd(); 7704 } else 7705 SemaRef.Diag(FD->getLocation(), 7706 IsMember ? diag::note_member_def_close_match 7707 : diag::note_local_decl_close_match); 7708 } 7709 return nullptr; 7710 } 7711 7712 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7713 switch (D.getDeclSpec().getStorageClassSpec()) { 7714 default: llvm_unreachable("Unknown storage class!"); 7715 case DeclSpec::SCS_auto: 7716 case DeclSpec::SCS_register: 7717 case DeclSpec::SCS_mutable: 7718 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7719 diag::err_typecheck_sclass_func); 7720 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7721 D.setInvalidType(); 7722 break; 7723 case DeclSpec::SCS_unspecified: break; 7724 case DeclSpec::SCS_extern: 7725 if (D.getDeclSpec().isExternInLinkageSpec()) 7726 return SC_None; 7727 return SC_Extern; 7728 case DeclSpec::SCS_static: { 7729 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7730 // C99 6.7.1p5: 7731 // The declaration of an identifier for a function that has 7732 // block scope shall have no explicit storage-class specifier 7733 // other than extern 7734 // See also (C++ [dcl.stc]p4). 7735 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7736 diag::err_static_block_func); 7737 break; 7738 } else 7739 return SC_Static; 7740 } 7741 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7742 } 7743 7744 // No explicit storage class has already been returned 7745 return SC_None; 7746 } 7747 7748 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7749 DeclContext *DC, QualType &R, 7750 TypeSourceInfo *TInfo, 7751 StorageClass SC, 7752 bool &IsVirtualOkay) { 7753 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7754 DeclarationName Name = NameInfo.getName(); 7755 7756 FunctionDecl *NewFD = nullptr; 7757 bool isInline = D.getDeclSpec().isInlineSpecified(); 7758 7759 if (!SemaRef.getLangOpts().CPlusPlus) { 7760 // Determine whether the function was written with a 7761 // prototype. This true when: 7762 // - there is a prototype in the declarator, or 7763 // - the type R of the function is some kind of typedef or other non- 7764 // attributed reference to a type name (which eventually refers to a 7765 // function type). 7766 bool HasPrototype = 7767 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7768 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7769 7770 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7771 D.getLocStart(), NameInfo, R, 7772 TInfo, SC, isInline, 7773 HasPrototype, false); 7774 if (D.isInvalidType()) 7775 NewFD->setInvalidDecl(); 7776 7777 return NewFD; 7778 } 7779 7780 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7781 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7782 7783 // Check that the return type is not an abstract class type. 7784 // For record types, this is done by the AbstractClassUsageDiagnoser once 7785 // the class has been completely parsed. 7786 if (!DC->isRecord() && 7787 SemaRef.RequireNonAbstractType( 7788 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7789 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7790 D.setInvalidType(); 7791 7792 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7793 // This is a C++ constructor declaration. 7794 assert(DC->isRecord() && 7795 "Constructors can only be declared in a member context"); 7796 7797 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7798 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7799 D.getLocStart(), NameInfo, 7800 R, TInfo, isExplicit, isInline, 7801 /*isImplicitlyDeclared=*/false, 7802 isConstexpr); 7803 7804 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7805 // This is a C++ destructor declaration. 7806 if (DC->isRecord()) { 7807 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7808 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7809 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7810 SemaRef.Context, Record, 7811 D.getLocStart(), 7812 NameInfo, R, TInfo, isInline, 7813 /*isImplicitlyDeclared=*/false); 7814 7815 // If the class is complete, then we now create the implicit exception 7816 // specification. If the class is incomplete or dependent, we can't do 7817 // it yet. 7818 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7819 Record->getDefinition() && !Record->isBeingDefined() && 7820 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7821 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7822 } 7823 7824 IsVirtualOkay = true; 7825 return NewDD; 7826 7827 } else { 7828 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7829 D.setInvalidType(); 7830 7831 // Create a FunctionDecl to satisfy the function definition parsing 7832 // code path. 7833 return FunctionDecl::Create(SemaRef.Context, DC, 7834 D.getLocStart(), 7835 D.getIdentifierLoc(), Name, R, TInfo, 7836 SC, isInline, 7837 /*hasPrototype=*/true, isConstexpr); 7838 } 7839 7840 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7841 if (!DC->isRecord()) { 7842 SemaRef.Diag(D.getIdentifierLoc(), 7843 diag::err_conv_function_not_member); 7844 return nullptr; 7845 } 7846 7847 SemaRef.CheckConversionDeclarator(D, R, SC); 7848 IsVirtualOkay = true; 7849 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7850 D.getLocStart(), NameInfo, 7851 R, TInfo, isInline, isExplicit, 7852 isConstexpr, SourceLocation()); 7853 7854 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7855 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7856 7857 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7858 isExplicit, NameInfo, R, TInfo, 7859 D.getLocEnd()); 7860 } else if (DC->isRecord()) { 7861 // If the name of the function is the same as the name of the record, 7862 // then this must be an invalid constructor that has a return type. 7863 // (The parser checks for a return type and makes the declarator a 7864 // constructor if it has no return type). 7865 if (Name.getAsIdentifierInfo() && 7866 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7867 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7868 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7869 << SourceRange(D.getIdentifierLoc()); 7870 return nullptr; 7871 } 7872 7873 // This is a C++ method declaration. 7874 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7875 cast<CXXRecordDecl>(DC), 7876 D.getLocStart(), NameInfo, R, 7877 TInfo, SC, isInline, 7878 isConstexpr, SourceLocation()); 7879 IsVirtualOkay = !Ret->isStatic(); 7880 return Ret; 7881 } else { 7882 bool isFriend = 7883 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7884 if (!isFriend && SemaRef.CurContext->isRecord()) 7885 return nullptr; 7886 7887 // Determine whether the function was written with a 7888 // prototype. This true when: 7889 // - we're in C++ (where every function has a prototype), 7890 return FunctionDecl::Create(SemaRef.Context, DC, 7891 D.getLocStart(), 7892 NameInfo, R, TInfo, SC, isInline, 7893 true/*HasPrototype*/, isConstexpr); 7894 } 7895 } 7896 7897 enum OpenCLParamType { 7898 ValidKernelParam, 7899 PtrPtrKernelParam, 7900 PtrKernelParam, 7901 InvalidAddrSpacePtrKernelParam, 7902 InvalidKernelParam, 7903 RecordKernelParam 7904 }; 7905 7906 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7907 if (PT->isPointerType()) { 7908 QualType PointeeType = PT->getPointeeType(); 7909 if (PointeeType->isPointerType()) 7910 return PtrPtrKernelParam; 7911 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7912 PointeeType.getAddressSpace() == 0) 7913 return InvalidAddrSpacePtrKernelParam; 7914 return PtrKernelParam; 7915 } 7916 7917 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7918 // be used as builtin types. 7919 7920 if (PT->isImageType()) 7921 return PtrKernelParam; 7922 7923 if (PT->isBooleanType()) 7924 return InvalidKernelParam; 7925 7926 if (PT->isEventT()) 7927 return InvalidKernelParam; 7928 7929 // OpenCL extension spec v1.2 s9.5: 7930 // This extension adds support for half scalar and vector types as built-in 7931 // types that can be used for arithmetic operations, conversions etc. 7932 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 7933 return InvalidKernelParam; 7934 7935 if (PT->isRecordType()) 7936 return RecordKernelParam; 7937 7938 return ValidKernelParam; 7939 } 7940 7941 static void checkIsValidOpenCLKernelParameter( 7942 Sema &S, 7943 Declarator &D, 7944 ParmVarDecl *Param, 7945 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7946 QualType PT = Param->getType(); 7947 7948 // Cache the valid types we encounter to avoid rechecking structs that are 7949 // used again 7950 if (ValidTypes.count(PT.getTypePtr())) 7951 return; 7952 7953 switch (getOpenCLKernelParameterType(S, PT)) { 7954 case PtrPtrKernelParam: 7955 // OpenCL v1.2 s6.9.a: 7956 // A kernel function argument cannot be declared as a 7957 // pointer to a pointer type. 7958 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7959 D.setInvalidType(); 7960 return; 7961 7962 case InvalidAddrSpacePtrKernelParam: 7963 // OpenCL v1.0 s6.5: 7964 // __kernel function arguments declared to be a pointer of a type can point 7965 // to one of the following address spaces only : __global, __local or 7966 // __constant. 7967 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 7968 D.setInvalidType(); 7969 return; 7970 7971 // OpenCL v1.2 s6.9.k: 7972 // Arguments to kernel functions in a program cannot be declared with the 7973 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7974 // uintptr_t or a struct and/or union that contain fields declared to be 7975 // one of these built-in scalar types. 7976 7977 case InvalidKernelParam: 7978 // OpenCL v1.2 s6.8 n: 7979 // A kernel function argument cannot be declared 7980 // of event_t type. 7981 // Do not diagnose half type since it is diagnosed as invalid argument 7982 // type for any function elsewhere. 7983 if (!PT->isHalfType()) 7984 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7985 D.setInvalidType(); 7986 return; 7987 7988 case PtrKernelParam: 7989 case ValidKernelParam: 7990 ValidTypes.insert(PT.getTypePtr()); 7991 return; 7992 7993 case RecordKernelParam: 7994 break; 7995 } 7996 7997 // Track nested structs we will inspect 7998 SmallVector<const Decl *, 4> VisitStack; 7999 8000 // Track where we are in the nested structs. Items will migrate from 8001 // VisitStack to HistoryStack as we do the DFS for bad field. 8002 SmallVector<const FieldDecl *, 4> HistoryStack; 8003 HistoryStack.push_back(nullptr); 8004 8005 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8006 VisitStack.push_back(PD); 8007 8008 assert(VisitStack.back() && "First decl null?"); 8009 8010 do { 8011 const Decl *Next = VisitStack.pop_back_val(); 8012 if (!Next) { 8013 assert(!HistoryStack.empty()); 8014 // Found a marker, we have gone up a level 8015 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8016 ValidTypes.insert(Hist->getType().getTypePtr()); 8017 8018 continue; 8019 } 8020 8021 // Adds everything except the original parameter declaration (which is not a 8022 // field itself) to the history stack. 8023 const RecordDecl *RD; 8024 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8025 HistoryStack.push_back(Field); 8026 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8027 } else { 8028 RD = cast<RecordDecl>(Next); 8029 } 8030 8031 // Add a null marker so we know when we've gone back up a level 8032 VisitStack.push_back(nullptr); 8033 8034 for (const auto *FD : RD->fields()) { 8035 QualType QT = FD->getType(); 8036 8037 if (ValidTypes.count(QT.getTypePtr())) 8038 continue; 8039 8040 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8041 if (ParamType == ValidKernelParam) 8042 continue; 8043 8044 if (ParamType == RecordKernelParam) { 8045 VisitStack.push_back(FD); 8046 continue; 8047 } 8048 8049 // OpenCL v1.2 s6.9.p: 8050 // Arguments to kernel functions that are declared to be a struct or union 8051 // do not allow OpenCL objects to be passed as elements of the struct or 8052 // union. 8053 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8054 ParamType == InvalidAddrSpacePtrKernelParam) { 8055 S.Diag(Param->getLocation(), 8056 diag::err_record_with_pointers_kernel_param) 8057 << PT->isUnionType() 8058 << PT; 8059 } else { 8060 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8061 } 8062 8063 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8064 << PD->getDeclName(); 8065 8066 // We have an error, now let's go back up through history and show where 8067 // the offending field came from 8068 for (ArrayRef<const FieldDecl *>::const_iterator 8069 I = HistoryStack.begin() + 1, 8070 E = HistoryStack.end(); 8071 I != E; ++I) { 8072 const FieldDecl *OuterField = *I; 8073 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8074 << OuterField->getType(); 8075 } 8076 8077 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8078 << QT->isPointerType() 8079 << QT; 8080 D.setInvalidType(); 8081 return; 8082 } 8083 } while (!VisitStack.empty()); 8084 } 8085 8086 /// Find the DeclContext in which a tag is implicitly declared if we see an 8087 /// elaborated type specifier in the specified context, and lookup finds 8088 /// nothing. 8089 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8090 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8091 DC = DC->getParent(); 8092 return DC; 8093 } 8094 8095 /// Find the Scope in which a tag is implicitly declared if we see an 8096 /// elaborated type specifier in the specified context, and lookup finds 8097 /// nothing. 8098 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8099 while (S->isClassScope() || 8100 (LangOpts.CPlusPlus && 8101 S->isFunctionPrototypeScope()) || 8102 ((S->getFlags() & Scope::DeclScope) == 0) || 8103 (S->getEntity() && S->getEntity()->isTransparentContext())) 8104 S = S->getParent(); 8105 return S; 8106 } 8107 8108 NamedDecl* 8109 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8110 TypeSourceInfo *TInfo, LookupResult &Previous, 8111 MultiTemplateParamsArg TemplateParamLists, 8112 bool &AddToScope) { 8113 QualType R = TInfo->getType(); 8114 8115 assert(R.getTypePtr()->isFunctionType()); 8116 8117 // TODO: consider using NameInfo for diagnostic. 8118 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8119 DeclarationName Name = NameInfo.getName(); 8120 StorageClass SC = getFunctionStorageClass(*this, D); 8121 8122 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8123 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8124 diag::err_invalid_thread) 8125 << DeclSpec::getSpecifierName(TSCS); 8126 8127 if (D.isFirstDeclarationOfMember()) 8128 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8129 D.getIdentifierLoc()); 8130 8131 bool isFriend = false; 8132 FunctionTemplateDecl *FunctionTemplate = nullptr; 8133 bool isMemberSpecialization = false; 8134 bool isFunctionTemplateSpecialization = false; 8135 8136 bool isDependentClassScopeExplicitSpecialization = false; 8137 bool HasExplicitTemplateArgs = false; 8138 TemplateArgumentListInfo TemplateArgs; 8139 8140 bool isVirtualOkay = false; 8141 8142 DeclContext *OriginalDC = DC; 8143 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8144 8145 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8146 isVirtualOkay); 8147 if (!NewFD) return nullptr; 8148 8149 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8150 NewFD->setTopLevelDeclInObjCContainer(); 8151 8152 // Set the lexical context. If this is a function-scope declaration, or has a 8153 // C++ scope specifier, or is the object of a friend declaration, the lexical 8154 // context will be different from the semantic context. 8155 NewFD->setLexicalDeclContext(CurContext); 8156 8157 if (IsLocalExternDecl) 8158 NewFD->setLocalExternDecl(); 8159 8160 if (getLangOpts().CPlusPlus) { 8161 bool isInline = D.getDeclSpec().isInlineSpecified(); 8162 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8163 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8164 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8165 bool isConcept = D.getDeclSpec().isConceptSpecified(); 8166 isFriend = D.getDeclSpec().isFriendSpecified(); 8167 if (isFriend && !isInline && D.isFunctionDefinition()) { 8168 // C++ [class.friend]p5 8169 // A function can be defined in a friend declaration of a 8170 // class . . . . Such a function is implicitly inline. 8171 NewFD->setImplicitlyInline(); 8172 } 8173 8174 // If this is a method defined in an __interface, and is not a constructor 8175 // or an overloaded operator, then set the pure flag (isVirtual will already 8176 // return true). 8177 if (const CXXRecordDecl *Parent = 8178 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8179 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8180 NewFD->setPure(true); 8181 8182 // C++ [class.union]p2 8183 // A union can have member functions, but not virtual functions. 8184 if (isVirtual && Parent->isUnion()) 8185 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8186 } 8187 8188 SetNestedNameSpecifier(NewFD, D); 8189 isMemberSpecialization = false; 8190 isFunctionTemplateSpecialization = false; 8191 if (D.isInvalidType()) 8192 NewFD->setInvalidDecl(); 8193 8194 // Match up the template parameter lists with the scope specifier, then 8195 // determine whether we have a template or a template specialization. 8196 bool Invalid = false; 8197 if (TemplateParameterList *TemplateParams = 8198 MatchTemplateParametersToScopeSpecifier( 8199 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8200 D.getCXXScopeSpec(), 8201 D.getName().getKind() == UnqualifiedId::IK_TemplateId 8202 ? D.getName().TemplateId 8203 : nullptr, 8204 TemplateParamLists, isFriend, isMemberSpecialization, 8205 Invalid)) { 8206 if (TemplateParams->size() > 0) { 8207 // This is a function template 8208 8209 // Check that we can declare a template here. 8210 if (CheckTemplateDeclScope(S, TemplateParams)) 8211 NewFD->setInvalidDecl(); 8212 8213 // A destructor cannot be a template. 8214 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8215 Diag(NewFD->getLocation(), diag::err_destructor_template); 8216 NewFD->setInvalidDecl(); 8217 } 8218 8219 // If we're adding a template to a dependent context, we may need to 8220 // rebuilding some of the types used within the template parameter list, 8221 // now that we know what the current instantiation is. 8222 if (DC->isDependentContext()) { 8223 ContextRAII SavedContext(*this, DC); 8224 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8225 Invalid = true; 8226 } 8227 8228 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8229 NewFD->getLocation(), 8230 Name, TemplateParams, 8231 NewFD); 8232 FunctionTemplate->setLexicalDeclContext(CurContext); 8233 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8234 8235 // For source fidelity, store the other template param lists. 8236 if (TemplateParamLists.size() > 1) { 8237 NewFD->setTemplateParameterListsInfo(Context, 8238 TemplateParamLists.drop_back(1)); 8239 } 8240 } else { 8241 // This is a function template specialization. 8242 isFunctionTemplateSpecialization = true; 8243 // For source fidelity, store all the template param lists. 8244 if (TemplateParamLists.size() > 0) 8245 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8246 8247 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8248 if (isFriend) { 8249 // We want to remove the "template<>", found here. 8250 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8251 8252 // If we remove the template<> and the name is not a 8253 // template-id, we're actually silently creating a problem: 8254 // the friend declaration will refer to an untemplated decl, 8255 // and clearly the user wants a template specialization. So 8256 // we need to insert '<>' after the name. 8257 SourceLocation InsertLoc; 8258 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8259 InsertLoc = D.getName().getSourceRange().getEnd(); 8260 InsertLoc = getLocForEndOfToken(InsertLoc); 8261 } 8262 8263 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8264 << Name << RemoveRange 8265 << FixItHint::CreateRemoval(RemoveRange) 8266 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8267 } 8268 } 8269 } 8270 else { 8271 // All template param lists were matched against the scope specifier: 8272 // this is NOT (an explicit specialization of) a template. 8273 if (TemplateParamLists.size() > 0) 8274 // For source fidelity, store all the template param lists. 8275 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8276 } 8277 8278 if (Invalid) { 8279 NewFD->setInvalidDecl(); 8280 if (FunctionTemplate) 8281 FunctionTemplate->setInvalidDecl(); 8282 } 8283 8284 // C++ [dcl.fct.spec]p5: 8285 // The virtual specifier shall only be used in declarations of 8286 // nonstatic class member functions that appear within a 8287 // member-specification of a class declaration; see 10.3. 8288 // 8289 if (isVirtual && !NewFD->isInvalidDecl()) { 8290 if (!isVirtualOkay) { 8291 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8292 diag::err_virtual_non_function); 8293 } else if (!CurContext->isRecord()) { 8294 // 'virtual' was specified outside of the class. 8295 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8296 diag::err_virtual_out_of_class) 8297 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8298 } else if (NewFD->getDescribedFunctionTemplate()) { 8299 // C++ [temp.mem]p3: 8300 // A member function template shall not be virtual. 8301 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8302 diag::err_virtual_member_function_template) 8303 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8304 } else { 8305 // Okay: Add virtual to the method. 8306 NewFD->setVirtualAsWritten(true); 8307 } 8308 8309 if (getLangOpts().CPlusPlus14 && 8310 NewFD->getReturnType()->isUndeducedType()) 8311 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8312 } 8313 8314 if (getLangOpts().CPlusPlus14 && 8315 (NewFD->isDependentContext() || 8316 (isFriend && CurContext->isDependentContext())) && 8317 NewFD->getReturnType()->isUndeducedType()) { 8318 // If the function template is referenced directly (for instance, as a 8319 // member of the current instantiation), pretend it has a dependent type. 8320 // This is not really justified by the standard, but is the only sane 8321 // thing to do. 8322 // FIXME: For a friend function, we have not marked the function as being 8323 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8324 const FunctionProtoType *FPT = 8325 NewFD->getType()->castAs<FunctionProtoType>(); 8326 QualType Result = 8327 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8328 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8329 FPT->getExtProtoInfo())); 8330 } 8331 8332 // C++ [dcl.fct.spec]p3: 8333 // The inline specifier shall not appear on a block scope function 8334 // declaration. 8335 if (isInline && !NewFD->isInvalidDecl()) { 8336 if (CurContext->isFunctionOrMethod()) { 8337 // 'inline' is not allowed on block scope function declaration. 8338 Diag(D.getDeclSpec().getInlineSpecLoc(), 8339 diag::err_inline_declaration_block_scope) << Name 8340 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8341 } 8342 } 8343 8344 // C++ [dcl.fct.spec]p6: 8345 // The explicit specifier shall be used only in the declaration of a 8346 // constructor or conversion function within its class definition; 8347 // see 12.3.1 and 12.3.2. 8348 if (isExplicit && !NewFD->isInvalidDecl() && 8349 !isa<CXXDeductionGuideDecl>(NewFD)) { 8350 if (!CurContext->isRecord()) { 8351 // 'explicit' was specified outside of the class. 8352 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8353 diag::err_explicit_out_of_class) 8354 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8355 } else if (!isa<CXXConstructorDecl>(NewFD) && 8356 !isa<CXXConversionDecl>(NewFD)) { 8357 // 'explicit' was specified on a function that wasn't a constructor 8358 // or conversion function. 8359 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8360 diag::err_explicit_non_ctor_or_conv_function) 8361 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8362 } 8363 } 8364 8365 if (isConstexpr) { 8366 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8367 // are implicitly inline. 8368 NewFD->setImplicitlyInline(); 8369 8370 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8371 // be either constructors or to return a literal type. Therefore, 8372 // destructors cannot be declared constexpr. 8373 if (isa<CXXDestructorDecl>(NewFD)) 8374 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8375 } 8376 8377 if (isConcept) { 8378 // This is a function concept. 8379 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8380 FTD->setConcept(); 8381 8382 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8383 // applied only to the definition of a function template [...] 8384 if (!D.isFunctionDefinition()) { 8385 Diag(D.getDeclSpec().getConceptSpecLoc(), 8386 diag::err_function_concept_not_defined); 8387 NewFD->setInvalidDecl(); 8388 } 8389 8390 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8391 // have no exception-specification and is treated as if it were specified 8392 // with noexcept(true) (15.4). [...] 8393 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8394 if (FPT->hasExceptionSpec()) { 8395 SourceRange Range; 8396 if (D.isFunctionDeclarator()) 8397 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8398 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8399 << FixItHint::CreateRemoval(Range); 8400 NewFD->setInvalidDecl(); 8401 } else { 8402 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8403 } 8404 8405 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8406 // following restrictions: 8407 // - The declared return type shall have the type bool. 8408 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8409 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8410 NewFD->setInvalidDecl(); 8411 } 8412 8413 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8414 // following restrictions: 8415 // - The declaration's parameter list shall be equivalent to an empty 8416 // parameter list. 8417 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8418 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8419 } 8420 8421 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8422 // implicity defined to be a constexpr declaration (implicitly inline) 8423 NewFD->setImplicitlyInline(); 8424 8425 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8426 // be declared with the thread_local, inline, friend, or constexpr 8427 // specifiers, [...] 8428 if (isInline) { 8429 Diag(D.getDeclSpec().getInlineSpecLoc(), 8430 diag::err_concept_decl_invalid_specifiers) 8431 << 1 << 1; 8432 NewFD->setInvalidDecl(true); 8433 } 8434 8435 if (isFriend) { 8436 Diag(D.getDeclSpec().getFriendSpecLoc(), 8437 diag::err_concept_decl_invalid_specifiers) 8438 << 1 << 2; 8439 NewFD->setInvalidDecl(true); 8440 } 8441 8442 if (isConstexpr) { 8443 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8444 diag::err_concept_decl_invalid_specifiers) 8445 << 1 << 3; 8446 NewFD->setInvalidDecl(true); 8447 } 8448 8449 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8450 // applied only to the definition of a function template or variable 8451 // template, declared in namespace scope. 8452 if (isFunctionTemplateSpecialization) { 8453 Diag(D.getDeclSpec().getConceptSpecLoc(), 8454 diag::err_concept_specified_specialization) << 1; 8455 NewFD->setInvalidDecl(true); 8456 return NewFD; 8457 } 8458 } 8459 8460 // If __module_private__ was specified, mark the function accordingly. 8461 if (D.getDeclSpec().isModulePrivateSpecified()) { 8462 if (isFunctionTemplateSpecialization) { 8463 SourceLocation ModulePrivateLoc 8464 = D.getDeclSpec().getModulePrivateSpecLoc(); 8465 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8466 << 0 8467 << FixItHint::CreateRemoval(ModulePrivateLoc); 8468 } else { 8469 NewFD->setModulePrivate(); 8470 if (FunctionTemplate) 8471 FunctionTemplate->setModulePrivate(); 8472 } 8473 } 8474 8475 if (isFriend) { 8476 if (FunctionTemplate) { 8477 FunctionTemplate->setObjectOfFriendDecl(); 8478 FunctionTemplate->setAccess(AS_public); 8479 } 8480 NewFD->setObjectOfFriendDecl(); 8481 NewFD->setAccess(AS_public); 8482 } 8483 8484 // If a function is defined as defaulted or deleted, mark it as such now. 8485 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8486 // definition kind to FDK_Definition. 8487 switch (D.getFunctionDefinitionKind()) { 8488 case FDK_Declaration: 8489 case FDK_Definition: 8490 break; 8491 8492 case FDK_Defaulted: 8493 NewFD->setDefaulted(); 8494 break; 8495 8496 case FDK_Deleted: 8497 NewFD->setDeletedAsWritten(); 8498 break; 8499 } 8500 8501 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8502 D.isFunctionDefinition()) { 8503 // C++ [class.mfct]p2: 8504 // A member function may be defined (8.4) in its class definition, in 8505 // which case it is an inline member function (7.1.2) 8506 NewFD->setImplicitlyInline(); 8507 } 8508 8509 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8510 !CurContext->isRecord()) { 8511 // C++ [class.static]p1: 8512 // A data or function member of a class may be declared static 8513 // in a class definition, in which case it is a static member of 8514 // the class. 8515 8516 // Complain about the 'static' specifier if it's on an out-of-line 8517 // member function definition. 8518 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8519 diag::err_static_out_of_line) 8520 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8521 } 8522 8523 // C++11 [except.spec]p15: 8524 // A deallocation function with no exception-specification is treated 8525 // as if it were specified with noexcept(true). 8526 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8527 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8528 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8529 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8530 NewFD->setType(Context.getFunctionType( 8531 FPT->getReturnType(), FPT->getParamTypes(), 8532 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8533 } 8534 8535 // Filter out previous declarations that don't match the scope. 8536 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8537 D.getCXXScopeSpec().isNotEmpty() || 8538 isMemberSpecialization || 8539 isFunctionTemplateSpecialization); 8540 8541 // Handle GNU asm-label extension (encoded as an attribute). 8542 if (Expr *E = (Expr*) D.getAsmLabel()) { 8543 // The parser guarantees this is a string. 8544 StringLiteral *SE = cast<StringLiteral>(E); 8545 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8546 SE->getString(), 0)); 8547 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8548 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8549 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8550 if (I != ExtnameUndeclaredIdentifiers.end()) { 8551 if (isDeclExternC(NewFD)) { 8552 NewFD->addAttr(I->second); 8553 ExtnameUndeclaredIdentifiers.erase(I); 8554 } else 8555 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8556 << /*Variable*/0 << NewFD; 8557 } 8558 } 8559 8560 // Copy the parameter declarations from the declarator D to the function 8561 // declaration NewFD, if they are available. First scavenge them into Params. 8562 SmallVector<ParmVarDecl*, 16> Params; 8563 unsigned FTIIdx; 8564 if (D.isFunctionDeclarator(FTIIdx)) { 8565 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8566 8567 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8568 // function that takes no arguments, not a function that takes a 8569 // single void argument. 8570 // We let through "const void" here because Sema::GetTypeForDeclarator 8571 // already checks for that case. 8572 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8573 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8574 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8575 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8576 Param->setDeclContext(NewFD); 8577 Params.push_back(Param); 8578 8579 if (Param->isInvalidDecl()) 8580 NewFD->setInvalidDecl(); 8581 } 8582 } 8583 8584 if (!getLangOpts().CPlusPlus) { 8585 // In C, find all the tag declarations from the prototype and move them 8586 // into the function DeclContext. Remove them from the surrounding tag 8587 // injection context of the function, which is typically but not always 8588 // the TU. 8589 DeclContext *PrototypeTagContext = 8590 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8591 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8592 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8593 8594 // We don't want to reparent enumerators. Look at their parent enum 8595 // instead. 8596 if (!TD) { 8597 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8598 TD = cast<EnumDecl>(ECD->getDeclContext()); 8599 } 8600 if (!TD) 8601 continue; 8602 DeclContext *TagDC = TD->getLexicalDeclContext(); 8603 if (!TagDC->containsDecl(TD)) 8604 continue; 8605 TagDC->removeDecl(TD); 8606 TD->setDeclContext(NewFD); 8607 NewFD->addDecl(TD); 8608 8609 // Preserve the lexical DeclContext if it is not the surrounding tag 8610 // injection context of the FD. In this example, the semantic context of 8611 // E will be f and the lexical context will be S, while both the 8612 // semantic and lexical contexts of S will be f: 8613 // void f(struct S { enum E { a } f; } s); 8614 if (TagDC != PrototypeTagContext) 8615 TD->setLexicalDeclContext(TagDC); 8616 } 8617 } 8618 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8619 // When we're declaring a function with a typedef, typeof, etc as in the 8620 // following example, we'll need to synthesize (unnamed) 8621 // parameters for use in the declaration. 8622 // 8623 // @code 8624 // typedef void fn(int); 8625 // fn f; 8626 // @endcode 8627 8628 // Synthesize a parameter for each argument type. 8629 for (const auto &AI : FT->param_types()) { 8630 ParmVarDecl *Param = 8631 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8632 Param->setScopeInfo(0, Params.size()); 8633 Params.push_back(Param); 8634 } 8635 } else { 8636 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8637 "Should not need args for typedef of non-prototype fn"); 8638 } 8639 8640 // Finally, we know we have the right number of parameters, install them. 8641 NewFD->setParams(Params); 8642 8643 if (D.getDeclSpec().isNoreturnSpecified()) 8644 NewFD->addAttr( 8645 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8646 Context, 0)); 8647 8648 // Functions returning a variably modified type violate C99 6.7.5.2p2 8649 // because all functions have linkage. 8650 if (!NewFD->isInvalidDecl() && 8651 NewFD->getReturnType()->isVariablyModifiedType()) { 8652 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8653 NewFD->setInvalidDecl(); 8654 } 8655 8656 // Apply an implicit SectionAttr if #pragma code_seg is active. 8657 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8658 !NewFD->hasAttr<SectionAttr>()) { 8659 NewFD->addAttr( 8660 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8661 CodeSegStack.CurrentValue->getString(), 8662 CodeSegStack.CurrentPragmaLocation)); 8663 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8664 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8665 ASTContext::PSF_Read, 8666 NewFD)) 8667 NewFD->dropAttr<SectionAttr>(); 8668 } 8669 8670 // Handle attributes. 8671 ProcessDeclAttributes(S, NewFD, D); 8672 8673 if (getLangOpts().OpenCL) { 8674 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8675 // type declaration will generate a compilation error. 8676 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8677 if (AddressSpace == LangAS::opencl_local || 8678 AddressSpace == LangAS::opencl_global || 8679 AddressSpace == LangAS::opencl_constant) { 8680 Diag(NewFD->getLocation(), 8681 diag::err_opencl_return_value_with_address_space); 8682 NewFD->setInvalidDecl(); 8683 } 8684 } 8685 8686 if (!getLangOpts().CPlusPlus) { 8687 // Perform semantic checking on the function declaration. 8688 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8689 CheckMain(NewFD, D.getDeclSpec()); 8690 8691 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8692 CheckMSVCRTEntryPoint(NewFD); 8693 8694 if (!NewFD->isInvalidDecl()) 8695 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8696 isMemberSpecialization)); 8697 else if (!Previous.empty()) 8698 // Recover gracefully from an invalid redeclaration. 8699 D.setRedeclaration(true); 8700 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8701 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8702 "previous declaration set still overloaded"); 8703 8704 // Diagnose no-prototype function declarations with calling conventions that 8705 // don't support variadic calls. Only do this in C and do it after merging 8706 // possibly prototyped redeclarations. 8707 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8708 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8709 CallingConv CC = FT->getExtInfo().getCC(); 8710 if (!supportsVariadicCall(CC)) { 8711 // Windows system headers sometimes accidentally use stdcall without 8712 // (void) parameters, so we relax this to a warning. 8713 int DiagID = 8714 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8715 Diag(NewFD->getLocation(), DiagID) 8716 << FunctionType::getNameForCallConv(CC); 8717 } 8718 } 8719 } else { 8720 // C++11 [replacement.functions]p3: 8721 // The program's definitions shall not be specified as inline. 8722 // 8723 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8724 // 8725 // Suppress the diagnostic if the function is __attribute__((used)), since 8726 // that forces an external definition to be emitted. 8727 if (D.getDeclSpec().isInlineSpecified() && 8728 NewFD->isReplaceableGlobalAllocationFunction() && 8729 !NewFD->hasAttr<UsedAttr>()) 8730 Diag(D.getDeclSpec().getInlineSpecLoc(), 8731 diag::ext_operator_new_delete_declared_inline) 8732 << NewFD->getDeclName(); 8733 8734 // If the declarator is a template-id, translate the parser's template 8735 // argument list into our AST format. 8736 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8737 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8738 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8739 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8740 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8741 TemplateId->NumArgs); 8742 translateTemplateArguments(TemplateArgsPtr, 8743 TemplateArgs); 8744 8745 HasExplicitTemplateArgs = true; 8746 8747 if (NewFD->isInvalidDecl()) { 8748 HasExplicitTemplateArgs = false; 8749 } else if (FunctionTemplate) { 8750 // Function template with explicit template arguments. 8751 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8752 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8753 8754 HasExplicitTemplateArgs = false; 8755 } else { 8756 assert((isFunctionTemplateSpecialization || 8757 D.getDeclSpec().isFriendSpecified()) && 8758 "should have a 'template<>' for this decl"); 8759 // "friend void foo<>(int);" is an implicit specialization decl. 8760 isFunctionTemplateSpecialization = true; 8761 } 8762 } else if (isFriend && isFunctionTemplateSpecialization) { 8763 // This combination is only possible in a recovery case; the user 8764 // wrote something like: 8765 // template <> friend void foo(int); 8766 // which we're recovering from as if the user had written: 8767 // friend void foo<>(int); 8768 // Go ahead and fake up a template id. 8769 HasExplicitTemplateArgs = true; 8770 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8771 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8772 } 8773 8774 // We do not add HD attributes to specializations here because 8775 // they may have different constexpr-ness compared to their 8776 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8777 // may end up with different effective targets. Instead, a 8778 // specialization inherits its target attributes from its template 8779 // in the CheckFunctionTemplateSpecialization() call below. 8780 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8781 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8782 8783 // If it's a friend (and only if it's a friend), it's possible 8784 // that either the specialized function type or the specialized 8785 // template is dependent, and therefore matching will fail. In 8786 // this case, don't check the specialization yet. 8787 bool InstantiationDependent = false; 8788 if (isFunctionTemplateSpecialization && isFriend && 8789 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8790 TemplateSpecializationType::anyDependentTemplateArguments( 8791 TemplateArgs, 8792 InstantiationDependent))) { 8793 assert(HasExplicitTemplateArgs && 8794 "friend function specialization without template args"); 8795 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8796 Previous)) 8797 NewFD->setInvalidDecl(); 8798 } else if (isFunctionTemplateSpecialization) { 8799 if (CurContext->isDependentContext() && CurContext->isRecord() 8800 && !isFriend) { 8801 isDependentClassScopeExplicitSpecialization = true; 8802 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8803 diag::ext_function_specialization_in_class : 8804 diag::err_function_specialization_in_class) 8805 << NewFD->getDeclName(); 8806 } else if (CheckFunctionTemplateSpecialization(NewFD, 8807 (HasExplicitTemplateArgs ? &TemplateArgs 8808 : nullptr), 8809 Previous)) 8810 NewFD->setInvalidDecl(); 8811 8812 // C++ [dcl.stc]p1: 8813 // A storage-class-specifier shall not be specified in an explicit 8814 // specialization (14.7.3) 8815 FunctionTemplateSpecializationInfo *Info = 8816 NewFD->getTemplateSpecializationInfo(); 8817 if (Info && SC != SC_None) { 8818 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8819 Diag(NewFD->getLocation(), 8820 diag::err_explicit_specialization_inconsistent_storage_class) 8821 << SC 8822 << FixItHint::CreateRemoval( 8823 D.getDeclSpec().getStorageClassSpecLoc()); 8824 8825 else 8826 Diag(NewFD->getLocation(), 8827 diag::ext_explicit_specialization_storage_class) 8828 << FixItHint::CreateRemoval( 8829 D.getDeclSpec().getStorageClassSpecLoc()); 8830 } 8831 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8832 if (CheckMemberSpecialization(NewFD, Previous)) 8833 NewFD->setInvalidDecl(); 8834 } 8835 8836 // Perform semantic checking on the function declaration. 8837 if (!isDependentClassScopeExplicitSpecialization) { 8838 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8839 CheckMain(NewFD, D.getDeclSpec()); 8840 8841 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8842 CheckMSVCRTEntryPoint(NewFD); 8843 8844 if (!NewFD->isInvalidDecl()) 8845 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8846 isMemberSpecialization)); 8847 else if (!Previous.empty()) 8848 // Recover gracefully from an invalid redeclaration. 8849 D.setRedeclaration(true); 8850 } 8851 8852 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8853 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8854 "previous declaration set still overloaded"); 8855 8856 NamedDecl *PrincipalDecl = (FunctionTemplate 8857 ? cast<NamedDecl>(FunctionTemplate) 8858 : NewFD); 8859 8860 if (isFriend && NewFD->getPreviousDecl()) { 8861 AccessSpecifier Access = AS_public; 8862 if (!NewFD->isInvalidDecl()) 8863 Access = NewFD->getPreviousDecl()->getAccess(); 8864 8865 NewFD->setAccess(Access); 8866 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8867 } 8868 8869 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8870 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8871 PrincipalDecl->setNonMemberOperator(); 8872 8873 // If we have a function template, check the template parameter 8874 // list. This will check and merge default template arguments. 8875 if (FunctionTemplate) { 8876 FunctionTemplateDecl *PrevTemplate = 8877 FunctionTemplate->getPreviousDecl(); 8878 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8879 PrevTemplate ? PrevTemplate->getTemplateParameters() 8880 : nullptr, 8881 D.getDeclSpec().isFriendSpecified() 8882 ? (D.isFunctionDefinition() 8883 ? TPC_FriendFunctionTemplateDefinition 8884 : TPC_FriendFunctionTemplate) 8885 : (D.getCXXScopeSpec().isSet() && 8886 DC && DC->isRecord() && 8887 DC->isDependentContext()) 8888 ? TPC_ClassTemplateMember 8889 : TPC_FunctionTemplate); 8890 } 8891 8892 if (NewFD->isInvalidDecl()) { 8893 // Ignore all the rest of this. 8894 } else if (!D.isRedeclaration()) { 8895 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8896 AddToScope }; 8897 // Fake up an access specifier if it's supposed to be a class member. 8898 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8899 NewFD->setAccess(AS_public); 8900 8901 // Qualified decls generally require a previous declaration. 8902 if (D.getCXXScopeSpec().isSet()) { 8903 // ...with the major exception of templated-scope or 8904 // dependent-scope friend declarations. 8905 8906 // TODO: we currently also suppress this check in dependent 8907 // contexts because (1) the parameter depth will be off when 8908 // matching friend templates and (2) we might actually be 8909 // selecting a friend based on a dependent factor. But there 8910 // are situations where these conditions don't apply and we 8911 // can actually do this check immediately. 8912 if (isFriend && 8913 (TemplateParamLists.size() || 8914 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8915 CurContext->isDependentContext())) { 8916 // ignore these 8917 } else { 8918 // The user tried to provide an out-of-line definition for a 8919 // function that is a member of a class or namespace, but there 8920 // was no such member function declared (C++ [class.mfct]p2, 8921 // C++ [namespace.memdef]p2). For example: 8922 // 8923 // class X { 8924 // void f() const; 8925 // }; 8926 // 8927 // void X::f() { } // ill-formed 8928 // 8929 // Complain about this problem, and attempt to suggest close 8930 // matches (e.g., those that differ only in cv-qualifiers and 8931 // whether the parameter types are references). 8932 8933 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8934 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8935 AddToScope = ExtraArgs.AddToScope; 8936 return Result; 8937 } 8938 } 8939 8940 // Unqualified local friend declarations are required to resolve 8941 // to something. 8942 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8943 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8944 *this, Previous, NewFD, ExtraArgs, true, S)) { 8945 AddToScope = ExtraArgs.AddToScope; 8946 return Result; 8947 } 8948 } 8949 } else if (!D.isFunctionDefinition() && 8950 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8951 !isFriend && !isFunctionTemplateSpecialization && 8952 !isMemberSpecialization) { 8953 // An out-of-line member function declaration must also be a 8954 // definition (C++ [class.mfct]p2). 8955 // Note that this is not the case for explicit specializations of 8956 // function templates or member functions of class templates, per 8957 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8958 // extension for compatibility with old SWIG code which likes to 8959 // generate them. 8960 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8961 << D.getCXXScopeSpec().getRange(); 8962 } 8963 } 8964 8965 ProcessPragmaWeak(S, NewFD); 8966 checkAttributesAfterMerging(*this, *NewFD); 8967 8968 AddKnownFunctionAttributes(NewFD); 8969 8970 if (NewFD->hasAttr<OverloadableAttr>() && 8971 !NewFD->getType()->getAs<FunctionProtoType>()) { 8972 Diag(NewFD->getLocation(), 8973 diag::err_attribute_overloadable_no_prototype) 8974 << NewFD; 8975 8976 // Turn this into a variadic function with no parameters. 8977 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8978 FunctionProtoType::ExtProtoInfo EPI( 8979 Context.getDefaultCallingConvention(true, false)); 8980 EPI.Variadic = true; 8981 EPI.ExtInfo = FT->getExtInfo(); 8982 8983 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8984 NewFD->setType(R); 8985 } 8986 8987 // If there's a #pragma GCC visibility in scope, and this isn't a class 8988 // member, set the visibility of this function. 8989 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8990 AddPushedVisibilityAttribute(NewFD); 8991 8992 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8993 // marking the function. 8994 AddCFAuditedAttribute(NewFD); 8995 8996 // If this is a function definition, check if we have to apply optnone due to 8997 // a pragma. 8998 if(D.isFunctionDefinition()) 8999 AddRangeBasedOptnone(NewFD); 9000 9001 // If this is the first declaration of an extern C variable, update 9002 // the map of such variables. 9003 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9004 isIncompleteDeclExternC(*this, NewFD)) 9005 RegisterLocallyScopedExternCDecl(NewFD, S); 9006 9007 // Set this FunctionDecl's range up to the right paren. 9008 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9009 9010 if (D.isRedeclaration() && !Previous.empty()) { 9011 checkDLLAttributeRedeclaration( 9012 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 9013 isMemberSpecialization || isFunctionTemplateSpecialization, 9014 D.isFunctionDefinition()); 9015 } 9016 9017 if (getLangOpts().CUDA) { 9018 IdentifierInfo *II = NewFD->getIdentifier(); 9019 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 9020 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9021 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9022 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9023 9024 Context.setcudaConfigureCallDecl(NewFD); 9025 } 9026 9027 // Variadic functions, other than a *declaration* of printf, are not allowed 9028 // in device-side CUDA code, unless someone passed 9029 // -fcuda-allow-variadic-functions. 9030 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9031 (NewFD->hasAttr<CUDADeviceAttr>() || 9032 NewFD->hasAttr<CUDAGlobalAttr>()) && 9033 !(II && II->isStr("printf") && NewFD->isExternC() && 9034 !D.isFunctionDefinition())) { 9035 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9036 } 9037 } 9038 9039 MarkUnusedFileScopedDecl(NewFD); 9040 9041 if (getLangOpts().CPlusPlus) { 9042 if (FunctionTemplate) { 9043 if (NewFD->isInvalidDecl()) 9044 FunctionTemplate->setInvalidDecl(); 9045 return FunctionTemplate; 9046 } 9047 9048 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9049 CompleteMemberSpecialization(NewFD, Previous); 9050 } 9051 9052 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9053 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9054 if ((getLangOpts().OpenCLVersion >= 120) 9055 && (SC == SC_Static)) { 9056 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9057 D.setInvalidType(); 9058 } 9059 9060 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9061 if (!NewFD->getReturnType()->isVoidType()) { 9062 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9063 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9064 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9065 : FixItHint()); 9066 D.setInvalidType(); 9067 } 9068 9069 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9070 for (auto Param : NewFD->parameters()) 9071 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9072 } 9073 for (const ParmVarDecl *Param : NewFD->parameters()) { 9074 QualType PT = Param->getType(); 9075 9076 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9077 // types. 9078 if (getLangOpts().OpenCLVersion >= 200) { 9079 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9080 QualType ElemTy = PipeTy->getElementType(); 9081 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9082 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9083 D.setInvalidType(); 9084 } 9085 } 9086 } 9087 } 9088 9089 // Here we have an function template explicit specialization at class scope. 9090 // The actually specialization will be postponed to template instatiation 9091 // time via the ClassScopeFunctionSpecializationDecl node. 9092 if (isDependentClassScopeExplicitSpecialization) { 9093 ClassScopeFunctionSpecializationDecl *NewSpec = 9094 ClassScopeFunctionSpecializationDecl::Create( 9095 Context, CurContext, SourceLocation(), 9096 cast<CXXMethodDecl>(NewFD), 9097 HasExplicitTemplateArgs, TemplateArgs); 9098 CurContext->addDecl(NewSpec); 9099 AddToScope = false; 9100 } 9101 9102 return NewFD; 9103 } 9104 9105 /// \brief Checks if the new declaration declared in dependent context must be 9106 /// put in the same redeclaration chain as the specified declaration. 9107 /// 9108 /// \param D Declaration that is checked. 9109 /// \param PrevDecl Previous declaration found with proper lookup method for the 9110 /// same declaration name. 9111 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9112 /// belongs to. 9113 /// 9114 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9115 // Any declarations should be put into redeclaration chains except for 9116 // friend declaration in a dependent context that names a function in 9117 // namespace scope. 9118 // 9119 // This allows to compile code like: 9120 // 9121 // void func(); 9122 // template<typename T> class C1 { friend void func() { } }; 9123 // template<typename T> class C2 { friend void func() { } }; 9124 // 9125 // This code snippet is a valid code unless both templates are instantiated. 9126 return !(D->getLexicalDeclContext()->isDependentContext() && 9127 D->getDeclContext()->isFileContext() && 9128 D->getFriendObjectKind() != Decl::FOK_None); 9129 } 9130 9131 /// \brief Perform semantic checking of a new function declaration. 9132 /// 9133 /// Performs semantic analysis of the new function declaration 9134 /// NewFD. This routine performs all semantic checking that does not 9135 /// require the actual declarator involved in the declaration, and is 9136 /// used both for the declaration of functions as they are parsed 9137 /// (called via ActOnDeclarator) and for the declaration of functions 9138 /// that have been instantiated via C++ template instantiation (called 9139 /// via InstantiateDecl). 9140 /// 9141 /// \param IsMemberSpecialization whether this new function declaration is 9142 /// a member specialization (that replaces any definition provided by the 9143 /// previous declaration). 9144 /// 9145 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9146 /// 9147 /// \returns true if the function declaration is a redeclaration. 9148 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9149 LookupResult &Previous, 9150 bool IsMemberSpecialization) { 9151 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9152 "Variably modified return types are not handled here"); 9153 9154 // Determine whether the type of this function should be merged with 9155 // a previous visible declaration. This never happens for functions in C++, 9156 // and always happens in C if the previous declaration was visible. 9157 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9158 !Previous.isShadowed(); 9159 9160 bool Redeclaration = false; 9161 NamedDecl *OldDecl = nullptr; 9162 9163 // Merge or overload the declaration with an existing declaration of 9164 // the same name, if appropriate. 9165 if (!Previous.empty()) { 9166 // Determine whether NewFD is an overload of PrevDecl or 9167 // a declaration that requires merging. If it's an overload, 9168 // there's no more work to do here; we'll just add the new 9169 // function to the scope. 9170 if (!AllowOverloadingOfFunction(Previous, Context)) { 9171 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9172 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9173 Redeclaration = true; 9174 OldDecl = Candidate; 9175 } 9176 } else { 9177 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9178 /*NewIsUsingDecl*/ false)) { 9179 case Ovl_Match: 9180 Redeclaration = true; 9181 break; 9182 9183 case Ovl_NonFunction: 9184 Redeclaration = true; 9185 break; 9186 9187 case Ovl_Overload: 9188 Redeclaration = false; 9189 break; 9190 } 9191 9192 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 9193 // If a function name is overloadable in C, then every function 9194 // with that name must be marked "overloadable". 9195 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 9196 << Redeclaration << NewFD; 9197 NamedDecl *OverloadedDecl = 9198 Redeclaration ? OldDecl : Previous.getRepresentativeDecl(); 9199 Diag(OverloadedDecl->getLocation(), 9200 diag::note_attribute_overloadable_prev_overload); 9201 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9202 } 9203 } 9204 } 9205 9206 // Check for a previous extern "C" declaration with this name. 9207 if (!Redeclaration && 9208 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9209 if (!Previous.empty()) { 9210 // This is an extern "C" declaration with the same name as a previous 9211 // declaration, and thus redeclares that entity... 9212 Redeclaration = true; 9213 OldDecl = Previous.getFoundDecl(); 9214 MergeTypeWithPrevious = false; 9215 9216 // ... except in the presence of __attribute__((overloadable)). 9217 if (OldDecl->hasAttr<OverloadableAttr>()) { 9218 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 9219 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 9220 << Redeclaration << NewFD; 9221 Diag(Previous.getFoundDecl()->getLocation(), 9222 diag::note_attribute_overloadable_prev_overload); 9223 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9224 } 9225 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9226 Redeclaration = false; 9227 OldDecl = nullptr; 9228 } 9229 } 9230 } 9231 } 9232 9233 // C++11 [dcl.constexpr]p8: 9234 // A constexpr specifier for a non-static member function that is not 9235 // a constructor declares that member function to be const. 9236 // 9237 // This needs to be delayed until we know whether this is an out-of-line 9238 // definition of a static member function. 9239 // 9240 // This rule is not present in C++1y, so we produce a backwards 9241 // compatibility warning whenever it happens in C++11. 9242 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9243 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9244 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9245 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9246 CXXMethodDecl *OldMD = nullptr; 9247 if (OldDecl) 9248 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9249 if (!OldMD || !OldMD->isStatic()) { 9250 const FunctionProtoType *FPT = 9251 MD->getType()->castAs<FunctionProtoType>(); 9252 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9253 EPI.TypeQuals |= Qualifiers::Const; 9254 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9255 FPT->getParamTypes(), EPI)); 9256 9257 // Warn that we did this, if we're not performing template instantiation. 9258 // In that case, we'll have warned already when the template was defined. 9259 if (!inTemplateInstantiation()) { 9260 SourceLocation AddConstLoc; 9261 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9262 .IgnoreParens().getAs<FunctionTypeLoc>()) 9263 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9264 9265 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9266 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9267 } 9268 } 9269 } 9270 9271 if (Redeclaration) { 9272 // NewFD and OldDecl represent declarations that need to be 9273 // merged. 9274 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9275 NewFD->setInvalidDecl(); 9276 return Redeclaration; 9277 } 9278 9279 Previous.clear(); 9280 Previous.addDecl(OldDecl); 9281 9282 if (FunctionTemplateDecl *OldTemplateDecl 9283 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9284 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9285 FunctionTemplateDecl *NewTemplateDecl 9286 = NewFD->getDescribedFunctionTemplate(); 9287 assert(NewTemplateDecl && "Template/non-template mismatch"); 9288 if (CXXMethodDecl *Method 9289 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9290 Method->setAccess(OldTemplateDecl->getAccess()); 9291 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9292 } 9293 9294 // If this is an explicit specialization of a member that is a function 9295 // template, mark it as a member specialization. 9296 if (IsMemberSpecialization && 9297 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9298 NewTemplateDecl->setMemberSpecialization(); 9299 assert(OldTemplateDecl->isMemberSpecialization()); 9300 // Explicit specializations of a member template do not inherit deleted 9301 // status from the parent member template that they are specializing. 9302 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9303 FunctionDecl *const OldTemplatedDecl = 9304 OldTemplateDecl->getTemplatedDecl(); 9305 // FIXME: This assert will not hold in the presence of modules. 9306 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9307 // FIXME: We need an update record for this AST mutation. 9308 OldTemplatedDecl->setDeletedAsWritten(false); 9309 } 9310 } 9311 9312 } else { 9313 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9314 // This needs to happen first so that 'inline' propagates. 9315 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9316 if (isa<CXXMethodDecl>(NewFD)) 9317 NewFD->setAccess(OldDecl->getAccess()); 9318 } 9319 } 9320 } 9321 9322 // Semantic checking for this function declaration (in isolation). 9323 9324 if (getLangOpts().CPlusPlus) { 9325 // C++-specific checks. 9326 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9327 CheckConstructor(Constructor); 9328 } else if (CXXDestructorDecl *Destructor = 9329 dyn_cast<CXXDestructorDecl>(NewFD)) { 9330 CXXRecordDecl *Record = Destructor->getParent(); 9331 QualType ClassType = Context.getTypeDeclType(Record); 9332 9333 // FIXME: Shouldn't we be able to perform this check even when the class 9334 // type is dependent? Both gcc and edg can handle that. 9335 if (!ClassType->isDependentType()) { 9336 DeclarationName Name 9337 = Context.DeclarationNames.getCXXDestructorName( 9338 Context.getCanonicalType(ClassType)); 9339 if (NewFD->getDeclName() != Name) { 9340 Diag(NewFD->getLocation(), diag::err_destructor_name); 9341 NewFD->setInvalidDecl(); 9342 return Redeclaration; 9343 } 9344 } 9345 } else if (CXXConversionDecl *Conversion 9346 = dyn_cast<CXXConversionDecl>(NewFD)) { 9347 ActOnConversionDeclarator(Conversion); 9348 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9349 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9350 CheckDeductionGuideTemplate(TD); 9351 9352 // A deduction guide is not on the list of entities that can be 9353 // explicitly specialized. 9354 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9355 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9356 << /*explicit specialization*/ 1; 9357 } 9358 9359 // Find any virtual functions that this function overrides. 9360 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9361 if (!Method->isFunctionTemplateSpecialization() && 9362 !Method->getDescribedFunctionTemplate() && 9363 Method->isCanonicalDecl()) { 9364 if (AddOverriddenMethods(Method->getParent(), Method)) { 9365 // If the function was marked as "static", we have a problem. 9366 if (NewFD->getStorageClass() == SC_Static) { 9367 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9368 } 9369 } 9370 } 9371 9372 if (Method->isStatic()) 9373 checkThisInStaticMemberFunctionType(Method); 9374 } 9375 9376 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9377 if (NewFD->isOverloadedOperator() && 9378 CheckOverloadedOperatorDeclaration(NewFD)) { 9379 NewFD->setInvalidDecl(); 9380 return Redeclaration; 9381 } 9382 9383 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9384 if (NewFD->getLiteralIdentifier() && 9385 CheckLiteralOperatorDeclaration(NewFD)) { 9386 NewFD->setInvalidDecl(); 9387 return Redeclaration; 9388 } 9389 9390 // In C++, check default arguments now that we have merged decls. Unless 9391 // the lexical context is the class, because in this case this is done 9392 // during delayed parsing anyway. 9393 if (!CurContext->isRecord()) 9394 CheckCXXDefaultArguments(NewFD); 9395 9396 // If this function declares a builtin function, check the type of this 9397 // declaration against the expected type for the builtin. 9398 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9399 ASTContext::GetBuiltinTypeError Error; 9400 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9401 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9402 // If the type of the builtin differs only in its exception 9403 // specification, that's OK. 9404 // FIXME: If the types do differ in this way, it would be better to 9405 // retain the 'noexcept' form of the type. 9406 if (!T.isNull() && 9407 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9408 NewFD->getType())) 9409 // The type of this function differs from the type of the builtin, 9410 // so forget about the builtin entirely. 9411 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9412 } 9413 9414 // If this function is declared as being extern "C", then check to see if 9415 // the function returns a UDT (class, struct, or union type) that is not C 9416 // compatible, and if it does, warn the user. 9417 // But, issue any diagnostic on the first declaration only. 9418 if (Previous.empty() && NewFD->isExternC()) { 9419 QualType R = NewFD->getReturnType(); 9420 if (R->isIncompleteType() && !R->isVoidType()) 9421 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9422 << NewFD << R; 9423 else if (!R.isPODType(Context) && !R->isVoidType() && 9424 !R->isObjCObjectPointerType()) 9425 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9426 } 9427 9428 // C++1z [dcl.fct]p6: 9429 // [...] whether the function has a non-throwing exception-specification 9430 // [is] part of the function type 9431 // 9432 // This results in an ABI break between C++14 and C++17 for functions whose 9433 // declared type includes an exception-specification in a parameter or 9434 // return type. (Exception specifications on the function itself are OK in 9435 // most cases, and exception specifications are not permitted in most other 9436 // contexts where they could make it into a mangling.) 9437 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9438 auto HasNoexcept = [&](QualType T) -> bool { 9439 // Strip off declarator chunks that could be between us and a function 9440 // type. We don't need to look far, exception specifications are very 9441 // restricted prior to C++17. 9442 if (auto *RT = T->getAs<ReferenceType>()) 9443 T = RT->getPointeeType(); 9444 else if (T->isAnyPointerType()) 9445 T = T->getPointeeType(); 9446 else if (auto *MPT = T->getAs<MemberPointerType>()) 9447 T = MPT->getPointeeType(); 9448 if (auto *FPT = T->getAs<FunctionProtoType>()) 9449 if (FPT->isNothrow(Context)) 9450 return true; 9451 return false; 9452 }; 9453 9454 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9455 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9456 for (QualType T : FPT->param_types()) 9457 AnyNoexcept |= HasNoexcept(T); 9458 if (AnyNoexcept) 9459 Diag(NewFD->getLocation(), 9460 diag::warn_cxx1z_compat_exception_spec_in_signature) 9461 << NewFD; 9462 } 9463 9464 if (!Redeclaration && LangOpts.CUDA) 9465 checkCUDATargetOverload(NewFD, Previous); 9466 } 9467 return Redeclaration; 9468 } 9469 9470 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9471 // C++11 [basic.start.main]p3: 9472 // A program that [...] declares main to be inline, static or 9473 // constexpr is ill-formed. 9474 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9475 // appear in a declaration of main. 9476 // static main is not an error under C99, but we should warn about it. 9477 // We accept _Noreturn main as an extension. 9478 if (FD->getStorageClass() == SC_Static) 9479 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9480 ? diag::err_static_main : diag::warn_static_main) 9481 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9482 if (FD->isInlineSpecified()) 9483 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9484 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9485 if (DS.isNoreturnSpecified()) { 9486 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9487 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9488 Diag(NoreturnLoc, diag::ext_noreturn_main); 9489 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9490 << FixItHint::CreateRemoval(NoreturnRange); 9491 } 9492 if (FD->isConstexpr()) { 9493 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9494 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9495 FD->setConstexpr(false); 9496 } 9497 9498 if (getLangOpts().OpenCL) { 9499 Diag(FD->getLocation(), diag::err_opencl_no_main) 9500 << FD->hasAttr<OpenCLKernelAttr>(); 9501 FD->setInvalidDecl(); 9502 return; 9503 } 9504 9505 QualType T = FD->getType(); 9506 assert(T->isFunctionType() && "function decl is not of function type"); 9507 const FunctionType* FT = T->castAs<FunctionType>(); 9508 9509 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9510 // In C with GNU extensions we allow main() to have non-integer return 9511 // type, but we should warn about the extension, and we disable the 9512 // implicit-return-zero rule. 9513 9514 // GCC in C mode accepts qualified 'int'. 9515 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9516 FD->setHasImplicitReturnZero(true); 9517 else { 9518 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9519 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9520 if (RTRange.isValid()) 9521 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9522 << FixItHint::CreateReplacement(RTRange, "int"); 9523 } 9524 } else { 9525 // In C and C++, main magically returns 0 if you fall off the end; 9526 // set the flag which tells us that. 9527 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9528 9529 // All the standards say that main() should return 'int'. 9530 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9531 FD->setHasImplicitReturnZero(true); 9532 else { 9533 // Otherwise, this is just a flat-out error. 9534 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9535 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9536 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9537 : FixItHint()); 9538 FD->setInvalidDecl(true); 9539 } 9540 } 9541 9542 // Treat protoless main() as nullary. 9543 if (isa<FunctionNoProtoType>(FT)) return; 9544 9545 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9546 unsigned nparams = FTP->getNumParams(); 9547 assert(FD->getNumParams() == nparams); 9548 9549 bool HasExtraParameters = (nparams > 3); 9550 9551 if (FTP->isVariadic()) { 9552 Diag(FD->getLocation(), diag::ext_variadic_main); 9553 // FIXME: if we had information about the location of the ellipsis, we 9554 // could add a FixIt hint to remove it as a parameter. 9555 } 9556 9557 // Darwin passes an undocumented fourth argument of type char**. If 9558 // other platforms start sprouting these, the logic below will start 9559 // getting shifty. 9560 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9561 HasExtraParameters = false; 9562 9563 if (HasExtraParameters) { 9564 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9565 FD->setInvalidDecl(true); 9566 nparams = 3; 9567 } 9568 9569 // FIXME: a lot of the following diagnostics would be improved 9570 // if we had some location information about types. 9571 9572 QualType CharPP = 9573 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9574 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9575 9576 for (unsigned i = 0; i < nparams; ++i) { 9577 QualType AT = FTP->getParamType(i); 9578 9579 bool mismatch = true; 9580 9581 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9582 mismatch = false; 9583 else if (Expected[i] == CharPP) { 9584 // As an extension, the following forms are okay: 9585 // char const ** 9586 // char const * const * 9587 // char * const * 9588 9589 QualifierCollector qs; 9590 const PointerType* PT; 9591 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9592 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9593 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9594 Context.CharTy)) { 9595 qs.removeConst(); 9596 mismatch = !qs.empty(); 9597 } 9598 } 9599 9600 if (mismatch) { 9601 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9602 // TODO: suggest replacing given type with expected type 9603 FD->setInvalidDecl(true); 9604 } 9605 } 9606 9607 if (nparams == 1 && !FD->isInvalidDecl()) { 9608 Diag(FD->getLocation(), diag::warn_main_one_arg); 9609 } 9610 9611 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9612 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9613 FD->setInvalidDecl(); 9614 } 9615 } 9616 9617 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9618 QualType T = FD->getType(); 9619 assert(T->isFunctionType() && "function decl is not of function type"); 9620 const FunctionType *FT = T->castAs<FunctionType>(); 9621 9622 // Set an implicit return of 'zero' if the function can return some integral, 9623 // enumeration, pointer or nullptr type. 9624 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9625 FT->getReturnType()->isAnyPointerType() || 9626 FT->getReturnType()->isNullPtrType()) 9627 // DllMain is exempt because a return value of zero means it failed. 9628 if (FD->getName() != "DllMain") 9629 FD->setHasImplicitReturnZero(true); 9630 9631 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9632 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9633 FD->setInvalidDecl(); 9634 } 9635 } 9636 9637 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9638 // FIXME: Need strict checking. In C89, we need to check for 9639 // any assignment, increment, decrement, function-calls, or 9640 // commas outside of a sizeof. In C99, it's the same list, 9641 // except that the aforementioned are allowed in unevaluated 9642 // expressions. Everything else falls under the 9643 // "may accept other forms of constant expressions" exception. 9644 // (We never end up here for C++, so the constant expression 9645 // rules there don't matter.) 9646 const Expr *Culprit; 9647 if (Init->isConstantInitializer(Context, false, &Culprit)) 9648 return false; 9649 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9650 << Culprit->getSourceRange(); 9651 return true; 9652 } 9653 9654 namespace { 9655 // Visits an initialization expression to see if OrigDecl is evaluated in 9656 // its own initialization and throws a warning if it does. 9657 class SelfReferenceChecker 9658 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9659 Sema &S; 9660 Decl *OrigDecl; 9661 bool isRecordType; 9662 bool isPODType; 9663 bool isReferenceType; 9664 9665 bool isInitList; 9666 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9667 9668 public: 9669 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9670 9671 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9672 S(S), OrigDecl(OrigDecl) { 9673 isPODType = false; 9674 isRecordType = false; 9675 isReferenceType = false; 9676 isInitList = false; 9677 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9678 isPODType = VD->getType().isPODType(S.Context); 9679 isRecordType = VD->getType()->isRecordType(); 9680 isReferenceType = VD->getType()->isReferenceType(); 9681 } 9682 } 9683 9684 // For most expressions, just call the visitor. For initializer lists, 9685 // track the index of the field being initialized since fields are 9686 // initialized in order allowing use of previously initialized fields. 9687 void CheckExpr(Expr *E) { 9688 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9689 if (!InitList) { 9690 Visit(E); 9691 return; 9692 } 9693 9694 // Track and increment the index here. 9695 isInitList = true; 9696 InitFieldIndex.push_back(0); 9697 for (auto Child : InitList->children()) { 9698 CheckExpr(cast<Expr>(Child)); 9699 ++InitFieldIndex.back(); 9700 } 9701 InitFieldIndex.pop_back(); 9702 } 9703 9704 // Returns true if MemberExpr is checked and no further checking is needed. 9705 // Returns false if additional checking is required. 9706 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9707 llvm::SmallVector<FieldDecl*, 4> Fields; 9708 Expr *Base = E; 9709 bool ReferenceField = false; 9710 9711 // Get the field memebers used. 9712 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9713 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9714 if (!FD) 9715 return false; 9716 Fields.push_back(FD); 9717 if (FD->getType()->isReferenceType()) 9718 ReferenceField = true; 9719 Base = ME->getBase()->IgnoreParenImpCasts(); 9720 } 9721 9722 // Keep checking only if the base Decl is the same. 9723 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9724 if (!DRE || DRE->getDecl() != OrigDecl) 9725 return false; 9726 9727 // A reference field can be bound to an unininitialized field. 9728 if (CheckReference && !ReferenceField) 9729 return true; 9730 9731 // Convert FieldDecls to their index number. 9732 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9733 for (const FieldDecl *I : llvm::reverse(Fields)) 9734 UsedFieldIndex.push_back(I->getFieldIndex()); 9735 9736 // See if a warning is needed by checking the first difference in index 9737 // numbers. If field being used has index less than the field being 9738 // initialized, then the use is safe. 9739 for (auto UsedIter = UsedFieldIndex.begin(), 9740 UsedEnd = UsedFieldIndex.end(), 9741 OrigIter = InitFieldIndex.begin(), 9742 OrigEnd = InitFieldIndex.end(); 9743 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9744 if (*UsedIter < *OrigIter) 9745 return true; 9746 if (*UsedIter > *OrigIter) 9747 break; 9748 } 9749 9750 // TODO: Add a different warning which will print the field names. 9751 HandleDeclRefExpr(DRE); 9752 return true; 9753 } 9754 9755 // For most expressions, the cast is directly above the DeclRefExpr. 9756 // For conditional operators, the cast can be outside the conditional 9757 // operator if both expressions are DeclRefExpr's. 9758 void HandleValue(Expr *E) { 9759 E = E->IgnoreParens(); 9760 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9761 HandleDeclRefExpr(DRE); 9762 return; 9763 } 9764 9765 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9766 Visit(CO->getCond()); 9767 HandleValue(CO->getTrueExpr()); 9768 HandleValue(CO->getFalseExpr()); 9769 return; 9770 } 9771 9772 if (BinaryConditionalOperator *BCO = 9773 dyn_cast<BinaryConditionalOperator>(E)) { 9774 Visit(BCO->getCond()); 9775 HandleValue(BCO->getFalseExpr()); 9776 return; 9777 } 9778 9779 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9780 HandleValue(OVE->getSourceExpr()); 9781 return; 9782 } 9783 9784 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9785 if (BO->getOpcode() == BO_Comma) { 9786 Visit(BO->getLHS()); 9787 HandleValue(BO->getRHS()); 9788 return; 9789 } 9790 } 9791 9792 if (isa<MemberExpr>(E)) { 9793 if (isInitList) { 9794 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9795 false /*CheckReference*/)) 9796 return; 9797 } 9798 9799 Expr *Base = E->IgnoreParenImpCasts(); 9800 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9801 // Check for static member variables and don't warn on them. 9802 if (!isa<FieldDecl>(ME->getMemberDecl())) 9803 return; 9804 Base = ME->getBase()->IgnoreParenImpCasts(); 9805 } 9806 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9807 HandleDeclRefExpr(DRE); 9808 return; 9809 } 9810 9811 Visit(E); 9812 } 9813 9814 // Reference types not handled in HandleValue are handled here since all 9815 // uses of references are bad, not just r-value uses. 9816 void VisitDeclRefExpr(DeclRefExpr *E) { 9817 if (isReferenceType) 9818 HandleDeclRefExpr(E); 9819 } 9820 9821 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9822 if (E->getCastKind() == CK_LValueToRValue) { 9823 HandleValue(E->getSubExpr()); 9824 return; 9825 } 9826 9827 Inherited::VisitImplicitCastExpr(E); 9828 } 9829 9830 void VisitMemberExpr(MemberExpr *E) { 9831 if (isInitList) { 9832 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9833 return; 9834 } 9835 9836 // Don't warn on arrays since they can be treated as pointers. 9837 if (E->getType()->canDecayToPointerType()) return; 9838 9839 // Warn when a non-static method call is followed by non-static member 9840 // field accesses, which is followed by a DeclRefExpr. 9841 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9842 bool Warn = (MD && !MD->isStatic()); 9843 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9844 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9845 if (!isa<FieldDecl>(ME->getMemberDecl())) 9846 Warn = false; 9847 Base = ME->getBase()->IgnoreParenImpCasts(); 9848 } 9849 9850 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9851 if (Warn) 9852 HandleDeclRefExpr(DRE); 9853 return; 9854 } 9855 9856 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9857 // Visit that expression. 9858 Visit(Base); 9859 } 9860 9861 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9862 Expr *Callee = E->getCallee(); 9863 9864 if (isa<UnresolvedLookupExpr>(Callee)) 9865 return Inherited::VisitCXXOperatorCallExpr(E); 9866 9867 Visit(Callee); 9868 for (auto Arg: E->arguments()) 9869 HandleValue(Arg->IgnoreParenImpCasts()); 9870 } 9871 9872 void VisitUnaryOperator(UnaryOperator *E) { 9873 // For POD record types, addresses of its own members are well-defined. 9874 if (E->getOpcode() == UO_AddrOf && isRecordType && 9875 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9876 if (!isPODType) 9877 HandleValue(E->getSubExpr()); 9878 return; 9879 } 9880 9881 if (E->isIncrementDecrementOp()) { 9882 HandleValue(E->getSubExpr()); 9883 return; 9884 } 9885 9886 Inherited::VisitUnaryOperator(E); 9887 } 9888 9889 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9890 9891 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9892 if (E->getConstructor()->isCopyConstructor()) { 9893 Expr *ArgExpr = E->getArg(0); 9894 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9895 if (ILE->getNumInits() == 1) 9896 ArgExpr = ILE->getInit(0); 9897 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9898 if (ICE->getCastKind() == CK_NoOp) 9899 ArgExpr = ICE->getSubExpr(); 9900 HandleValue(ArgExpr); 9901 return; 9902 } 9903 Inherited::VisitCXXConstructExpr(E); 9904 } 9905 9906 void VisitCallExpr(CallExpr *E) { 9907 // Treat std::move as a use. 9908 if (E->getNumArgs() == 1) { 9909 if (FunctionDecl *FD = E->getDirectCallee()) { 9910 if (FD->isInStdNamespace() && FD->getIdentifier() && 9911 FD->getIdentifier()->isStr("move")) { 9912 HandleValue(E->getArg(0)); 9913 return; 9914 } 9915 } 9916 } 9917 9918 Inherited::VisitCallExpr(E); 9919 } 9920 9921 void VisitBinaryOperator(BinaryOperator *E) { 9922 if (E->isCompoundAssignmentOp()) { 9923 HandleValue(E->getLHS()); 9924 Visit(E->getRHS()); 9925 return; 9926 } 9927 9928 Inherited::VisitBinaryOperator(E); 9929 } 9930 9931 // A custom visitor for BinaryConditionalOperator is needed because the 9932 // regular visitor would check the condition and true expression separately 9933 // but both point to the same place giving duplicate diagnostics. 9934 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9935 Visit(E->getCond()); 9936 Visit(E->getFalseExpr()); 9937 } 9938 9939 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9940 Decl* ReferenceDecl = DRE->getDecl(); 9941 if (OrigDecl != ReferenceDecl) return; 9942 unsigned diag; 9943 if (isReferenceType) { 9944 diag = diag::warn_uninit_self_reference_in_reference_init; 9945 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9946 diag = diag::warn_static_self_reference_in_init; 9947 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9948 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9949 DRE->getDecl()->getType()->isRecordType()) { 9950 diag = diag::warn_uninit_self_reference_in_init; 9951 } else { 9952 // Local variables will be handled by the CFG analysis. 9953 return; 9954 } 9955 9956 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9957 S.PDiag(diag) 9958 << DRE->getNameInfo().getName() 9959 << OrigDecl->getLocation() 9960 << DRE->getSourceRange()); 9961 } 9962 }; 9963 9964 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9965 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9966 bool DirectInit) { 9967 // Parameters arguments are occassionially constructed with itself, 9968 // for instance, in recursive functions. Skip them. 9969 if (isa<ParmVarDecl>(OrigDecl)) 9970 return; 9971 9972 E = E->IgnoreParens(); 9973 9974 // Skip checking T a = a where T is not a record or reference type. 9975 // Doing so is a way to silence uninitialized warnings. 9976 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9977 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9978 if (ICE->getCastKind() == CK_LValueToRValue) 9979 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9980 if (DRE->getDecl() == OrigDecl) 9981 return; 9982 9983 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9984 } 9985 } // end anonymous namespace 9986 9987 namespace { 9988 // Simple wrapper to add the name of a variable or (if no variable is 9989 // available) a DeclarationName into a diagnostic. 9990 struct VarDeclOrName { 9991 VarDecl *VDecl; 9992 DeclarationName Name; 9993 9994 friend const Sema::SemaDiagnosticBuilder & 9995 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 9996 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 9997 } 9998 }; 9999 } // end anonymous namespace 10000 10001 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10002 DeclarationName Name, QualType Type, 10003 TypeSourceInfo *TSI, 10004 SourceRange Range, bool DirectInit, 10005 Expr *Init) { 10006 bool IsInitCapture = !VDecl; 10007 assert((!VDecl || !VDecl->isInitCapture()) && 10008 "init captures are expected to be deduced prior to initialization"); 10009 10010 VarDeclOrName VN{VDecl, Name}; 10011 10012 DeducedType *Deduced = Type->getContainedDeducedType(); 10013 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10014 10015 // C++11 [dcl.spec.auto]p3 10016 if (!Init) { 10017 assert(VDecl && "no init for init capture deduction?"); 10018 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10019 << VDecl->getDeclName() << Type; 10020 return QualType(); 10021 } 10022 10023 ArrayRef<Expr*> DeduceInits = Init; 10024 if (DirectInit) { 10025 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10026 DeduceInits = PL->exprs(); 10027 } 10028 10029 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10030 assert(VDecl && "non-auto type for init capture deduction?"); 10031 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10032 InitializationKind Kind = InitializationKind::CreateForInit( 10033 VDecl->getLocation(), DirectInit, Init); 10034 // FIXME: Initialization should not be taking a mutable list of inits. 10035 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10036 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10037 InitsCopy); 10038 } 10039 10040 if (DirectInit) { 10041 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10042 DeduceInits = IL->inits(); 10043 } 10044 10045 // Deduction only works if we have exactly one source expression. 10046 if (DeduceInits.empty()) { 10047 // It isn't possible to write this directly, but it is possible to 10048 // end up in this situation with "auto x(some_pack...);" 10049 Diag(Init->getLocStart(), IsInitCapture 10050 ? diag::err_init_capture_no_expression 10051 : diag::err_auto_var_init_no_expression) 10052 << VN << Type << Range; 10053 return QualType(); 10054 } 10055 10056 if (DeduceInits.size() > 1) { 10057 Diag(DeduceInits[1]->getLocStart(), 10058 IsInitCapture ? diag::err_init_capture_multiple_expressions 10059 : diag::err_auto_var_init_multiple_expressions) 10060 << VN << Type << Range; 10061 return QualType(); 10062 } 10063 10064 Expr *DeduceInit = DeduceInits[0]; 10065 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10066 Diag(Init->getLocStart(), IsInitCapture 10067 ? diag::err_init_capture_paren_braces 10068 : diag::err_auto_var_init_paren_braces) 10069 << isa<InitListExpr>(Init) << VN << Type << Range; 10070 return QualType(); 10071 } 10072 10073 // Expressions default to 'id' when we're in a debugger. 10074 bool DefaultedAnyToId = false; 10075 if (getLangOpts().DebuggerCastResultToId && 10076 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10077 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10078 if (Result.isInvalid()) { 10079 return QualType(); 10080 } 10081 Init = Result.get(); 10082 DefaultedAnyToId = true; 10083 } 10084 10085 // C++ [dcl.decomp]p1: 10086 // If the assignment-expression [...] has array type A and no ref-qualifier 10087 // is present, e has type cv A 10088 if (VDecl && isa<DecompositionDecl>(VDecl) && 10089 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10090 DeduceInit->getType()->isConstantArrayType()) 10091 return Context.getQualifiedType(DeduceInit->getType(), 10092 Type.getQualifiers()); 10093 10094 QualType DeducedType; 10095 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10096 if (!IsInitCapture) 10097 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10098 else if (isa<InitListExpr>(Init)) 10099 Diag(Range.getBegin(), 10100 diag::err_init_capture_deduction_failure_from_init_list) 10101 << VN 10102 << (DeduceInit->getType().isNull() ? TSI->getType() 10103 : DeduceInit->getType()) 10104 << DeduceInit->getSourceRange(); 10105 else 10106 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10107 << VN << TSI->getType() 10108 << (DeduceInit->getType().isNull() ? TSI->getType() 10109 : DeduceInit->getType()) 10110 << DeduceInit->getSourceRange(); 10111 } 10112 10113 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10114 // 'id' instead of a specific object type prevents most of our usual 10115 // checks. 10116 // We only want to warn outside of template instantiations, though: 10117 // inside a template, the 'id' could have come from a parameter. 10118 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10119 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10120 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10121 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10122 } 10123 10124 return DeducedType; 10125 } 10126 10127 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10128 Expr *Init) { 10129 QualType DeducedType = deduceVarTypeFromInitializer( 10130 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10131 VDecl->getSourceRange(), DirectInit, Init); 10132 if (DeducedType.isNull()) { 10133 VDecl->setInvalidDecl(); 10134 return true; 10135 } 10136 10137 VDecl->setType(DeducedType); 10138 assert(VDecl->isLinkageValid()); 10139 10140 // In ARC, infer lifetime. 10141 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10142 VDecl->setInvalidDecl(); 10143 10144 // If this is a redeclaration, check that the type we just deduced matches 10145 // the previously declared type. 10146 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10147 // We never need to merge the type, because we cannot form an incomplete 10148 // array of auto, nor deduce such a type. 10149 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10150 } 10151 10152 // Check the deduced type is valid for a variable declaration. 10153 CheckVariableDeclarationType(VDecl); 10154 return VDecl->isInvalidDecl(); 10155 } 10156 10157 /// AddInitializerToDecl - Adds the initializer Init to the 10158 /// declaration dcl. If DirectInit is true, this is C++ direct 10159 /// initialization rather than copy initialization. 10160 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10161 // If there is no declaration, there was an error parsing it. Just ignore 10162 // the initializer. 10163 if (!RealDecl || RealDecl->isInvalidDecl()) { 10164 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10165 return; 10166 } 10167 10168 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10169 // Pure-specifiers are handled in ActOnPureSpecifier. 10170 Diag(Method->getLocation(), diag::err_member_function_initialization) 10171 << Method->getDeclName() << Init->getSourceRange(); 10172 Method->setInvalidDecl(); 10173 return; 10174 } 10175 10176 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10177 if (!VDecl) { 10178 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10179 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10180 RealDecl->setInvalidDecl(); 10181 return; 10182 } 10183 10184 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10185 if (VDecl->getType()->isUndeducedType()) { 10186 // Attempt typo correction early so that the type of the init expression can 10187 // be deduced based on the chosen correction if the original init contains a 10188 // TypoExpr. 10189 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10190 if (!Res.isUsable()) { 10191 RealDecl->setInvalidDecl(); 10192 return; 10193 } 10194 Init = Res.get(); 10195 10196 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10197 return; 10198 } 10199 10200 // dllimport cannot be used on variable definitions. 10201 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10202 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10203 VDecl->setInvalidDecl(); 10204 return; 10205 } 10206 10207 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10208 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10209 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10210 VDecl->setInvalidDecl(); 10211 return; 10212 } 10213 10214 if (!VDecl->getType()->isDependentType()) { 10215 // A definition must end up with a complete type, which means it must be 10216 // complete with the restriction that an array type might be completed by 10217 // the initializer; note that later code assumes this restriction. 10218 QualType BaseDeclType = VDecl->getType(); 10219 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10220 BaseDeclType = Array->getElementType(); 10221 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10222 diag::err_typecheck_decl_incomplete_type)) { 10223 RealDecl->setInvalidDecl(); 10224 return; 10225 } 10226 10227 // The variable can not have an abstract class type. 10228 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10229 diag::err_abstract_type_in_decl, 10230 AbstractVariableType)) 10231 VDecl->setInvalidDecl(); 10232 } 10233 10234 // If adding the initializer will turn this declaration into a definition, 10235 // and we already have a definition for this variable, diagnose or otherwise 10236 // handle the situation. 10237 VarDecl *Def; 10238 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10239 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10240 !VDecl->isThisDeclarationADemotedDefinition() && 10241 checkVarDeclRedefinition(Def, VDecl)) 10242 return; 10243 10244 if (getLangOpts().CPlusPlus) { 10245 // C++ [class.static.data]p4 10246 // If a static data member is of const integral or const 10247 // enumeration type, its declaration in the class definition can 10248 // specify a constant-initializer which shall be an integral 10249 // constant expression (5.19). In that case, the member can appear 10250 // in integral constant expressions. The member shall still be 10251 // defined in a namespace scope if it is used in the program and the 10252 // namespace scope definition shall not contain an initializer. 10253 // 10254 // We already performed a redefinition check above, but for static 10255 // data members we also need to check whether there was an in-class 10256 // declaration with an initializer. 10257 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10258 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10259 << VDecl->getDeclName(); 10260 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10261 diag::note_previous_initializer) 10262 << 0; 10263 return; 10264 } 10265 10266 if (VDecl->hasLocalStorage()) 10267 getCurFunction()->setHasBranchProtectedScope(); 10268 10269 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10270 VDecl->setInvalidDecl(); 10271 return; 10272 } 10273 } 10274 10275 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10276 // a kernel function cannot be initialized." 10277 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10278 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10279 VDecl->setInvalidDecl(); 10280 return; 10281 } 10282 10283 // Get the decls type and save a reference for later, since 10284 // CheckInitializerTypes may change it. 10285 QualType DclT = VDecl->getType(), SavT = DclT; 10286 10287 // Expressions default to 'id' when we're in a debugger 10288 // and we are assigning it to a variable of Objective-C pointer type. 10289 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10290 Init->getType() == Context.UnknownAnyTy) { 10291 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10292 if (Result.isInvalid()) { 10293 VDecl->setInvalidDecl(); 10294 return; 10295 } 10296 Init = Result.get(); 10297 } 10298 10299 // Perform the initialization. 10300 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10301 if (!VDecl->isInvalidDecl()) { 10302 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10303 InitializationKind Kind = InitializationKind::CreateForInit( 10304 VDecl->getLocation(), DirectInit, Init); 10305 10306 MultiExprArg Args = Init; 10307 if (CXXDirectInit) 10308 Args = MultiExprArg(CXXDirectInit->getExprs(), 10309 CXXDirectInit->getNumExprs()); 10310 10311 // Try to correct any TypoExprs in the initialization arguments. 10312 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10313 ExprResult Res = CorrectDelayedTyposInExpr( 10314 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10315 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10316 return Init.Failed() ? ExprError() : E; 10317 }); 10318 if (Res.isInvalid()) { 10319 VDecl->setInvalidDecl(); 10320 } else if (Res.get() != Args[Idx]) { 10321 Args[Idx] = Res.get(); 10322 } 10323 } 10324 if (VDecl->isInvalidDecl()) 10325 return; 10326 10327 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10328 /*TopLevelOfInitList=*/false, 10329 /*TreatUnavailableAsInvalid=*/false); 10330 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10331 if (Result.isInvalid()) { 10332 VDecl->setInvalidDecl(); 10333 return; 10334 } 10335 10336 Init = Result.getAs<Expr>(); 10337 } 10338 10339 // Check for self-references within variable initializers. 10340 // Variables declared within a function/method body (except for references) 10341 // are handled by a dataflow analysis. 10342 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10343 VDecl->getType()->isReferenceType()) { 10344 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10345 } 10346 10347 // If the type changed, it means we had an incomplete type that was 10348 // completed by the initializer. For example: 10349 // int ary[] = { 1, 3, 5 }; 10350 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10351 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10352 VDecl->setType(DclT); 10353 10354 if (!VDecl->isInvalidDecl()) { 10355 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10356 10357 if (VDecl->hasAttr<BlocksAttr>()) 10358 checkRetainCycles(VDecl, Init); 10359 10360 // It is safe to assign a weak reference into a strong variable. 10361 // Although this code can still have problems: 10362 // id x = self.weakProp; 10363 // id y = self.weakProp; 10364 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10365 // paths through the function. This should be revisited if 10366 // -Wrepeated-use-of-weak is made flow-sensitive. 10367 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10368 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10369 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10370 Init->getLocStart())) 10371 getCurFunction()->markSafeWeakUse(Init); 10372 } 10373 10374 // The initialization is usually a full-expression. 10375 // 10376 // FIXME: If this is a braced initialization of an aggregate, it is not 10377 // an expression, and each individual field initializer is a separate 10378 // full-expression. For instance, in: 10379 // 10380 // struct Temp { ~Temp(); }; 10381 // struct S { S(Temp); }; 10382 // struct T { S a, b; } t = { Temp(), Temp() } 10383 // 10384 // we should destroy the first Temp before constructing the second. 10385 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10386 false, 10387 VDecl->isConstexpr()); 10388 if (Result.isInvalid()) { 10389 VDecl->setInvalidDecl(); 10390 return; 10391 } 10392 Init = Result.get(); 10393 10394 // Attach the initializer to the decl. 10395 VDecl->setInit(Init); 10396 10397 if (VDecl->isLocalVarDecl()) { 10398 // Don't check the initializer if the declaration is malformed. 10399 if (VDecl->isInvalidDecl()) { 10400 // do nothing 10401 10402 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10403 // This is true even in OpenCL C++. 10404 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10405 CheckForConstantInitializer(Init, DclT); 10406 10407 // Otherwise, C++ does not restrict the initializer. 10408 } else if (getLangOpts().CPlusPlus) { 10409 // do nothing 10410 10411 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10412 // static storage duration shall be constant expressions or string literals. 10413 } else if (VDecl->getStorageClass() == SC_Static) { 10414 CheckForConstantInitializer(Init, DclT); 10415 10416 // C89 is stricter than C99 for aggregate initializers. 10417 // C89 6.5.7p3: All the expressions [...] in an initializer list 10418 // for an object that has aggregate or union type shall be 10419 // constant expressions. 10420 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10421 isa<InitListExpr>(Init)) { 10422 const Expr *Culprit; 10423 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10424 Diag(Culprit->getExprLoc(), 10425 diag::ext_aggregate_init_not_constant) 10426 << Culprit->getSourceRange(); 10427 } 10428 } 10429 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10430 VDecl->getLexicalDeclContext()->isRecord()) { 10431 // This is an in-class initialization for a static data member, e.g., 10432 // 10433 // struct S { 10434 // static const int value = 17; 10435 // }; 10436 10437 // C++ [class.mem]p4: 10438 // A member-declarator can contain a constant-initializer only 10439 // if it declares a static member (9.4) of const integral or 10440 // const enumeration type, see 9.4.2. 10441 // 10442 // C++11 [class.static.data]p3: 10443 // If a non-volatile non-inline const static data member is of integral 10444 // or enumeration type, its declaration in the class definition can 10445 // specify a brace-or-equal-initializer in which every initializer-clause 10446 // that is an assignment-expression is a constant expression. A static 10447 // data member of literal type can be declared in the class definition 10448 // with the constexpr specifier; if so, its declaration shall specify a 10449 // brace-or-equal-initializer in which every initializer-clause that is 10450 // an assignment-expression is a constant expression. 10451 10452 // Do nothing on dependent types. 10453 if (DclT->isDependentType()) { 10454 10455 // Allow any 'static constexpr' members, whether or not they are of literal 10456 // type. We separately check that every constexpr variable is of literal 10457 // type. 10458 } else if (VDecl->isConstexpr()) { 10459 10460 // Require constness. 10461 } else if (!DclT.isConstQualified()) { 10462 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10463 << Init->getSourceRange(); 10464 VDecl->setInvalidDecl(); 10465 10466 // We allow integer constant expressions in all cases. 10467 } else if (DclT->isIntegralOrEnumerationType()) { 10468 // Check whether the expression is a constant expression. 10469 SourceLocation Loc; 10470 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10471 // In C++11, a non-constexpr const static data member with an 10472 // in-class initializer cannot be volatile. 10473 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10474 else if (Init->isValueDependent()) 10475 ; // Nothing to check. 10476 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10477 ; // Ok, it's an ICE! 10478 else if (Init->isEvaluatable(Context)) { 10479 // If we can constant fold the initializer through heroics, accept it, 10480 // but report this as a use of an extension for -pedantic. 10481 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10482 << Init->getSourceRange(); 10483 } else { 10484 // Otherwise, this is some crazy unknown case. Report the issue at the 10485 // location provided by the isIntegerConstantExpr failed check. 10486 Diag(Loc, diag::err_in_class_initializer_non_constant) 10487 << Init->getSourceRange(); 10488 VDecl->setInvalidDecl(); 10489 } 10490 10491 // We allow foldable floating-point constants as an extension. 10492 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10493 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10494 // it anyway and provide a fixit to add the 'constexpr'. 10495 if (getLangOpts().CPlusPlus11) { 10496 Diag(VDecl->getLocation(), 10497 diag::ext_in_class_initializer_float_type_cxx11) 10498 << DclT << Init->getSourceRange(); 10499 Diag(VDecl->getLocStart(), 10500 diag::note_in_class_initializer_float_type_cxx11) 10501 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10502 } else { 10503 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10504 << DclT << Init->getSourceRange(); 10505 10506 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10507 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10508 << Init->getSourceRange(); 10509 VDecl->setInvalidDecl(); 10510 } 10511 } 10512 10513 // Suggest adding 'constexpr' in C++11 for literal types. 10514 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10515 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10516 << DclT << Init->getSourceRange() 10517 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10518 VDecl->setConstexpr(true); 10519 10520 } else { 10521 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10522 << DclT << Init->getSourceRange(); 10523 VDecl->setInvalidDecl(); 10524 } 10525 } else if (VDecl->isFileVarDecl()) { 10526 // In C, extern is typically used to avoid tentative definitions when 10527 // declaring variables in headers, but adding an intializer makes it a 10528 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10529 // In C++, extern is often used to give implictly static const variables 10530 // external linkage, so don't warn in that case. If selectany is present, 10531 // this might be header code intended for C and C++ inclusion, so apply the 10532 // C++ rules. 10533 if (VDecl->getStorageClass() == SC_Extern && 10534 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10535 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10536 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10537 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10538 Diag(VDecl->getLocation(), diag::warn_extern_init); 10539 10540 // C99 6.7.8p4. All file scoped initializers need to be constant. 10541 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10542 CheckForConstantInitializer(Init, DclT); 10543 } 10544 10545 // We will represent direct-initialization similarly to copy-initialization: 10546 // int x(1); -as-> int x = 1; 10547 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10548 // 10549 // Clients that want to distinguish between the two forms, can check for 10550 // direct initializer using VarDecl::getInitStyle(). 10551 // A major benefit is that clients that don't particularly care about which 10552 // exactly form was it (like the CodeGen) can handle both cases without 10553 // special case code. 10554 10555 // C++ 8.5p11: 10556 // The form of initialization (using parentheses or '=') is generally 10557 // insignificant, but does matter when the entity being initialized has a 10558 // class type. 10559 if (CXXDirectInit) { 10560 assert(DirectInit && "Call-style initializer must be direct init."); 10561 VDecl->setInitStyle(VarDecl::CallInit); 10562 } else if (DirectInit) { 10563 // This must be list-initialization. No other way is direct-initialization. 10564 VDecl->setInitStyle(VarDecl::ListInit); 10565 } 10566 10567 CheckCompleteVariableDeclaration(VDecl); 10568 } 10569 10570 /// ActOnInitializerError - Given that there was an error parsing an 10571 /// initializer for the given declaration, try to return to some form 10572 /// of sanity. 10573 void Sema::ActOnInitializerError(Decl *D) { 10574 // Our main concern here is re-establishing invariants like "a 10575 // variable's type is either dependent or complete". 10576 if (!D || D->isInvalidDecl()) return; 10577 10578 VarDecl *VD = dyn_cast<VarDecl>(D); 10579 if (!VD) return; 10580 10581 // Bindings are not usable if we can't make sense of the initializer. 10582 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10583 for (auto *BD : DD->bindings()) 10584 BD->setInvalidDecl(); 10585 10586 // Auto types are meaningless if we can't make sense of the initializer. 10587 if (ParsingInitForAutoVars.count(D)) { 10588 D->setInvalidDecl(); 10589 return; 10590 } 10591 10592 QualType Ty = VD->getType(); 10593 if (Ty->isDependentType()) return; 10594 10595 // Require a complete type. 10596 if (RequireCompleteType(VD->getLocation(), 10597 Context.getBaseElementType(Ty), 10598 diag::err_typecheck_decl_incomplete_type)) { 10599 VD->setInvalidDecl(); 10600 return; 10601 } 10602 10603 // Require a non-abstract type. 10604 if (RequireNonAbstractType(VD->getLocation(), Ty, 10605 diag::err_abstract_type_in_decl, 10606 AbstractVariableType)) { 10607 VD->setInvalidDecl(); 10608 return; 10609 } 10610 10611 // Don't bother complaining about constructors or destructors, 10612 // though. 10613 } 10614 10615 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10616 // If there is no declaration, there was an error parsing it. Just ignore it. 10617 if (!RealDecl) 10618 return; 10619 10620 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10621 QualType Type = Var->getType(); 10622 10623 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10624 if (isa<DecompositionDecl>(RealDecl)) { 10625 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10626 Var->setInvalidDecl(); 10627 return; 10628 } 10629 10630 if (Type->isUndeducedType() && 10631 DeduceVariableDeclarationType(Var, false, nullptr)) 10632 return; 10633 10634 // C++11 [class.static.data]p3: A static data member can be declared with 10635 // the constexpr specifier; if so, its declaration shall specify 10636 // a brace-or-equal-initializer. 10637 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10638 // the definition of a variable [...] or the declaration of a static data 10639 // member. 10640 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10641 !Var->isThisDeclarationADemotedDefinition()) { 10642 if (Var->isStaticDataMember()) { 10643 // C++1z removes the relevant rule; the in-class declaration is always 10644 // a definition there. 10645 if (!getLangOpts().CPlusPlus1z) { 10646 Diag(Var->getLocation(), 10647 diag::err_constexpr_static_mem_var_requires_init) 10648 << Var->getDeclName(); 10649 Var->setInvalidDecl(); 10650 return; 10651 } 10652 } else { 10653 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10654 Var->setInvalidDecl(); 10655 return; 10656 } 10657 } 10658 10659 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10660 // definition having the concept specifier is called a variable concept. A 10661 // concept definition refers to [...] a variable concept and its initializer. 10662 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10663 if (VTD->isConcept()) { 10664 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10665 Var->setInvalidDecl(); 10666 return; 10667 } 10668 } 10669 10670 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10671 // be initialized. 10672 if (!Var->isInvalidDecl() && 10673 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10674 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10675 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10676 Var->setInvalidDecl(); 10677 return; 10678 } 10679 10680 switch (Var->isThisDeclarationADefinition()) { 10681 case VarDecl::Definition: 10682 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10683 break; 10684 10685 // We have an out-of-line definition of a static data member 10686 // that has an in-class initializer, so we type-check this like 10687 // a declaration. 10688 // 10689 // Fall through 10690 10691 case VarDecl::DeclarationOnly: 10692 // It's only a declaration. 10693 10694 // Block scope. C99 6.7p7: If an identifier for an object is 10695 // declared with no linkage (C99 6.2.2p6), the type for the 10696 // object shall be complete. 10697 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10698 !Var->hasLinkage() && !Var->isInvalidDecl() && 10699 RequireCompleteType(Var->getLocation(), Type, 10700 diag::err_typecheck_decl_incomplete_type)) 10701 Var->setInvalidDecl(); 10702 10703 // Make sure that the type is not abstract. 10704 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10705 RequireNonAbstractType(Var->getLocation(), Type, 10706 diag::err_abstract_type_in_decl, 10707 AbstractVariableType)) 10708 Var->setInvalidDecl(); 10709 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10710 Var->getStorageClass() == SC_PrivateExtern) { 10711 Diag(Var->getLocation(), diag::warn_private_extern); 10712 Diag(Var->getLocation(), diag::note_private_extern); 10713 } 10714 10715 return; 10716 10717 case VarDecl::TentativeDefinition: 10718 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10719 // object that has file scope without an initializer, and without a 10720 // storage-class specifier or with the storage-class specifier "static", 10721 // constitutes a tentative definition. Note: A tentative definition with 10722 // external linkage is valid (C99 6.2.2p5). 10723 if (!Var->isInvalidDecl()) { 10724 if (const IncompleteArrayType *ArrayT 10725 = Context.getAsIncompleteArrayType(Type)) { 10726 if (RequireCompleteType(Var->getLocation(), 10727 ArrayT->getElementType(), 10728 diag::err_illegal_decl_array_incomplete_type)) 10729 Var->setInvalidDecl(); 10730 } else if (Var->getStorageClass() == SC_Static) { 10731 // C99 6.9.2p3: If the declaration of an identifier for an object is 10732 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10733 // declared type shall not be an incomplete type. 10734 // NOTE: code such as the following 10735 // static struct s; 10736 // struct s { int a; }; 10737 // is accepted by gcc. Hence here we issue a warning instead of 10738 // an error and we do not invalidate the static declaration. 10739 // NOTE: to avoid multiple warnings, only check the first declaration. 10740 if (Var->isFirstDecl()) 10741 RequireCompleteType(Var->getLocation(), Type, 10742 diag::ext_typecheck_decl_incomplete_type); 10743 } 10744 } 10745 10746 // Record the tentative definition; we're done. 10747 if (!Var->isInvalidDecl()) 10748 TentativeDefinitions.push_back(Var); 10749 return; 10750 } 10751 10752 // Provide a specific diagnostic for uninitialized variable 10753 // definitions with incomplete array type. 10754 if (Type->isIncompleteArrayType()) { 10755 Diag(Var->getLocation(), 10756 diag::err_typecheck_incomplete_array_needs_initializer); 10757 Var->setInvalidDecl(); 10758 return; 10759 } 10760 10761 // Provide a specific diagnostic for uninitialized variable 10762 // definitions with reference type. 10763 if (Type->isReferenceType()) { 10764 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10765 << Var->getDeclName() 10766 << SourceRange(Var->getLocation(), Var->getLocation()); 10767 Var->setInvalidDecl(); 10768 return; 10769 } 10770 10771 // Do not attempt to type-check the default initializer for a 10772 // variable with dependent type. 10773 if (Type->isDependentType()) 10774 return; 10775 10776 if (Var->isInvalidDecl()) 10777 return; 10778 10779 if (!Var->hasAttr<AliasAttr>()) { 10780 if (RequireCompleteType(Var->getLocation(), 10781 Context.getBaseElementType(Type), 10782 diag::err_typecheck_decl_incomplete_type)) { 10783 Var->setInvalidDecl(); 10784 return; 10785 } 10786 } else { 10787 return; 10788 } 10789 10790 // The variable can not have an abstract class type. 10791 if (RequireNonAbstractType(Var->getLocation(), Type, 10792 diag::err_abstract_type_in_decl, 10793 AbstractVariableType)) { 10794 Var->setInvalidDecl(); 10795 return; 10796 } 10797 10798 // Check for jumps past the implicit initializer. C++0x 10799 // clarifies that this applies to a "variable with automatic 10800 // storage duration", not a "local variable". 10801 // C++11 [stmt.dcl]p3 10802 // A program that jumps from a point where a variable with automatic 10803 // storage duration is not in scope to a point where it is in scope is 10804 // ill-formed unless the variable has scalar type, class type with a 10805 // trivial default constructor and a trivial destructor, a cv-qualified 10806 // version of one of these types, or an array of one of the preceding 10807 // types and is declared without an initializer. 10808 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10809 if (const RecordType *Record 10810 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10811 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10812 // Mark the function for further checking even if the looser rules of 10813 // C++11 do not require such checks, so that we can diagnose 10814 // incompatibilities with C++98. 10815 if (!CXXRecord->isPOD()) 10816 getCurFunction()->setHasBranchProtectedScope(); 10817 } 10818 } 10819 10820 // C++03 [dcl.init]p9: 10821 // If no initializer is specified for an object, and the 10822 // object is of (possibly cv-qualified) non-POD class type (or 10823 // array thereof), the object shall be default-initialized; if 10824 // the object is of const-qualified type, the underlying class 10825 // type shall have a user-declared default 10826 // constructor. Otherwise, if no initializer is specified for 10827 // a non- static object, the object and its subobjects, if 10828 // any, have an indeterminate initial value); if the object 10829 // or any of its subobjects are of const-qualified type, the 10830 // program is ill-formed. 10831 // C++0x [dcl.init]p11: 10832 // If no initializer is specified for an object, the object is 10833 // default-initialized; [...]. 10834 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10835 InitializationKind Kind 10836 = InitializationKind::CreateDefault(Var->getLocation()); 10837 10838 InitializationSequence InitSeq(*this, Entity, Kind, None); 10839 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10840 if (Init.isInvalid()) 10841 Var->setInvalidDecl(); 10842 else if (Init.get()) { 10843 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10844 // This is important for template substitution. 10845 Var->setInitStyle(VarDecl::CallInit); 10846 } 10847 10848 CheckCompleteVariableDeclaration(Var); 10849 } 10850 } 10851 10852 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10853 // If there is no declaration, there was an error parsing it. Ignore it. 10854 if (!D) 10855 return; 10856 10857 VarDecl *VD = dyn_cast<VarDecl>(D); 10858 if (!VD) { 10859 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10860 D->setInvalidDecl(); 10861 return; 10862 } 10863 10864 VD->setCXXForRangeDecl(true); 10865 10866 // for-range-declaration cannot be given a storage class specifier. 10867 int Error = -1; 10868 switch (VD->getStorageClass()) { 10869 case SC_None: 10870 break; 10871 case SC_Extern: 10872 Error = 0; 10873 break; 10874 case SC_Static: 10875 Error = 1; 10876 break; 10877 case SC_PrivateExtern: 10878 Error = 2; 10879 break; 10880 case SC_Auto: 10881 Error = 3; 10882 break; 10883 case SC_Register: 10884 Error = 4; 10885 break; 10886 } 10887 if (Error != -1) { 10888 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10889 << VD->getDeclName() << Error; 10890 D->setInvalidDecl(); 10891 } 10892 } 10893 10894 StmtResult 10895 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10896 IdentifierInfo *Ident, 10897 ParsedAttributes &Attrs, 10898 SourceLocation AttrEnd) { 10899 // C++1y [stmt.iter]p1: 10900 // A range-based for statement of the form 10901 // for ( for-range-identifier : for-range-initializer ) statement 10902 // is equivalent to 10903 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10904 DeclSpec DS(Attrs.getPool().getFactory()); 10905 10906 const char *PrevSpec; 10907 unsigned DiagID; 10908 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10909 getPrintingPolicy()); 10910 10911 Declarator D(DS, Declarator::ForContext); 10912 D.SetIdentifier(Ident, IdentLoc); 10913 D.takeAttributes(Attrs, AttrEnd); 10914 10915 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10916 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10917 EmptyAttrs, IdentLoc); 10918 Decl *Var = ActOnDeclarator(S, D); 10919 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10920 FinalizeDeclaration(Var); 10921 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10922 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10923 } 10924 10925 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10926 if (var->isInvalidDecl()) return; 10927 10928 if (getLangOpts().OpenCL) { 10929 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10930 // initialiser 10931 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10932 !var->hasInit()) { 10933 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10934 << 1 /*Init*/; 10935 var->setInvalidDecl(); 10936 return; 10937 } 10938 } 10939 10940 // In Objective-C, don't allow jumps past the implicit initialization of a 10941 // local retaining variable. 10942 if (getLangOpts().ObjC1 && 10943 var->hasLocalStorage()) { 10944 switch (var->getType().getObjCLifetime()) { 10945 case Qualifiers::OCL_None: 10946 case Qualifiers::OCL_ExplicitNone: 10947 case Qualifiers::OCL_Autoreleasing: 10948 break; 10949 10950 case Qualifiers::OCL_Weak: 10951 case Qualifiers::OCL_Strong: 10952 getCurFunction()->setHasBranchProtectedScope(); 10953 break; 10954 } 10955 } 10956 10957 // Warn about externally-visible variables being defined without a 10958 // prior declaration. We only want to do this for global 10959 // declarations, but we also specifically need to avoid doing it for 10960 // class members because the linkage of an anonymous class can 10961 // change if it's later given a typedef name. 10962 if (var->isThisDeclarationADefinition() && 10963 var->getDeclContext()->getRedeclContext()->isFileContext() && 10964 var->isExternallyVisible() && var->hasLinkage() && 10965 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10966 var->getLocation())) { 10967 // Find a previous declaration that's not a definition. 10968 VarDecl *prev = var->getPreviousDecl(); 10969 while (prev && prev->isThisDeclarationADefinition()) 10970 prev = prev->getPreviousDecl(); 10971 10972 if (!prev) 10973 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10974 } 10975 10976 // Cache the result of checking for constant initialization. 10977 Optional<bool> CacheHasConstInit; 10978 const Expr *CacheCulprit; 10979 auto checkConstInit = [&]() mutable { 10980 if (!CacheHasConstInit) 10981 CacheHasConstInit = var->getInit()->isConstantInitializer( 10982 Context, var->getType()->isReferenceType(), &CacheCulprit); 10983 return *CacheHasConstInit; 10984 }; 10985 10986 if (var->getTLSKind() == VarDecl::TLS_Static) { 10987 if (var->getType().isDestructedType()) { 10988 // GNU C++98 edits for __thread, [basic.start.term]p3: 10989 // The type of an object with thread storage duration shall not 10990 // have a non-trivial destructor. 10991 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10992 if (getLangOpts().CPlusPlus11) 10993 Diag(var->getLocation(), diag::note_use_thread_local); 10994 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10995 if (!checkConstInit()) { 10996 // GNU C++98 edits for __thread, [basic.start.init]p4: 10997 // An object of thread storage duration shall not require dynamic 10998 // initialization. 10999 // FIXME: Need strict checking here. 11000 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11001 << CacheCulprit->getSourceRange(); 11002 if (getLangOpts().CPlusPlus11) 11003 Diag(var->getLocation(), diag::note_use_thread_local); 11004 } 11005 } 11006 } 11007 11008 // Apply section attributes and pragmas to global variables. 11009 bool GlobalStorage = var->hasGlobalStorage(); 11010 if (GlobalStorage && var->isThisDeclarationADefinition() && 11011 !inTemplateInstantiation()) { 11012 PragmaStack<StringLiteral *> *Stack = nullptr; 11013 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11014 if (var->getType().isConstQualified()) 11015 Stack = &ConstSegStack; 11016 else if (!var->getInit()) { 11017 Stack = &BSSSegStack; 11018 SectionFlags |= ASTContext::PSF_Write; 11019 } else { 11020 Stack = &DataSegStack; 11021 SectionFlags |= ASTContext::PSF_Write; 11022 } 11023 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11024 var->addAttr(SectionAttr::CreateImplicit( 11025 Context, SectionAttr::Declspec_allocate, 11026 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11027 } 11028 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11029 if (UnifySection(SA->getName(), SectionFlags, var)) 11030 var->dropAttr<SectionAttr>(); 11031 11032 // Apply the init_seg attribute if this has an initializer. If the 11033 // initializer turns out to not be dynamic, we'll end up ignoring this 11034 // attribute. 11035 if (CurInitSeg && var->getInit()) 11036 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11037 CurInitSegLoc)); 11038 } 11039 11040 // All the following checks are C++ only. 11041 if (!getLangOpts().CPlusPlus) { 11042 // If this variable must be emitted, add it as an initializer for the 11043 // current module. 11044 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11045 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11046 return; 11047 } 11048 11049 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11050 CheckCompleteDecompositionDeclaration(DD); 11051 11052 QualType type = var->getType(); 11053 if (type->isDependentType()) return; 11054 11055 // __block variables might require us to capture a copy-initializer. 11056 if (var->hasAttr<BlocksAttr>()) { 11057 // It's currently invalid to ever have a __block variable with an 11058 // array type; should we diagnose that here? 11059 11060 // Regardless, we don't want to ignore array nesting when 11061 // constructing this copy. 11062 if (type->isStructureOrClassType()) { 11063 EnterExpressionEvaluationContext scope( 11064 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11065 SourceLocation poi = var->getLocation(); 11066 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11067 ExprResult result 11068 = PerformMoveOrCopyInitialization( 11069 InitializedEntity::InitializeBlock(poi, type, false), 11070 var, var->getType(), varRef, /*AllowNRVO=*/true); 11071 if (!result.isInvalid()) { 11072 result = MaybeCreateExprWithCleanups(result); 11073 Expr *init = result.getAs<Expr>(); 11074 Context.setBlockVarCopyInits(var, init); 11075 } 11076 } 11077 } 11078 11079 Expr *Init = var->getInit(); 11080 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11081 QualType baseType = Context.getBaseElementType(type); 11082 11083 if (!var->getDeclContext()->isDependentContext() && 11084 Init && !Init->isValueDependent()) { 11085 11086 if (var->isConstexpr()) { 11087 SmallVector<PartialDiagnosticAt, 8> Notes; 11088 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11089 SourceLocation DiagLoc = var->getLocation(); 11090 // If the note doesn't add any useful information other than a source 11091 // location, fold it into the primary diagnostic. 11092 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11093 diag::note_invalid_subexpr_in_const_expr) { 11094 DiagLoc = Notes[0].first; 11095 Notes.clear(); 11096 } 11097 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11098 << var << Init->getSourceRange(); 11099 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11100 Diag(Notes[I].first, Notes[I].second); 11101 } 11102 } else if (var->isUsableInConstantExpressions(Context)) { 11103 // Check whether the initializer of a const variable of integral or 11104 // enumeration type is an ICE now, since we can't tell whether it was 11105 // initialized by a constant expression if we check later. 11106 var->checkInitIsICE(); 11107 } 11108 11109 // Don't emit further diagnostics about constexpr globals since they 11110 // were just diagnosed. 11111 if (!var->isConstexpr() && GlobalStorage && 11112 var->hasAttr<RequireConstantInitAttr>()) { 11113 // FIXME: Need strict checking in C++03 here. 11114 bool DiagErr = getLangOpts().CPlusPlus11 11115 ? !var->checkInitIsICE() : !checkConstInit(); 11116 if (DiagErr) { 11117 auto attr = var->getAttr<RequireConstantInitAttr>(); 11118 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11119 << Init->getSourceRange(); 11120 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11121 << attr->getRange(); 11122 } 11123 } 11124 else if (!var->isConstexpr() && IsGlobal && 11125 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11126 var->getLocation())) { 11127 // Warn about globals which don't have a constant initializer. Don't 11128 // warn about globals with a non-trivial destructor because we already 11129 // warned about them. 11130 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11131 if (!(RD && !RD->hasTrivialDestructor())) { 11132 if (!checkConstInit()) 11133 Diag(var->getLocation(), diag::warn_global_constructor) 11134 << Init->getSourceRange(); 11135 } 11136 } 11137 } 11138 11139 // Require the destructor. 11140 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11141 FinalizeVarWithDestructor(var, recordType); 11142 11143 // If this variable must be emitted, add it as an initializer for the current 11144 // module. 11145 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11146 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11147 } 11148 11149 /// \brief Determines if a variable's alignment is dependent. 11150 static bool hasDependentAlignment(VarDecl *VD) { 11151 if (VD->getType()->isDependentType()) 11152 return true; 11153 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11154 if (I->isAlignmentDependent()) 11155 return true; 11156 return false; 11157 } 11158 11159 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11160 /// any semantic actions necessary after any initializer has been attached. 11161 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11162 // Note that we are no longer parsing the initializer for this declaration. 11163 ParsingInitForAutoVars.erase(ThisDecl); 11164 11165 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11166 if (!VD) 11167 return; 11168 11169 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11170 for (auto *BD : DD->bindings()) { 11171 FinalizeDeclaration(BD); 11172 } 11173 } 11174 11175 checkAttributesAfterMerging(*this, *VD); 11176 11177 // Perform TLS alignment check here after attributes attached to the variable 11178 // which may affect the alignment have been processed. Only perform the check 11179 // if the target has a maximum TLS alignment (zero means no constraints). 11180 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11181 // Protect the check so that it's not performed on dependent types and 11182 // dependent alignments (we can't determine the alignment in that case). 11183 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11184 !VD->isInvalidDecl()) { 11185 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11186 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11187 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11188 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11189 << (unsigned)MaxAlignChars.getQuantity(); 11190 } 11191 } 11192 } 11193 11194 if (VD->isStaticLocal()) { 11195 if (FunctionDecl *FD = 11196 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11197 // Static locals inherit dll attributes from their function. 11198 if (Attr *A = getDLLAttr(FD)) { 11199 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11200 NewAttr->setInherited(true); 11201 VD->addAttr(NewAttr); 11202 } 11203 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11204 // function, only __shared__ variables may be declared with 11205 // static storage class. 11206 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11207 CUDADiagIfDeviceCode(VD->getLocation(), 11208 diag::err_device_static_local_var) 11209 << CurrentCUDATarget()) 11210 VD->setInvalidDecl(); 11211 } 11212 } 11213 11214 // Perform check for initializers of device-side global variables. 11215 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11216 // 7.5). We must also apply the same checks to all __shared__ 11217 // variables whether they are local or not. CUDA also allows 11218 // constant initializers for __constant__ and __device__ variables. 11219 if (getLangOpts().CUDA) { 11220 const Expr *Init = VD->getInit(); 11221 if (Init && VD->hasGlobalStorage()) { 11222 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11223 VD->hasAttr<CUDASharedAttr>()) { 11224 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11225 bool AllowedInit = false; 11226 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11227 AllowedInit = 11228 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11229 // We'll allow constant initializers even if it's a non-empty 11230 // constructor according to CUDA rules. This deviates from NVCC, 11231 // but allows us to handle things like constexpr constructors. 11232 if (!AllowedInit && 11233 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11234 AllowedInit = VD->getInit()->isConstantInitializer( 11235 Context, VD->getType()->isReferenceType()); 11236 11237 // Also make sure that destructor, if there is one, is empty. 11238 if (AllowedInit) 11239 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11240 AllowedInit = 11241 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11242 11243 if (!AllowedInit) { 11244 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11245 ? diag::err_shared_var_init 11246 : diag::err_dynamic_var_init) 11247 << Init->getSourceRange(); 11248 VD->setInvalidDecl(); 11249 } 11250 } else { 11251 // This is a host-side global variable. Check that the initializer is 11252 // callable from the host side. 11253 const FunctionDecl *InitFn = nullptr; 11254 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11255 InitFn = CE->getConstructor(); 11256 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11257 InitFn = CE->getDirectCallee(); 11258 } 11259 if (InitFn) { 11260 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11261 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11262 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11263 << InitFnTarget << InitFn; 11264 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11265 VD->setInvalidDecl(); 11266 } 11267 } 11268 } 11269 } 11270 } 11271 11272 // Grab the dllimport or dllexport attribute off of the VarDecl. 11273 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11274 11275 // Imported static data members cannot be defined out-of-line. 11276 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11277 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11278 VD->isThisDeclarationADefinition()) { 11279 // We allow definitions of dllimport class template static data members 11280 // with a warning. 11281 CXXRecordDecl *Context = 11282 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11283 bool IsClassTemplateMember = 11284 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11285 Context->getDescribedClassTemplate(); 11286 11287 Diag(VD->getLocation(), 11288 IsClassTemplateMember 11289 ? diag::warn_attribute_dllimport_static_field_definition 11290 : diag::err_attribute_dllimport_static_field_definition); 11291 Diag(IA->getLocation(), diag::note_attribute); 11292 if (!IsClassTemplateMember) 11293 VD->setInvalidDecl(); 11294 } 11295 } 11296 11297 // dllimport/dllexport variables cannot be thread local, their TLS index 11298 // isn't exported with the variable. 11299 if (DLLAttr && VD->getTLSKind()) { 11300 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11301 if (F && getDLLAttr(F)) { 11302 assert(VD->isStaticLocal()); 11303 // But if this is a static local in a dlimport/dllexport function, the 11304 // function will never be inlined, which means the var would never be 11305 // imported, so having it marked import/export is safe. 11306 } else { 11307 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11308 << DLLAttr; 11309 VD->setInvalidDecl(); 11310 } 11311 } 11312 11313 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11314 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11315 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11316 VD->dropAttr<UsedAttr>(); 11317 } 11318 } 11319 11320 const DeclContext *DC = VD->getDeclContext(); 11321 // If there's a #pragma GCC visibility in scope, and this isn't a class 11322 // member, set the visibility of this variable. 11323 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11324 AddPushedVisibilityAttribute(VD); 11325 11326 // FIXME: Warn on unused var template partial specializations. 11327 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11328 MarkUnusedFileScopedDecl(VD); 11329 11330 // Now we have parsed the initializer and can update the table of magic 11331 // tag values. 11332 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11333 !VD->getType()->isIntegralOrEnumerationType()) 11334 return; 11335 11336 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11337 const Expr *MagicValueExpr = VD->getInit(); 11338 if (!MagicValueExpr) { 11339 continue; 11340 } 11341 llvm::APSInt MagicValueInt; 11342 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11343 Diag(I->getRange().getBegin(), 11344 diag::err_type_tag_for_datatype_not_ice) 11345 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11346 continue; 11347 } 11348 if (MagicValueInt.getActiveBits() > 64) { 11349 Diag(I->getRange().getBegin(), 11350 diag::err_type_tag_for_datatype_too_large) 11351 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11352 continue; 11353 } 11354 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11355 RegisterTypeTagForDatatype(I->getArgumentKind(), 11356 MagicValue, 11357 I->getMatchingCType(), 11358 I->getLayoutCompatible(), 11359 I->getMustBeNull()); 11360 } 11361 } 11362 11363 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11364 auto *VD = dyn_cast<VarDecl>(DD); 11365 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11366 } 11367 11368 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11369 ArrayRef<Decl *> Group) { 11370 SmallVector<Decl*, 8> Decls; 11371 11372 if (DS.isTypeSpecOwned()) 11373 Decls.push_back(DS.getRepAsDecl()); 11374 11375 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11376 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11377 bool DiagnosedMultipleDecomps = false; 11378 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11379 bool DiagnosedNonDeducedAuto = false; 11380 11381 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11382 if (Decl *D = Group[i]) { 11383 // For declarators, there are some additional syntactic-ish checks we need 11384 // to perform. 11385 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11386 if (!FirstDeclaratorInGroup) 11387 FirstDeclaratorInGroup = DD; 11388 if (!FirstDecompDeclaratorInGroup) 11389 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11390 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11391 !hasDeducedAuto(DD)) 11392 FirstNonDeducedAutoInGroup = DD; 11393 11394 if (FirstDeclaratorInGroup != DD) { 11395 // A decomposition declaration cannot be combined with any other 11396 // declaration in the same group. 11397 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11398 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11399 diag::err_decomp_decl_not_alone) 11400 << FirstDeclaratorInGroup->getSourceRange() 11401 << DD->getSourceRange(); 11402 DiagnosedMultipleDecomps = true; 11403 } 11404 11405 // A declarator that uses 'auto' in any way other than to declare a 11406 // variable with a deduced type cannot be combined with any other 11407 // declarator in the same group. 11408 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11409 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11410 diag::err_auto_non_deduced_not_alone) 11411 << FirstNonDeducedAutoInGroup->getType() 11412 ->hasAutoForTrailingReturnType() 11413 << FirstDeclaratorInGroup->getSourceRange() 11414 << DD->getSourceRange(); 11415 DiagnosedNonDeducedAuto = true; 11416 } 11417 } 11418 } 11419 11420 Decls.push_back(D); 11421 } 11422 } 11423 11424 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11425 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11426 handleTagNumbering(Tag, S); 11427 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11428 getLangOpts().CPlusPlus) 11429 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11430 } 11431 } 11432 11433 return BuildDeclaratorGroup(Decls); 11434 } 11435 11436 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11437 /// group, performing any necessary semantic checking. 11438 Sema::DeclGroupPtrTy 11439 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11440 // C++14 [dcl.spec.auto]p7: (DR1347) 11441 // If the type that replaces the placeholder type is not the same in each 11442 // deduction, the program is ill-formed. 11443 if (Group.size() > 1) { 11444 QualType Deduced; 11445 VarDecl *DeducedDecl = nullptr; 11446 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11447 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11448 if (!D || D->isInvalidDecl()) 11449 break; 11450 DeducedType *DT = D->getType()->getContainedDeducedType(); 11451 if (!DT || DT->getDeducedType().isNull()) 11452 continue; 11453 if (Deduced.isNull()) { 11454 Deduced = DT->getDeducedType(); 11455 DeducedDecl = D; 11456 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11457 auto *AT = dyn_cast<AutoType>(DT); 11458 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11459 diag::err_auto_different_deductions) 11460 << (AT ? (unsigned)AT->getKeyword() : 3) 11461 << Deduced << DeducedDecl->getDeclName() 11462 << DT->getDeducedType() << D->getDeclName() 11463 << DeducedDecl->getInit()->getSourceRange() 11464 << D->getInit()->getSourceRange(); 11465 D->setInvalidDecl(); 11466 break; 11467 } 11468 } 11469 } 11470 11471 ActOnDocumentableDecls(Group); 11472 11473 return DeclGroupPtrTy::make( 11474 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11475 } 11476 11477 void Sema::ActOnDocumentableDecl(Decl *D) { 11478 ActOnDocumentableDecls(D); 11479 } 11480 11481 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11482 // Don't parse the comment if Doxygen diagnostics are ignored. 11483 if (Group.empty() || !Group[0]) 11484 return; 11485 11486 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11487 Group[0]->getLocation()) && 11488 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11489 Group[0]->getLocation())) 11490 return; 11491 11492 if (Group.size() >= 2) { 11493 // This is a decl group. Normally it will contain only declarations 11494 // produced from declarator list. But in case we have any definitions or 11495 // additional declaration references: 11496 // 'typedef struct S {} S;' 11497 // 'typedef struct S *S;' 11498 // 'struct S *pS;' 11499 // FinalizeDeclaratorGroup adds these as separate declarations. 11500 Decl *MaybeTagDecl = Group[0]; 11501 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11502 Group = Group.slice(1); 11503 } 11504 } 11505 11506 // See if there are any new comments that are not attached to a decl. 11507 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11508 if (!Comments.empty() && 11509 !Comments.back()->isAttached()) { 11510 // There is at least one comment that not attached to a decl. 11511 // Maybe it should be attached to one of these decls? 11512 // 11513 // Note that this way we pick up not only comments that precede the 11514 // declaration, but also comments that *follow* the declaration -- thanks to 11515 // the lookahead in the lexer: we've consumed the semicolon and looked 11516 // ahead through comments. 11517 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11518 Context.getCommentForDecl(Group[i], &PP); 11519 } 11520 } 11521 11522 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11523 /// to introduce parameters into function prototype scope. 11524 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11525 const DeclSpec &DS = D.getDeclSpec(); 11526 11527 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11528 11529 // C++03 [dcl.stc]p2 also permits 'auto'. 11530 StorageClass SC = SC_None; 11531 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11532 SC = SC_Register; 11533 } else if (getLangOpts().CPlusPlus && 11534 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11535 SC = SC_Auto; 11536 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11537 Diag(DS.getStorageClassSpecLoc(), 11538 diag::err_invalid_storage_class_in_func_decl); 11539 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11540 } 11541 11542 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11543 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11544 << DeclSpec::getSpecifierName(TSCS); 11545 if (DS.isInlineSpecified()) 11546 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11547 << getLangOpts().CPlusPlus1z; 11548 if (DS.isConstexprSpecified()) 11549 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11550 << 0; 11551 if (DS.isConceptSpecified()) 11552 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11553 11554 DiagnoseFunctionSpecifiers(DS); 11555 11556 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11557 QualType parmDeclType = TInfo->getType(); 11558 11559 if (getLangOpts().CPlusPlus) { 11560 // Check that there are no default arguments inside the type of this 11561 // parameter. 11562 CheckExtraCXXDefaultArguments(D); 11563 11564 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11565 if (D.getCXXScopeSpec().isSet()) { 11566 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11567 << D.getCXXScopeSpec().getRange(); 11568 D.getCXXScopeSpec().clear(); 11569 } 11570 } 11571 11572 // Ensure we have a valid name 11573 IdentifierInfo *II = nullptr; 11574 if (D.hasName()) { 11575 II = D.getIdentifier(); 11576 if (!II) { 11577 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11578 << GetNameForDeclarator(D).getName(); 11579 D.setInvalidType(true); 11580 } 11581 } 11582 11583 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11584 if (II) { 11585 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11586 ForRedeclaration); 11587 LookupName(R, S); 11588 if (R.isSingleResult()) { 11589 NamedDecl *PrevDecl = R.getFoundDecl(); 11590 if (PrevDecl->isTemplateParameter()) { 11591 // Maybe we will complain about the shadowed template parameter. 11592 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11593 // Just pretend that we didn't see the previous declaration. 11594 PrevDecl = nullptr; 11595 } else if (S->isDeclScope(PrevDecl)) { 11596 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11597 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11598 11599 // Recover by removing the name 11600 II = nullptr; 11601 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11602 D.setInvalidType(true); 11603 } 11604 } 11605 } 11606 11607 // Temporarily put parameter variables in the translation unit, not 11608 // the enclosing context. This prevents them from accidentally 11609 // looking like class members in C++. 11610 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11611 D.getLocStart(), 11612 D.getIdentifierLoc(), II, 11613 parmDeclType, TInfo, 11614 SC); 11615 11616 if (D.isInvalidType()) 11617 New->setInvalidDecl(); 11618 11619 assert(S->isFunctionPrototypeScope()); 11620 assert(S->getFunctionPrototypeDepth() >= 1); 11621 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11622 S->getNextFunctionPrototypeIndex()); 11623 11624 // Add the parameter declaration into this scope. 11625 S->AddDecl(New); 11626 if (II) 11627 IdResolver.AddDecl(New); 11628 11629 ProcessDeclAttributes(S, New, D); 11630 11631 if (D.getDeclSpec().isModulePrivateSpecified()) 11632 Diag(New->getLocation(), diag::err_module_private_local) 11633 << 1 << New->getDeclName() 11634 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11635 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11636 11637 if (New->hasAttr<BlocksAttr>()) { 11638 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11639 } 11640 return New; 11641 } 11642 11643 /// \brief Synthesizes a variable for a parameter arising from a 11644 /// typedef. 11645 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11646 SourceLocation Loc, 11647 QualType T) { 11648 /* FIXME: setting StartLoc == Loc. 11649 Would it be worth to modify callers so as to provide proper source 11650 location for the unnamed parameters, embedding the parameter's type? */ 11651 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11652 T, Context.getTrivialTypeSourceInfo(T, Loc), 11653 SC_None, nullptr); 11654 Param->setImplicit(); 11655 return Param; 11656 } 11657 11658 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11659 // Don't diagnose unused-parameter errors in template instantiations; we 11660 // will already have done so in the template itself. 11661 if (inTemplateInstantiation()) 11662 return; 11663 11664 for (const ParmVarDecl *Parameter : Parameters) { 11665 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11666 !Parameter->hasAttr<UnusedAttr>()) { 11667 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11668 << Parameter->getDeclName(); 11669 } 11670 } 11671 } 11672 11673 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11674 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11675 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11676 return; 11677 11678 // Warn if the return value is pass-by-value and larger than the specified 11679 // threshold. 11680 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11681 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11682 if (Size > LangOpts.NumLargeByValueCopy) 11683 Diag(D->getLocation(), diag::warn_return_value_size) 11684 << D->getDeclName() << Size; 11685 } 11686 11687 // Warn if any parameter is pass-by-value and larger than the specified 11688 // threshold. 11689 for (const ParmVarDecl *Parameter : Parameters) { 11690 QualType T = Parameter->getType(); 11691 if (T->isDependentType() || !T.isPODType(Context)) 11692 continue; 11693 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11694 if (Size > LangOpts.NumLargeByValueCopy) 11695 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11696 << Parameter->getDeclName() << Size; 11697 } 11698 } 11699 11700 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11701 SourceLocation NameLoc, IdentifierInfo *Name, 11702 QualType T, TypeSourceInfo *TSInfo, 11703 StorageClass SC) { 11704 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11705 if (getLangOpts().ObjCAutoRefCount && 11706 T.getObjCLifetime() == Qualifiers::OCL_None && 11707 T->isObjCLifetimeType()) { 11708 11709 Qualifiers::ObjCLifetime lifetime; 11710 11711 // Special cases for arrays: 11712 // - if it's const, use __unsafe_unretained 11713 // - otherwise, it's an error 11714 if (T->isArrayType()) { 11715 if (!T.isConstQualified()) { 11716 DelayedDiagnostics.add( 11717 sema::DelayedDiagnostic::makeForbiddenType( 11718 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11719 } 11720 lifetime = Qualifiers::OCL_ExplicitNone; 11721 } else { 11722 lifetime = T->getObjCARCImplicitLifetime(); 11723 } 11724 T = Context.getLifetimeQualifiedType(T, lifetime); 11725 } 11726 11727 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11728 Context.getAdjustedParameterType(T), 11729 TSInfo, SC, nullptr); 11730 11731 // Parameters can not be abstract class types. 11732 // For record types, this is done by the AbstractClassUsageDiagnoser once 11733 // the class has been completely parsed. 11734 if (!CurContext->isRecord() && 11735 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11736 AbstractParamType)) 11737 New->setInvalidDecl(); 11738 11739 // Parameter declarators cannot be interface types. All ObjC objects are 11740 // passed by reference. 11741 if (T->isObjCObjectType()) { 11742 SourceLocation TypeEndLoc = 11743 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11744 Diag(NameLoc, 11745 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11746 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11747 T = Context.getObjCObjectPointerType(T); 11748 New->setType(T); 11749 } 11750 11751 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11752 // duration shall not be qualified by an address-space qualifier." 11753 // Since all parameters have automatic store duration, they can not have 11754 // an address space. 11755 if (T.getAddressSpace() != 0) { 11756 // OpenCL allows function arguments declared to be an array of a type 11757 // to be qualified with an address space. 11758 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11759 Diag(NameLoc, diag::err_arg_with_address_space); 11760 New->setInvalidDecl(); 11761 } 11762 } 11763 11764 return New; 11765 } 11766 11767 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11768 SourceLocation LocAfterDecls) { 11769 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11770 11771 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11772 // for a K&R function. 11773 if (!FTI.hasPrototype) { 11774 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11775 --i; 11776 if (FTI.Params[i].Param == nullptr) { 11777 SmallString<256> Code; 11778 llvm::raw_svector_ostream(Code) 11779 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11780 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11781 << FTI.Params[i].Ident 11782 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11783 11784 // Implicitly declare the argument as type 'int' for lack of a better 11785 // type. 11786 AttributeFactory attrs; 11787 DeclSpec DS(attrs); 11788 const char* PrevSpec; // unused 11789 unsigned DiagID; // unused 11790 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11791 DiagID, Context.getPrintingPolicy()); 11792 // Use the identifier location for the type source range. 11793 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11794 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11795 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11796 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11797 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11798 } 11799 } 11800 } 11801 } 11802 11803 Decl * 11804 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11805 MultiTemplateParamsArg TemplateParameterLists, 11806 SkipBodyInfo *SkipBody) { 11807 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11808 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11809 Scope *ParentScope = FnBodyScope->getParent(); 11810 11811 D.setFunctionDefinitionKind(FDK_Definition); 11812 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11813 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11814 } 11815 11816 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11817 Consumer.HandleInlineFunctionDefinition(D); 11818 } 11819 11820 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11821 const FunctionDecl*& PossibleZeroParamPrototype) { 11822 // Don't warn about invalid declarations. 11823 if (FD->isInvalidDecl()) 11824 return false; 11825 11826 // Or declarations that aren't global. 11827 if (!FD->isGlobal()) 11828 return false; 11829 11830 // Don't warn about C++ member functions. 11831 if (isa<CXXMethodDecl>(FD)) 11832 return false; 11833 11834 // Don't warn about 'main'. 11835 if (FD->isMain()) 11836 return false; 11837 11838 // Don't warn about inline functions. 11839 if (FD->isInlined()) 11840 return false; 11841 11842 // Don't warn about function templates. 11843 if (FD->getDescribedFunctionTemplate()) 11844 return false; 11845 11846 // Don't warn about function template specializations. 11847 if (FD->isFunctionTemplateSpecialization()) 11848 return false; 11849 11850 // Don't warn for OpenCL kernels. 11851 if (FD->hasAttr<OpenCLKernelAttr>()) 11852 return false; 11853 11854 // Don't warn on explicitly deleted functions. 11855 if (FD->isDeleted()) 11856 return false; 11857 11858 bool MissingPrototype = true; 11859 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11860 Prev; Prev = Prev->getPreviousDecl()) { 11861 // Ignore any declarations that occur in function or method 11862 // scope, because they aren't visible from the header. 11863 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11864 continue; 11865 11866 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11867 if (FD->getNumParams() == 0) 11868 PossibleZeroParamPrototype = Prev; 11869 break; 11870 } 11871 11872 return MissingPrototype; 11873 } 11874 11875 void 11876 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11877 const FunctionDecl *EffectiveDefinition, 11878 SkipBodyInfo *SkipBody) { 11879 const FunctionDecl *Definition = EffectiveDefinition; 11880 if (!Definition) 11881 if (!FD->isDefined(Definition)) 11882 return; 11883 11884 if (canRedefineFunction(Definition, getLangOpts())) 11885 return; 11886 11887 // Don't emit an error when this is redifinition of a typo-corrected 11888 // definition. 11889 if (TypoCorrectedFunctionDefinitions.count(Definition)) 11890 return; 11891 11892 // If we don't have a visible definition of the function, and it's inline or 11893 // a template, skip the new definition. 11894 if (SkipBody && !hasVisibleDefinition(Definition) && 11895 (Definition->getFormalLinkage() == InternalLinkage || 11896 Definition->isInlined() || 11897 Definition->getDescribedFunctionTemplate() || 11898 Definition->getNumTemplateParameterLists())) { 11899 SkipBody->ShouldSkip = true; 11900 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11901 makeMergedDefinitionVisible(TD); 11902 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 11903 return; 11904 } 11905 11906 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11907 Definition->getStorageClass() == SC_Extern) 11908 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11909 << FD->getDeclName() << getLangOpts().CPlusPlus; 11910 else 11911 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11912 11913 Diag(Definition->getLocation(), diag::note_previous_definition); 11914 FD->setInvalidDecl(); 11915 } 11916 11917 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11918 Sema &S) { 11919 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11920 11921 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11922 LSI->CallOperator = CallOperator; 11923 LSI->Lambda = LambdaClass; 11924 LSI->ReturnType = CallOperator->getReturnType(); 11925 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11926 11927 if (LCD == LCD_None) 11928 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11929 else if (LCD == LCD_ByCopy) 11930 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11931 else if (LCD == LCD_ByRef) 11932 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11933 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11934 11935 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11936 LSI->Mutable = !CallOperator->isConst(); 11937 11938 // Add the captures to the LSI so they can be noted as already 11939 // captured within tryCaptureVar. 11940 auto I = LambdaClass->field_begin(); 11941 for (const auto &C : LambdaClass->captures()) { 11942 if (C.capturesVariable()) { 11943 VarDecl *VD = C.getCapturedVar(); 11944 if (VD->isInitCapture()) 11945 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11946 QualType CaptureType = VD->getType(); 11947 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11948 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11949 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11950 /*EllipsisLoc*/C.isPackExpansion() 11951 ? C.getEllipsisLoc() : SourceLocation(), 11952 CaptureType, /*Expr*/ nullptr); 11953 11954 } else if (C.capturesThis()) { 11955 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11956 /*Expr*/ nullptr, 11957 C.getCaptureKind() == LCK_StarThis); 11958 } else { 11959 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11960 } 11961 ++I; 11962 } 11963 } 11964 11965 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11966 SkipBodyInfo *SkipBody) { 11967 if (!D) 11968 return D; 11969 FunctionDecl *FD = nullptr; 11970 11971 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11972 FD = FunTmpl->getTemplatedDecl(); 11973 else 11974 FD = cast<FunctionDecl>(D); 11975 11976 // Check for defining attributes before the check for redefinition. 11977 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 11978 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 11979 FD->dropAttr<AliasAttr>(); 11980 FD->setInvalidDecl(); 11981 } 11982 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 11983 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 11984 FD->dropAttr<IFuncAttr>(); 11985 FD->setInvalidDecl(); 11986 } 11987 11988 // See if this is a redefinition. 11989 if (!FD->isLateTemplateParsed()) { 11990 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11991 11992 // If we're skipping the body, we're done. Don't enter the scope. 11993 if (SkipBody && SkipBody->ShouldSkip) 11994 return D; 11995 } 11996 11997 // Mark this function as "will have a body eventually". This lets users to 11998 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 11999 // this function. 12000 FD->setWillHaveBody(); 12001 12002 // If we are instantiating a generic lambda call operator, push 12003 // a LambdaScopeInfo onto the function stack. But use the information 12004 // that's already been calculated (ActOnLambdaExpr) to prime the current 12005 // LambdaScopeInfo. 12006 // When the template operator is being specialized, the LambdaScopeInfo, 12007 // has to be properly restored so that tryCaptureVariable doesn't try 12008 // and capture any new variables. In addition when calculating potential 12009 // captures during transformation of nested lambdas, it is necessary to 12010 // have the LSI properly restored. 12011 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12012 assert(inTemplateInstantiation() && 12013 "There should be an active template instantiation on the stack " 12014 "when instantiating a generic lambda!"); 12015 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12016 } else { 12017 // Enter a new function scope 12018 PushFunctionScope(); 12019 } 12020 12021 // Builtin functions cannot be defined. 12022 if (unsigned BuiltinID = FD->getBuiltinID()) { 12023 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12024 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12025 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12026 FD->setInvalidDecl(); 12027 } 12028 } 12029 12030 // The return type of a function definition must be complete 12031 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12032 QualType ResultType = FD->getReturnType(); 12033 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12034 !FD->isInvalidDecl() && 12035 RequireCompleteType(FD->getLocation(), ResultType, 12036 diag::err_func_def_incomplete_result)) 12037 FD->setInvalidDecl(); 12038 12039 if (FnBodyScope) 12040 PushDeclContext(FnBodyScope, FD); 12041 12042 // Check the validity of our function parameters 12043 CheckParmsForFunctionDef(FD->parameters(), 12044 /*CheckParameterNames=*/true); 12045 12046 // Add non-parameter declarations already in the function to the current 12047 // scope. 12048 if (FnBodyScope) { 12049 for (Decl *NPD : FD->decls()) { 12050 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12051 if (!NonParmDecl) 12052 continue; 12053 assert(!isa<ParmVarDecl>(NonParmDecl) && 12054 "parameters should not be in newly created FD yet"); 12055 12056 // If the decl has a name, make it accessible in the current scope. 12057 if (NonParmDecl->getDeclName()) 12058 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12059 12060 // Similarly, dive into enums and fish their constants out, making them 12061 // accessible in this scope. 12062 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12063 for (auto *EI : ED->enumerators()) 12064 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12065 } 12066 } 12067 } 12068 12069 // Introduce our parameters into the function scope 12070 for (auto Param : FD->parameters()) { 12071 Param->setOwningFunction(FD); 12072 12073 // If this has an identifier, add it to the scope stack. 12074 if (Param->getIdentifier() && FnBodyScope) { 12075 CheckShadow(FnBodyScope, Param); 12076 12077 PushOnScopeChains(Param, FnBodyScope); 12078 } 12079 } 12080 12081 // Ensure that the function's exception specification is instantiated. 12082 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12083 ResolveExceptionSpec(D->getLocation(), FPT); 12084 12085 // dllimport cannot be applied to non-inline function definitions. 12086 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12087 !FD->isTemplateInstantiation()) { 12088 assert(!FD->hasAttr<DLLExportAttr>()); 12089 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12090 FD->setInvalidDecl(); 12091 return D; 12092 } 12093 // We want to attach documentation to original Decl (which might be 12094 // a function template). 12095 ActOnDocumentableDecl(D); 12096 if (getCurLexicalContext()->isObjCContainer() && 12097 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12098 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12099 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12100 12101 return D; 12102 } 12103 12104 /// \brief Given the set of return statements within a function body, 12105 /// compute the variables that are subject to the named return value 12106 /// optimization. 12107 /// 12108 /// Each of the variables that is subject to the named return value 12109 /// optimization will be marked as NRVO variables in the AST, and any 12110 /// return statement that has a marked NRVO variable as its NRVO candidate can 12111 /// use the named return value optimization. 12112 /// 12113 /// This function applies a very simplistic algorithm for NRVO: if every return 12114 /// statement in the scope of a variable has the same NRVO candidate, that 12115 /// candidate is an NRVO variable. 12116 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12117 ReturnStmt **Returns = Scope->Returns.data(); 12118 12119 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12120 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12121 if (!NRVOCandidate->isNRVOVariable()) 12122 Returns[I]->setNRVOCandidate(nullptr); 12123 } 12124 } 12125 } 12126 12127 bool Sema::canDelayFunctionBody(const Declarator &D) { 12128 // We can't delay parsing the body of a constexpr function template (yet). 12129 if (D.getDeclSpec().isConstexprSpecified()) 12130 return false; 12131 12132 // We can't delay parsing the body of a function template with a deduced 12133 // return type (yet). 12134 if (D.getDeclSpec().hasAutoTypeSpec()) { 12135 // If the placeholder introduces a non-deduced trailing return type, 12136 // we can still delay parsing it. 12137 if (D.getNumTypeObjects()) { 12138 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12139 if (Outer.Kind == DeclaratorChunk::Function && 12140 Outer.Fun.hasTrailingReturnType()) { 12141 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12142 return Ty.isNull() || !Ty->isUndeducedType(); 12143 } 12144 } 12145 return false; 12146 } 12147 12148 return true; 12149 } 12150 12151 bool Sema::canSkipFunctionBody(Decl *D) { 12152 // We cannot skip the body of a function (or function template) which is 12153 // constexpr, since we may need to evaluate its body in order to parse the 12154 // rest of the file. 12155 // We cannot skip the body of a function with an undeduced return type, 12156 // because any callers of that function need to know the type. 12157 if (const FunctionDecl *FD = D->getAsFunction()) 12158 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12159 return false; 12160 return Consumer.shouldSkipFunctionBody(D); 12161 } 12162 12163 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12164 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 12165 FD->setHasSkippedBody(); 12166 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 12167 MD->setHasSkippedBody(); 12168 return Decl; 12169 } 12170 12171 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12172 return ActOnFinishFunctionBody(D, BodyArg, false); 12173 } 12174 12175 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12176 bool IsInstantiation) { 12177 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12178 12179 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12180 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12181 12182 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12183 CheckCompletedCoroutineBody(FD, Body); 12184 12185 if (FD) { 12186 FD->setBody(Body); 12187 12188 if (getLangOpts().CPlusPlus14) { 12189 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12190 FD->getReturnType()->isUndeducedType()) { 12191 // If the function has a deduced result type but contains no 'return' 12192 // statements, the result type as written must be exactly 'auto', and 12193 // the deduced result type is 'void'. 12194 if (!FD->getReturnType()->getAs<AutoType>()) { 12195 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12196 << FD->getReturnType(); 12197 FD->setInvalidDecl(); 12198 } else { 12199 // Substitute 'void' for the 'auto' in the type. 12200 TypeLoc ResultType = getReturnTypeLoc(FD); 12201 Context.adjustDeducedFunctionResultType( 12202 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12203 } 12204 } 12205 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12206 // In C++11, we don't use 'auto' deduction rules for lambda call 12207 // operators because we don't support return type deduction. 12208 auto *LSI = getCurLambda(); 12209 if (LSI->HasImplicitReturnType) { 12210 deduceClosureReturnType(*LSI); 12211 12212 // C++11 [expr.prim.lambda]p4: 12213 // [...] if there are no return statements in the compound-statement 12214 // [the deduced type is] the type void 12215 QualType RetType = 12216 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12217 12218 // Update the return type to the deduced type. 12219 const FunctionProtoType *Proto = 12220 FD->getType()->getAs<FunctionProtoType>(); 12221 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12222 Proto->getExtProtoInfo())); 12223 } 12224 } 12225 12226 // The only way to be included in UndefinedButUsed is if there is an 12227 // ODR use before the definition. Avoid the expensive map lookup if this 12228 // is the first declaration. 12229 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 12230 if (!FD->isExternallyVisible()) 12231 UndefinedButUsed.erase(FD); 12232 else if (FD->isInlined() && 12233 !LangOpts.GNUInline && 12234 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 12235 UndefinedButUsed.erase(FD); 12236 } 12237 12238 // If the function implicitly returns zero (like 'main') or is naked, 12239 // don't complain about missing return statements. 12240 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12241 WP.disableCheckFallThrough(); 12242 12243 // MSVC permits the use of pure specifier (=0) on function definition, 12244 // defined at class scope, warn about this non-standard construct. 12245 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12246 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12247 12248 if (!FD->isInvalidDecl()) { 12249 // Don't diagnose unused parameters of defaulted or deleted functions. 12250 if (!FD->isDeleted() && !FD->isDefaulted()) 12251 DiagnoseUnusedParameters(FD->parameters()); 12252 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12253 FD->getReturnType(), FD); 12254 12255 // If this is a structor, we need a vtable. 12256 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12257 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12258 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12259 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12260 12261 // Try to apply the named return value optimization. We have to check 12262 // if we can do this here because lambdas keep return statements around 12263 // to deduce an implicit return type. 12264 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12265 !FD->isDependentContext()) 12266 computeNRVO(Body, getCurFunction()); 12267 } 12268 12269 // GNU warning -Wmissing-prototypes: 12270 // Warn if a global function is defined without a previous 12271 // prototype declaration. This warning is issued even if the 12272 // definition itself provides a prototype. The aim is to detect 12273 // global functions that fail to be declared in header files. 12274 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12275 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12276 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12277 12278 if (PossibleZeroParamPrototype) { 12279 // We found a declaration that is not a prototype, 12280 // but that could be a zero-parameter prototype 12281 if (TypeSourceInfo *TI = 12282 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12283 TypeLoc TL = TI->getTypeLoc(); 12284 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12285 Diag(PossibleZeroParamPrototype->getLocation(), 12286 diag::note_declaration_not_a_prototype) 12287 << PossibleZeroParamPrototype 12288 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12289 } 12290 } 12291 12292 // GNU warning -Wstrict-prototypes 12293 // Warn if K&R function is defined without a previous declaration. 12294 // This warning is issued only if the definition itself does not provide 12295 // a prototype. Only K&R definitions do not provide a prototype. 12296 // An empty list in a function declarator that is part of a definition 12297 // of that function specifies that the function has no parameters 12298 // (C99 6.7.5.3p14) 12299 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12300 !LangOpts.CPlusPlus) { 12301 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12302 TypeLoc TL = TI->getTypeLoc(); 12303 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12304 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1; 12305 } 12306 } 12307 12308 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12309 const CXXMethodDecl *KeyFunction; 12310 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12311 MD->isVirtual() && 12312 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12313 MD == KeyFunction->getCanonicalDecl()) { 12314 // Update the key-function state if necessary for this ABI. 12315 if (FD->isInlined() && 12316 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12317 Context.setNonKeyFunction(MD); 12318 12319 // If the newly-chosen key function is already defined, then we 12320 // need to mark the vtable as used retroactively. 12321 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12322 const FunctionDecl *Definition; 12323 if (KeyFunction && KeyFunction->isDefined(Definition)) 12324 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12325 } else { 12326 // We just defined they key function; mark the vtable as used. 12327 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12328 } 12329 } 12330 } 12331 12332 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12333 "Function parsing confused"); 12334 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12335 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12336 MD->setBody(Body); 12337 if (!MD->isInvalidDecl()) { 12338 DiagnoseUnusedParameters(MD->parameters()); 12339 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12340 MD->getReturnType(), MD); 12341 12342 if (Body) 12343 computeNRVO(Body, getCurFunction()); 12344 } 12345 if (getCurFunction()->ObjCShouldCallSuper) { 12346 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12347 << MD->getSelector().getAsString(); 12348 getCurFunction()->ObjCShouldCallSuper = false; 12349 } 12350 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12351 const ObjCMethodDecl *InitMethod = nullptr; 12352 bool isDesignated = 12353 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12354 assert(isDesignated && InitMethod); 12355 (void)isDesignated; 12356 12357 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12358 auto IFace = MD->getClassInterface(); 12359 if (!IFace) 12360 return false; 12361 auto SuperD = IFace->getSuperClass(); 12362 if (!SuperD) 12363 return false; 12364 return SuperD->getIdentifier() == 12365 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12366 }; 12367 // Don't issue this warning for unavailable inits or direct subclasses 12368 // of NSObject. 12369 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12370 Diag(MD->getLocation(), 12371 diag::warn_objc_designated_init_missing_super_call); 12372 Diag(InitMethod->getLocation(), 12373 diag::note_objc_designated_init_marked_here); 12374 } 12375 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12376 } 12377 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12378 // Don't issue this warning for unavaialable inits. 12379 if (!MD->isUnavailable()) 12380 Diag(MD->getLocation(), 12381 diag::warn_objc_secondary_init_missing_init_call); 12382 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12383 } 12384 } else { 12385 return nullptr; 12386 } 12387 12388 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12389 DiagnoseUnguardedAvailabilityViolations(dcl); 12390 12391 assert(!getCurFunction()->ObjCShouldCallSuper && 12392 "This should only be set for ObjC methods, which should have been " 12393 "handled in the block above."); 12394 12395 // Verify and clean out per-function state. 12396 if (Body && (!FD || !FD->isDefaulted())) { 12397 // C++ constructors that have function-try-blocks can't have return 12398 // statements in the handlers of that block. (C++ [except.handle]p14) 12399 // Verify this. 12400 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12401 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12402 12403 // Verify that gotos and switch cases don't jump into scopes illegally. 12404 if (getCurFunction()->NeedsScopeChecking() && 12405 !PP.isCodeCompletionEnabled()) 12406 DiagnoseInvalidJumps(Body); 12407 12408 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12409 if (!Destructor->getParent()->isDependentType()) 12410 CheckDestructor(Destructor); 12411 12412 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12413 Destructor->getParent()); 12414 } 12415 12416 // If any errors have occurred, clear out any temporaries that may have 12417 // been leftover. This ensures that these temporaries won't be picked up for 12418 // deletion in some later function. 12419 if (getDiagnostics().hasErrorOccurred() || 12420 getDiagnostics().getSuppressAllDiagnostics()) { 12421 DiscardCleanupsInEvaluationContext(); 12422 } 12423 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12424 !isa<FunctionTemplateDecl>(dcl)) { 12425 // Since the body is valid, issue any analysis-based warnings that are 12426 // enabled. 12427 ActivePolicy = &WP; 12428 } 12429 12430 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12431 (!CheckConstexprFunctionDecl(FD) || 12432 !CheckConstexprFunctionBody(FD, Body))) 12433 FD->setInvalidDecl(); 12434 12435 if (FD && FD->hasAttr<NakedAttr>()) { 12436 for (const Stmt *S : Body->children()) { 12437 // Allow local register variables without initializer as they don't 12438 // require prologue. 12439 bool RegisterVariables = false; 12440 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12441 for (const auto *Decl : DS->decls()) { 12442 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12443 RegisterVariables = 12444 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12445 if (!RegisterVariables) 12446 break; 12447 } 12448 } 12449 } 12450 if (RegisterVariables) 12451 continue; 12452 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12453 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12454 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12455 FD->setInvalidDecl(); 12456 break; 12457 } 12458 } 12459 } 12460 12461 assert(ExprCleanupObjects.size() == 12462 ExprEvalContexts.back().NumCleanupObjects && 12463 "Leftover temporaries in function"); 12464 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12465 assert(MaybeODRUseExprs.empty() && 12466 "Leftover expressions for odr-use checking"); 12467 } 12468 12469 if (!IsInstantiation) 12470 PopDeclContext(); 12471 12472 PopFunctionScopeInfo(ActivePolicy, dcl); 12473 // If any errors have occurred, clear out any temporaries that may have 12474 // been leftover. This ensures that these temporaries won't be picked up for 12475 // deletion in some later function. 12476 if (getDiagnostics().hasErrorOccurred()) { 12477 DiscardCleanupsInEvaluationContext(); 12478 } 12479 12480 return dcl; 12481 } 12482 12483 /// When we finish delayed parsing of an attribute, we must attach it to the 12484 /// relevant Decl. 12485 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12486 ParsedAttributes &Attrs) { 12487 // Always attach attributes to the underlying decl. 12488 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12489 D = TD->getTemplatedDecl(); 12490 ProcessDeclAttributeList(S, D, Attrs.getList()); 12491 12492 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12493 if (Method->isStatic()) 12494 checkThisInStaticMemberFunctionAttributes(Method); 12495 } 12496 12497 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12498 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12499 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12500 IdentifierInfo &II, Scope *S) { 12501 // Before we produce a declaration for an implicitly defined 12502 // function, see whether there was a locally-scoped declaration of 12503 // this name as a function or variable. If so, use that 12504 // (non-visible) declaration, and complain about it. 12505 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12506 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12507 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12508 return ExternCPrev; 12509 } 12510 12511 // Extension in C99. Legal in C90, but warn about it. 12512 unsigned diag_id; 12513 if (II.getName().startswith("__builtin_")) 12514 diag_id = diag::warn_builtin_unknown; 12515 else if (getLangOpts().C99) 12516 diag_id = diag::ext_implicit_function_decl; 12517 else 12518 diag_id = diag::warn_implicit_function_decl; 12519 Diag(Loc, diag_id) << &II; 12520 12521 // Because typo correction is expensive, only do it if the implicit 12522 // function declaration is going to be treated as an error. 12523 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12524 TypoCorrection Corrected; 12525 if (S && 12526 (Corrected = CorrectTypo( 12527 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12528 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12529 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12530 /*ErrorRecovery*/false); 12531 } 12532 12533 // Set a Declarator for the implicit definition: int foo(); 12534 const char *Dummy; 12535 AttributeFactory attrFactory; 12536 DeclSpec DS(attrFactory); 12537 unsigned DiagID; 12538 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12539 Context.getPrintingPolicy()); 12540 (void)Error; // Silence warning. 12541 assert(!Error && "Error setting up implicit decl!"); 12542 SourceLocation NoLoc; 12543 Declarator D(DS, Declarator::BlockContext); 12544 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12545 /*IsAmbiguous=*/false, 12546 /*LParenLoc=*/NoLoc, 12547 /*Params=*/nullptr, 12548 /*NumParams=*/0, 12549 /*EllipsisLoc=*/NoLoc, 12550 /*RParenLoc=*/NoLoc, 12551 /*TypeQuals=*/0, 12552 /*RefQualifierIsLvalueRef=*/true, 12553 /*RefQualifierLoc=*/NoLoc, 12554 /*ConstQualifierLoc=*/NoLoc, 12555 /*VolatileQualifierLoc=*/NoLoc, 12556 /*RestrictQualifierLoc=*/NoLoc, 12557 /*MutableLoc=*/NoLoc, 12558 EST_None, 12559 /*ESpecRange=*/SourceRange(), 12560 /*Exceptions=*/nullptr, 12561 /*ExceptionRanges=*/nullptr, 12562 /*NumExceptions=*/0, 12563 /*NoexceptExpr=*/nullptr, 12564 /*ExceptionSpecTokens=*/nullptr, 12565 /*DeclsInPrototype=*/None, 12566 Loc, Loc, D), 12567 DS.getAttributes(), 12568 SourceLocation()); 12569 D.SetIdentifier(&II, Loc); 12570 12571 // Insert this function into translation-unit scope. 12572 12573 DeclContext *PrevDC = CurContext; 12574 CurContext = Context.getTranslationUnitDecl(); 12575 12576 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12577 FD->setImplicit(); 12578 12579 CurContext = PrevDC; 12580 12581 AddKnownFunctionAttributes(FD); 12582 12583 return FD; 12584 } 12585 12586 /// \brief Adds any function attributes that we know a priori based on 12587 /// the declaration of this function. 12588 /// 12589 /// These attributes can apply both to implicitly-declared builtins 12590 /// (like __builtin___printf_chk) or to library-declared functions 12591 /// like NSLog or printf. 12592 /// 12593 /// We need to check for duplicate attributes both here and where user-written 12594 /// attributes are applied to declarations. 12595 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12596 if (FD->isInvalidDecl()) 12597 return; 12598 12599 // If this is a built-in function, map its builtin attributes to 12600 // actual attributes. 12601 if (unsigned BuiltinID = FD->getBuiltinID()) { 12602 // Handle printf-formatting attributes. 12603 unsigned FormatIdx; 12604 bool HasVAListArg; 12605 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12606 if (!FD->hasAttr<FormatAttr>()) { 12607 const char *fmt = "printf"; 12608 unsigned int NumParams = FD->getNumParams(); 12609 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12610 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12611 fmt = "NSString"; 12612 FD->addAttr(FormatAttr::CreateImplicit(Context, 12613 &Context.Idents.get(fmt), 12614 FormatIdx+1, 12615 HasVAListArg ? 0 : FormatIdx+2, 12616 FD->getLocation())); 12617 } 12618 } 12619 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12620 HasVAListArg)) { 12621 if (!FD->hasAttr<FormatAttr>()) 12622 FD->addAttr(FormatAttr::CreateImplicit(Context, 12623 &Context.Idents.get("scanf"), 12624 FormatIdx+1, 12625 HasVAListArg ? 0 : FormatIdx+2, 12626 FD->getLocation())); 12627 } 12628 12629 // Mark const if we don't care about errno and that is the only 12630 // thing preventing the function from being const. This allows 12631 // IRgen to use LLVM intrinsics for such functions. 12632 if (!getLangOpts().MathErrno && 12633 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12634 if (!FD->hasAttr<ConstAttr>()) 12635 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12636 } 12637 12638 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12639 !FD->hasAttr<ReturnsTwiceAttr>()) 12640 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12641 FD->getLocation())); 12642 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12643 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12644 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12645 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12646 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12647 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12648 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12649 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12650 // Add the appropriate attribute, depending on the CUDA compilation mode 12651 // and which target the builtin belongs to. For example, during host 12652 // compilation, aux builtins are __device__, while the rest are __host__. 12653 if (getLangOpts().CUDAIsDevice != 12654 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12655 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12656 else 12657 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12658 } 12659 } 12660 12661 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12662 // throw, add an implicit nothrow attribute to any extern "C" function we come 12663 // across. 12664 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12665 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12666 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12667 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12668 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12669 } 12670 12671 IdentifierInfo *Name = FD->getIdentifier(); 12672 if (!Name) 12673 return; 12674 if ((!getLangOpts().CPlusPlus && 12675 FD->getDeclContext()->isTranslationUnit()) || 12676 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12677 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12678 LinkageSpecDecl::lang_c)) { 12679 // Okay: this could be a libc/libm/Objective-C function we know 12680 // about. 12681 } else 12682 return; 12683 12684 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12685 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12686 // target-specific builtins, perhaps? 12687 if (!FD->hasAttr<FormatAttr>()) 12688 FD->addAttr(FormatAttr::CreateImplicit(Context, 12689 &Context.Idents.get("printf"), 2, 12690 Name->isStr("vasprintf") ? 0 : 3, 12691 FD->getLocation())); 12692 } 12693 12694 if (Name->isStr("__CFStringMakeConstantString")) { 12695 // We already have a __builtin___CFStringMakeConstantString, 12696 // but builds that use -fno-constant-cfstrings don't go through that. 12697 if (!FD->hasAttr<FormatArgAttr>()) 12698 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12699 FD->getLocation())); 12700 } 12701 } 12702 12703 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12704 TypeSourceInfo *TInfo) { 12705 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12706 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12707 12708 if (!TInfo) { 12709 assert(D.isInvalidType() && "no declarator info for valid type"); 12710 TInfo = Context.getTrivialTypeSourceInfo(T); 12711 } 12712 12713 // Scope manipulation handled by caller. 12714 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12715 D.getLocStart(), 12716 D.getIdentifierLoc(), 12717 D.getIdentifier(), 12718 TInfo); 12719 12720 // Bail out immediately if we have an invalid declaration. 12721 if (D.isInvalidType()) { 12722 NewTD->setInvalidDecl(); 12723 return NewTD; 12724 } 12725 12726 if (D.getDeclSpec().isModulePrivateSpecified()) { 12727 if (CurContext->isFunctionOrMethod()) 12728 Diag(NewTD->getLocation(), diag::err_module_private_local) 12729 << 2 << NewTD->getDeclName() 12730 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12731 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12732 else 12733 NewTD->setModulePrivate(); 12734 } 12735 12736 // C++ [dcl.typedef]p8: 12737 // If the typedef declaration defines an unnamed class (or 12738 // enum), the first typedef-name declared by the declaration 12739 // to be that class type (or enum type) is used to denote the 12740 // class type (or enum type) for linkage purposes only. 12741 // We need to check whether the type was declared in the declaration. 12742 switch (D.getDeclSpec().getTypeSpecType()) { 12743 case TST_enum: 12744 case TST_struct: 12745 case TST_interface: 12746 case TST_union: 12747 case TST_class: { 12748 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12749 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12750 break; 12751 } 12752 12753 default: 12754 break; 12755 } 12756 12757 return NewTD; 12758 } 12759 12760 /// \brief Check that this is a valid underlying type for an enum declaration. 12761 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12762 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12763 QualType T = TI->getType(); 12764 12765 if (T->isDependentType()) 12766 return false; 12767 12768 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12769 if (BT->isInteger()) 12770 return false; 12771 12772 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12773 return true; 12774 } 12775 12776 /// Check whether this is a valid redeclaration of a previous enumeration. 12777 /// \return true if the redeclaration was invalid. 12778 bool Sema::CheckEnumRedeclaration( 12779 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12780 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12781 bool IsFixed = !EnumUnderlyingTy.isNull(); 12782 12783 if (IsScoped != Prev->isScoped()) { 12784 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12785 << Prev->isScoped(); 12786 Diag(Prev->getLocation(), diag::note_previous_declaration); 12787 return true; 12788 } 12789 12790 if (IsFixed && Prev->isFixed()) { 12791 if (!EnumUnderlyingTy->isDependentType() && 12792 !Prev->getIntegerType()->isDependentType() && 12793 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12794 Prev->getIntegerType())) { 12795 // TODO: Highlight the underlying type of the redeclaration. 12796 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12797 << EnumUnderlyingTy << Prev->getIntegerType(); 12798 Diag(Prev->getLocation(), diag::note_previous_declaration) 12799 << Prev->getIntegerTypeRange(); 12800 return true; 12801 } 12802 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12803 ; 12804 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12805 ; 12806 } else if (IsFixed != Prev->isFixed()) { 12807 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12808 << Prev->isFixed(); 12809 Diag(Prev->getLocation(), diag::note_previous_declaration); 12810 return true; 12811 } 12812 12813 return false; 12814 } 12815 12816 /// \brief Get diagnostic %select index for tag kind for 12817 /// redeclaration diagnostic message. 12818 /// WARNING: Indexes apply to particular diagnostics only! 12819 /// 12820 /// \returns diagnostic %select index. 12821 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12822 switch (Tag) { 12823 case TTK_Struct: return 0; 12824 case TTK_Interface: return 1; 12825 case TTK_Class: return 2; 12826 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12827 } 12828 } 12829 12830 /// \brief Determine if tag kind is a class-key compatible with 12831 /// class for redeclaration (class, struct, or __interface). 12832 /// 12833 /// \returns true iff the tag kind is compatible. 12834 static bool isClassCompatTagKind(TagTypeKind Tag) 12835 { 12836 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12837 } 12838 12839 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12840 TagTypeKind TTK) { 12841 if (isa<TypedefDecl>(PrevDecl)) 12842 return NTK_Typedef; 12843 else if (isa<TypeAliasDecl>(PrevDecl)) 12844 return NTK_TypeAlias; 12845 else if (isa<ClassTemplateDecl>(PrevDecl)) 12846 return NTK_Template; 12847 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12848 return NTK_TypeAliasTemplate; 12849 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12850 return NTK_TemplateTemplateArgument; 12851 switch (TTK) { 12852 case TTK_Struct: 12853 case TTK_Interface: 12854 case TTK_Class: 12855 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12856 case TTK_Union: 12857 return NTK_NonUnion; 12858 case TTK_Enum: 12859 return NTK_NonEnum; 12860 } 12861 llvm_unreachable("invalid TTK"); 12862 } 12863 12864 /// \brief Determine whether a tag with a given kind is acceptable 12865 /// as a redeclaration of the given tag declaration. 12866 /// 12867 /// \returns true if the new tag kind is acceptable, false otherwise. 12868 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12869 TagTypeKind NewTag, bool isDefinition, 12870 SourceLocation NewTagLoc, 12871 const IdentifierInfo *Name) { 12872 // C++ [dcl.type.elab]p3: 12873 // The class-key or enum keyword present in the 12874 // elaborated-type-specifier shall agree in kind with the 12875 // declaration to which the name in the elaborated-type-specifier 12876 // refers. This rule also applies to the form of 12877 // elaborated-type-specifier that declares a class-name or 12878 // friend class since it can be construed as referring to the 12879 // definition of the class. Thus, in any 12880 // elaborated-type-specifier, the enum keyword shall be used to 12881 // refer to an enumeration (7.2), the union class-key shall be 12882 // used to refer to a union (clause 9), and either the class or 12883 // struct class-key shall be used to refer to a class (clause 9) 12884 // declared using the class or struct class-key. 12885 TagTypeKind OldTag = Previous->getTagKind(); 12886 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12887 if (OldTag == NewTag) 12888 return true; 12889 12890 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12891 // Warn about the struct/class tag mismatch. 12892 bool isTemplate = false; 12893 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12894 isTemplate = Record->getDescribedClassTemplate(); 12895 12896 if (inTemplateInstantiation()) { 12897 // In a template instantiation, do not offer fix-its for tag mismatches 12898 // since they usually mess up the template instead of fixing the problem. 12899 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12900 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12901 << getRedeclDiagFromTagKind(OldTag); 12902 return true; 12903 } 12904 12905 if (isDefinition) { 12906 // On definitions, check previous tags and issue a fix-it for each 12907 // one that doesn't match the current tag. 12908 if (Previous->getDefinition()) { 12909 // Don't suggest fix-its for redefinitions. 12910 return true; 12911 } 12912 12913 bool previousMismatch = false; 12914 for (auto I : Previous->redecls()) { 12915 if (I->getTagKind() != NewTag) { 12916 if (!previousMismatch) { 12917 previousMismatch = true; 12918 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12919 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12920 << getRedeclDiagFromTagKind(I->getTagKind()); 12921 } 12922 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12923 << getRedeclDiagFromTagKind(NewTag) 12924 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12925 TypeWithKeyword::getTagTypeKindName(NewTag)); 12926 } 12927 } 12928 return true; 12929 } 12930 12931 // Check for a previous definition. If current tag and definition 12932 // are same type, do nothing. If no definition, but disagree with 12933 // with previous tag type, give a warning, but no fix-it. 12934 const TagDecl *Redecl = Previous->getDefinition() ? 12935 Previous->getDefinition() : Previous; 12936 if (Redecl->getTagKind() == NewTag) { 12937 return true; 12938 } 12939 12940 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12941 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12942 << getRedeclDiagFromTagKind(OldTag); 12943 Diag(Redecl->getLocation(), diag::note_previous_use); 12944 12945 // If there is a previous definition, suggest a fix-it. 12946 if (Previous->getDefinition()) { 12947 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12948 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12949 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12950 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12951 } 12952 12953 return true; 12954 } 12955 return false; 12956 } 12957 12958 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12959 /// from an outer enclosing namespace or file scope inside a friend declaration. 12960 /// This should provide the commented out code in the following snippet: 12961 /// namespace N { 12962 /// struct X; 12963 /// namespace M { 12964 /// struct Y { friend struct /*N::*/ X; }; 12965 /// } 12966 /// } 12967 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12968 SourceLocation NameLoc) { 12969 // While the decl is in a namespace, do repeated lookup of that name and see 12970 // if we get the same namespace back. If we do not, continue until 12971 // translation unit scope, at which point we have a fully qualified NNS. 12972 SmallVector<IdentifierInfo *, 4> Namespaces; 12973 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12974 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12975 // This tag should be declared in a namespace, which can only be enclosed by 12976 // other namespaces. Bail if there's an anonymous namespace in the chain. 12977 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12978 if (!Namespace || Namespace->isAnonymousNamespace()) 12979 return FixItHint(); 12980 IdentifierInfo *II = Namespace->getIdentifier(); 12981 Namespaces.push_back(II); 12982 NamedDecl *Lookup = SemaRef.LookupSingleName( 12983 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12984 if (Lookup == Namespace) 12985 break; 12986 } 12987 12988 // Once we have all the namespaces, reverse them to go outermost first, and 12989 // build an NNS. 12990 SmallString<64> Insertion; 12991 llvm::raw_svector_ostream OS(Insertion); 12992 if (DC->isTranslationUnit()) 12993 OS << "::"; 12994 std::reverse(Namespaces.begin(), Namespaces.end()); 12995 for (auto *II : Namespaces) 12996 OS << II->getName() << "::"; 12997 return FixItHint::CreateInsertion(NameLoc, Insertion); 12998 } 12999 13000 /// \brief Determine whether a tag originally declared in context \p OldDC can 13001 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 13002 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13003 /// using-declaration). 13004 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13005 DeclContext *NewDC) { 13006 OldDC = OldDC->getRedeclContext(); 13007 NewDC = NewDC->getRedeclContext(); 13008 13009 if (OldDC->Equals(NewDC)) 13010 return true; 13011 13012 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13013 // encloses the other). 13014 if (S.getLangOpts().MSVCCompat && 13015 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13016 return true; 13017 13018 return false; 13019 } 13020 13021 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13022 /// former case, Name will be non-null. In the later case, Name will be null. 13023 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13024 /// reference/declaration/definition of a tag. 13025 /// 13026 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13027 /// trailing-type-specifier) other than one in an alias-declaration. 13028 /// 13029 /// \param SkipBody If non-null, will be set to indicate if the caller should 13030 /// skip the definition of this tag and treat it as if it were a declaration. 13031 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13032 SourceLocation KWLoc, CXXScopeSpec &SS, 13033 IdentifierInfo *Name, SourceLocation NameLoc, 13034 AttributeList *Attr, AccessSpecifier AS, 13035 SourceLocation ModulePrivateLoc, 13036 MultiTemplateParamsArg TemplateParameterLists, 13037 bool &OwnedDecl, bool &IsDependent, 13038 SourceLocation ScopedEnumKWLoc, 13039 bool ScopedEnumUsesClassTag, 13040 TypeResult UnderlyingType, 13041 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 13042 // If this is not a definition, it must have a name. 13043 IdentifierInfo *OrigName = Name; 13044 assert((Name != nullptr || TUK == TUK_Definition) && 13045 "Nameless record must be a definition!"); 13046 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13047 13048 OwnedDecl = false; 13049 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13050 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13051 13052 // FIXME: Check member specializations more carefully. 13053 bool isMemberSpecialization = false; 13054 bool Invalid = false; 13055 13056 // We only need to do this matching if we have template parameters 13057 // or a scope specifier, which also conveniently avoids this work 13058 // for non-C++ cases. 13059 if (TemplateParameterLists.size() > 0 || 13060 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13061 if (TemplateParameterList *TemplateParams = 13062 MatchTemplateParametersToScopeSpecifier( 13063 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13064 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13065 if (Kind == TTK_Enum) { 13066 Diag(KWLoc, diag::err_enum_template); 13067 return nullptr; 13068 } 13069 13070 if (TemplateParams->size() > 0) { 13071 // This is a declaration or definition of a class template (which may 13072 // be a member of another template). 13073 13074 if (Invalid) 13075 return nullptr; 13076 13077 OwnedDecl = false; 13078 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13079 SS, Name, NameLoc, Attr, 13080 TemplateParams, AS, 13081 ModulePrivateLoc, 13082 /*FriendLoc*/SourceLocation(), 13083 TemplateParameterLists.size()-1, 13084 TemplateParameterLists.data(), 13085 SkipBody); 13086 return Result.get(); 13087 } else { 13088 // The "template<>" header is extraneous. 13089 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13090 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13091 isMemberSpecialization = true; 13092 } 13093 } 13094 } 13095 13096 // Figure out the underlying type if this a enum declaration. We need to do 13097 // this early, because it's needed to detect if this is an incompatible 13098 // redeclaration. 13099 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13100 bool EnumUnderlyingIsImplicit = false; 13101 13102 if (Kind == TTK_Enum) { 13103 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 13104 // No underlying type explicitly specified, or we failed to parse the 13105 // type, default to int. 13106 EnumUnderlying = Context.IntTy.getTypePtr(); 13107 else if (UnderlyingType.get()) { 13108 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13109 // integral type; any cv-qualification is ignored. 13110 TypeSourceInfo *TI = nullptr; 13111 GetTypeFromParser(UnderlyingType.get(), &TI); 13112 EnumUnderlying = TI; 13113 13114 if (CheckEnumUnderlyingType(TI)) 13115 // Recover by falling back to int. 13116 EnumUnderlying = Context.IntTy.getTypePtr(); 13117 13118 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13119 UPPC_FixedUnderlyingType)) 13120 EnumUnderlying = Context.IntTy.getTypePtr(); 13121 13122 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13123 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 13124 // Microsoft enums are always of int type. 13125 EnumUnderlying = Context.IntTy.getTypePtr(); 13126 EnumUnderlyingIsImplicit = true; 13127 } 13128 } 13129 } 13130 13131 DeclContext *SearchDC = CurContext; 13132 DeclContext *DC = CurContext; 13133 bool isStdBadAlloc = false; 13134 bool isStdAlignValT = false; 13135 13136 RedeclarationKind Redecl = ForRedeclaration; 13137 if (TUK == TUK_Friend || TUK == TUK_Reference) 13138 Redecl = NotForRedeclaration; 13139 13140 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13141 if (Name && SS.isNotEmpty()) { 13142 // We have a nested-name tag ('struct foo::bar'). 13143 13144 // Check for invalid 'foo::'. 13145 if (SS.isInvalid()) { 13146 Name = nullptr; 13147 goto CreateNewDecl; 13148 } 13149 13150 // If this is a friend or a reference to a class in a dependent 13151 // context, don't try to make a decl for it. 13152 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13153 DC = computeDeclContext(SS, false); 13154 if (!DC) { 13155 IsDependent = true; 13156 return nullptr; 13157 } 13158 } else { 13159 DC = computeDeclContext(SS, true); 13160 if (!DC) { 13161 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13162 << SS.getRange(); 13163 return nullptr; 13164 } 13165 } 13166 13167 if (RequireCompleteDeclContext(SS, DC)) 13168 return nullptr; 13169 13170 SearchDC = DC; 13171 // Look-up name inside 'foo::'. 13172 LookupQualifiedName(Previous, DC); 13173 13174 if (Previous.isAmbiguous()) 13175 return nullptr; 13176 13177 if (Previous.empty()) { 13178 // Name lookup did not find anything. However, if the 13179 // nested-name-specifier refers to the current instantiation, 13180 // and that current instantiation has any dependent base 13181 // classes, we might find something at instantiation time: treat 13182 // this as a dependent elaborated-type-specifier. 13183 // But this only makes any sense for reference-like lookups. 13184 if (Previous.wasNotFoundInCurrentInstantiation() && 13185 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13186 IsDependent = true; 13187 return nullptr; 13188 } 13189 13190 // A tag 'foo::bar' must already exist. 13191 Diag(NameLoc, diag::err_not_tag_in_scope) 13192 << Kind << Name << DC << SS.getRange(); 13193 Name = nullptr; 13194 Invalid = true; 13195 goto CreateNewDecl; 13196 } 13197 } else if (Name) { 13198 // C++14 [class.mem]p14: 13199 // If T is the name of a class, then each of the following shall have a 13200 // name different from T: 13201 // -- every member of class T that is itself a type 13202 if (TUK != TUK_Reference && TUK != TUK_Friend && 13203 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13204 return nullptr; 13205 13206 // If this is a named struct, check to see if there was a previous forward 13207 // declaration or definition. 13208 // FIXME: We're looking into outer scopes here, even when we 13209 // shouldn't be. Doing so can result in ambiguities that we 13210 // shouldn't be diagnosing. 13211 LookupName(Previous, S); 13212 13213 // When declaring or defining a tag, ignore ambiguities introduced 13214 // by types using'ed into this scope. 13215 if (Previous.isAmbiguous() && 13216 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13217 LookupResult::Filter F = Previous.makeFilter(); 13218 while (F.hasNext()) { 13219 NamedDecl *ND = F.next(); 13220 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13221 SearchDC->getRedeclContext())) 13222 F.erase(); 13223 } 13224 F.done(); 13225 } 13226 13227 // C++11 [namespace.memdef]p3: 13228 // If the name in a friend declaration is neither qualified nor 13229 // a template-id and the declaration is a function or an 13230 // elaborated-type-specifier, the lookup to determine whether 13231 // the entity has been previously declared shall not consider 13232 // any scopes outside the innermost enclosing namespace. 13233 // 13234 // MSVC doesn't implement the above rule for types, so a friend tag 13235 // declaration may be a redeclaration of a type declared in an enclosing 13236 // scope. They do implement this rule for friend functions. 13237 // 13238 // Does it matter that this should be by scope instead of by 13239 // semantic context? 13240 if (!Previous.empty() && TUK == TUK_Friend) { 13241 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13242 LookupResult::Filter F = Previous.makeFilter(); 13243 bool FriendSawTagOutsideEnclosingNamespace = false; 13244 while (F.hasNext()) { 13245 NamedDecl *ND = F.next(); 13246 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13247 if (DC->isFileContext() && 13248 !EnclosingNS->Encloses(ND->getDeclContext())) { 13249 if (getLangOpts().MSVCCompat) 13250 FriendSawTagOutsideEnclosingNamespace = true; 13251 else 13252 F.erase(); 13253 } 13254 } 13255 F.done(); 13256 13257 // Diagnose this MSVC extension in the easy case where lookup would have 13258 // unambiguously found something outside the enclosing namespace. 13259 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13260 NamedDecl *ND = Previous.getFoundDecl(); 13261 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13262 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13263 } 13264 } 13265 13266 // Note: there used to be some attempt at recovery here. 13267 if (Previous.isAmbiguous()) 13268 return nullptr; 13269 13270 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13271 // FIXME: This makes sure that we ignore the contexts associated 13272 // with C structs, unions, and enums when looking for a matching 13273 // tag declaration or definition. See the similar lookup tweak 13274 // in Sema::LookupName; is there a better way to deal with this? 13275 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13276 SearchDC = SearchDC->getParent(); 13277 } 13278 } 13279 13280 if (Previous.isSingleResult() && 13281 Previous.getFoundDecl()->isTemplateParameter()) { 13282 // Maybe we will complain about the shadowed template parameter. 13283 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13284 // Just pretend that we didn't see the previous declaration. 13285 Previous.clear(); 13286 } 13287 13288 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13289 DC->Equals(getStdNamespace())) { 13290 if (Name->isStr("bad_alloc")) { 13291 // This is a declaration of or a reference to "std::bad_alloc". 13292 isStdBadAlloc = true; 13293 13294 // If std::bad_alloc has been implicitly declared (but made invisible to 13295 // name lookup), fill in this implicit declaration as the previous 13296 // declaration, so that the declarations get chained appropriately. 13297 if (Previous.empty() && StdBadAlloc) 13298 Previous.addDecl(getStdBadAlloc()); 13299 } else if (Name->isStr("align_val_t")) { 13300 isStdAlignValT = true; 13301 if (Previous.empty() && StdAlignValT) 13302 Previous.addDecl(getStdAlignValT()); 13303 } 13304 } 13305 13306 // If we didn't find a previous declaration, and this is a reference 13307 // (or friend reference), move to the correct scope. In C++, we 13308 // also need to do a redeclaration lookup there, just in case 13309 // there's a shadow friend decl. 13310 if (Name && Previous.empty() && 13311 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13312 if (Invalid) goto CreateNewDecl; 13313 assert(SS.isEmpty()); 13314 13315 if (TUK == TUK_Reference) { 13316 // C++ [basic.scope.pdecl]p5: 13317 // -- for an elaborated-type-specifier of the form 13318 // 13319 // class-key identifier 13320 // 13321 // if the elaborated-type-specifier is used in the 13322 // decl-specifier-seq or parameter-declaration-clause of a 13323 // function defined in namespace scope, the identifier is 13324 // declared as a class-name in the namespace that contains 13325 // the declaration; otherwise, except as a friend 13326 // declaration, the identifier is declared in the smallest 13327 // non-class, non-function-prototype scope that contains the 13328 // declaration. 13329 // 13330 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13331 // C structs and unions. 13332 // 13333 // It is an error in C++ to declare (rather than define) an enum 13334 // type, including via an elaborated type specifier. We'll 13335 // diagnose that later; for now, declare the enum in the same 13336 // scope as we would have picked for any other tag type. 13337 // 13338 // GNU C also supports this behavior as part of its incomplete 13339 // enum types extension, while GNU C++ does not. 13340 // 13341 // Find the context where we'll be declaring the tag. 13342 // FIXME: We would like to maintain the current DeclContext as the 13343 // lexical context, 13344 SearchDC = getTagInjectionContext(SearchDC); 13345 13346 // Find the scope where we'll be declaring the tag. 13347 S = getTagInjectionScope(S, getLangOpts()); 13348 } else { 13349 assert(TUK == TUK_Friend); 13350 // C++ [namespace.memdef]p3: 13351 // If a friend declaration in a non-local class first declares a 13352 // class or function, the friend class or function is a member of 13353 // the innermost enclosing namespace. 13354 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13355 } 13356 13357 // In C++, we need to do a redeclaration lookup to properly 13358 // diagnose some problems. 13359 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13360 // hidden declaration so that we don't get ambiguity errors when using a 13361 // type declared by an elaborated-type-specifier. In C that is not correct 13362 // and we should instead merge compatible types found by lookup. 13363 if (getLangOpts().CPlusPlus) { 13364 Previous.setRedeclarationKind(ForRedeclaration); 13365 LookupQualifiedName(Previous, SearchDC); 13366 } else { 13367 Previous.setRedeclarationKind(ForRedeclaration); 13368 LookupName(Previous, S); 13369 } 13370 } 13371 13372 // If we have a known previous declaration to use, then use it. 13373 if (Previous.empty() && SkipBody && SkipBody->Previous) 13374 Previous.addDecl(SkipBody->Previous); 13375 13376 if (!Previous.empty()) { 13377 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13378 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13379 13380 // It's okay to have a tag decl in the same scope as a typedef 13381 // which hides a tag decl in the same scope. Finding this 13382 // insanity with a redeclaration lookup can only actually happen 13383 // in C++. 13384 // 13385 // This is also okay for elaborated-type-specifiers, which is 13386 // technically forbidden by the current standard but which is 13387 // okay according to the likely resolution of an open issue; 13388 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13389 if (getLangOpts().CPlusPlus) { 13390 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13391 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13392 TagDecl *Tag = TT->getDecl(); 13393 if (Tag->getDeclName() == Name && 13394 Tag->getDeclContext()->getRedeclContext() 13395 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13396 PrevDecl = Tag; 13397 Previous.clear(); 13398 Previous.addDecl(Tag); 13399 Previous.resolveKind(); 13400 } 13401 } 13402 } 13403 } 13404 13405 // If this is a redeclaration of a using shadow declaration, it must 13406 // declare a tag in the same context. In MSVC mode, we allow a 13407 // redefinition if either context is within the other. 13408 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13409 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13410 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13411 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13412 !(OldTag && isAcceptableTagRedeclContext( 13413 *this, OldTag->getDeclContext(), SearchDC))) { 13414 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13415 Diag(Shadow->getTargetDecl()->getLocation(), 13416 diag::note_using_decl_target); 13417 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13418 << 0; 13419 // Recover by ignoring the old declaration. 13420 Previous.clear(); 13421 goto CreateNewDecl; 13422 } 13423 } 13424 13425 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13426 // If this is a use of a previous tag, or if the tag is already declared 13427 // in the same scope (so that the definition/declaration completes or 13428 // rementions the tag), reuse the decl. 13429 if (TUK == TUK_Reference || TUK == TUK_Friend || 13430 isDeclInScope(DirectPrevDecl, SearchDC, S, 13431 SS.isNotEmpty() || isMemberSpecialization)) { 13432 // Make sure that this wasn't declared as an enum and now used as a 13433 // struct or something similar. 13434 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13435 TUK == TUK_Definition, KWLoc, 13436 Name)) { 13437 bool SafeToContinue 13438 = (PrevTagDecl->getTagKind() != TTK_Enum && 13439 Kind != TTK_Enum); 13440 if (SafeToContinue) 13441 Diag(KWLoc, diag::err_use_with_wrong_tag) 13442 << Name 13443 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13444 PrevTagDecl->getKindName()); 13445 else 13446 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13447 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13448 13449 if (SafeToContinue) 13450 Kind = PrevTagDecl->getTagKind(); 13451 else { 13452 // Recover by making this an anonymous redefinition. 13453 Name = nullptr; 13454 Previous.clear(); 13455 Invalid = true; 13456 } 13457 } 13458 13459 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13460 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13461 13462 // If this is an elaborated-type-specifier for a scoped enumeration, 13463 // the 'class' keyword is not necessary and not permitted. 13464 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13465 if (ScopedEnum) 13466 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13467 << PrevEnum->isScoped() 13468 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13469 return PrevTagDecl; 13470 } 13471 13472 QualType EnumUnderlyingTy; 13473 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13474 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13475 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13476 EnumUnderlyingTy = QualType(T, 0); 13477 13478 // All conflicts with previous declarations are recovered by 13479 // returning the previous declaration, unless this is a definition, 13480 // in which case we want the caller to bail out. 13481 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13482 ScopedEnum, EnumUnderlyingTy, 13483 EnumUnderlyingIsImplicit, PrevEnum)) 13484 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13485 } 13486 13487 // C++11 [class.mem]p1: 13488 // A member shall not be declared twice in the member-specification, 13489 // except that a nested class or member class template can be declared 13490 // and then later defined. 13491 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13492 S->isDeclScope(PrevDecl)) { 13493 Diag(NameLoc, diag::ext_member_redeclared); 13494 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13495 } 13496 13497 if (!Invalid) { 13498 // If this is a use, just return the declaration we found, unless 13499 // we have attributes. 13500 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13501 if (Attr) { 13502 // FIXME: Diagnose these attributes. For now, we create a new 13503 // declaration to hold them. 13504 } else if (TUK == TUK_Reference && 13505 (PrevTagDecl->getFriendObjectKind() == 13506 Decl::FOK_Undeclared || 13507 PrevDecl->getOwningModule() != getCurrentModule()) && 13508 SS.isEmpty()) { 13509 // This declaration is a reference to an existing entity, but 13510 // has different visibility from that entity: it either makes 13511 // a friend visible or it makes a type visible in a new module. 13512 // In either case, create a new declaration. We only do this if 13513 // the declaration would have meant the same thing if no prior 13514 // declaration were found, that is, if it was found in the same 13515 // scope where we would have injected a declaration. 13516 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13517 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13518 return PrevTagDecl; 13519 // This is in the injected scope, create a new declaration in 13520 // that scope. 13521 S = getTagInjectionScope(S, getLangOpts()); 13522 } else { 13523 return PrevTagDecl; 13524 } 13525 } 13526 13527 // Diagnose attempts to redefine a tag. 13528 if (TUK == TUK_Definition) { 13529 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13530 // If we're defining a specialization and the previous definition 13531 // is from an implicit instantiation, don't emit an error 13532 // here; we'll catch this in the general case below. 13533 bool IsExplicitSpecializationAfterInstantiation = false; 13534 if (isMemberSpecialization) { 13535 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13536 IsExplicitSpecializationAfterInstantiation = 13537 RD->getTemplateSpecializationKind() != 13538 TSK_ExplicitSpecialization; 13539 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13540 IsExplicitSpecializationAfterInstantiation = 13541 ED->getTemplateSpecializationKind() != 13542 TSK_ExplicitSpecialization; 13543 } 13544 13545 NamedDecl *Hidden = nullptr; 13546 if (SkipBody && getLangOpts().CPlusPlus && 13547 !hasVisibleDefinition(Def, &Hidden)) { 13548 // There is a definition of this tag, but it is not visible. We 13549 // explicitly make use of C++'s one definition rule here, and 13550 // assume that this definition is identical to the hidden one 13551 // we already have. Make the existing definition visible and 13552 // use it in place of this one. 13553 SkipBody->ShouldSkip = true; 13554 makeMergedDefinitionVisible(Hidden); 13555 return Def; 13556 } else if (!IsExplicitSpecializationAfterInstantiation) { 13557 // A redeclaration in function prototype scope in C isn't 13558 // visible elsewhere, so merely issue a warning. 13559 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13560 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13561 else 13562 Diag(NameLoc, diag::err_redefinition) << Name; 13563 notePreviousDefinition(Def, 13564 NameLoc.isValid() ? NameLoc : KWLoc); 13565 // If this is a redefinition, recover by making this 13566 // struct be anonymous, which will make any later 13567 // references get the previous definition. 13568 Name = nullptr; 13569 Previous.clear(); 13570 Invalid = true; 13571 } 13572 } else { 13573 // If the type is currently being defined, complain 13574 // about a nested redefinition. 13575 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13576 if (TD->isBeingDefined()) { 13577 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13578 Diag(PrevTagDecl->getLocation(), 13579 diag::note_previous_definition); 13580 Name = nullptr; 13581 Previous.clear(); 13582 Invalid = true; 13583 } 13584 } 13585 13586 // Okay, this is definition of a previously declared or referenced 13587 // tag. We're going to create a new Decl for it. 13588 } 13589 13590 // Okay, we're going to make a redeclaration. If this is some kind 13591 // of reference, make sure we build the redeclaration in the same DC 13592 // as the original, and ignore the current access specifier. 13593 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13594 SearchDC = PrevTagDecl->getDeclContext(); 13595 AS = AS_none; 13596 } 13597 } 13598 // If we get here we have (another) forward declaration or we 13599 // have a definition. Just create a new decl. 13600 13601 } else { 13602 // If we get here, this is a definition of a new tag type in a nested 13603 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13604 // new decl/type. We set PrevDecl to NULL so that the entities 13605 // have distinct types. 13606 Previous.clear(); 13607 } 13608 // If we get here, we're going to create a new Decl. If PrevDecl 13609 // is non-NULL, it's a definition of the tag declared by 13610 // PrevDecl. If it's NULL, we have a new definition. 13611 13612 // Otherwise, PrevDecl is not a tag, but was found with tag 13613 // lookup. This is only actually possible in C++, where a few 13614 // things like templates still live in the tag namespace. 13615 } else { 13616 // Use a better diagnostic if an elaborated-type-specifier 13617 // found the wrong kind of type on the first 13618 // (non-redeclaration) lookup. 13619 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13620 !Previous.isForRedeclaration()) { 13621 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13622 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13623 << Kind; 13624 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13625 Invalid = true; 13626 13627 // Otherwise, only diagnose if the declaration is in scope. 13628 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13629 SS.isNotEmpty() || isMemberSpecialization)) { 13630 // do nothing 13631 13632 // Diagnose implicit declarations introduced by elaborated types. 13633 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13634 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13635 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13636 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13637 Invalid = true; 13638 13639 // Otherwise it's a declaration. Call out a particularly common 13640 // case here. 13641 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13642 unsigned Kind = 0; 13643 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13644 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13645 << Name << Kind << TND->getUnderlyingType(); 13646 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13647 Invalid = true; 13648 13649 // Otherwise, diagnose. 13650 } else { 13651 // The tag name clashes with something else in the target scope, 13652 // issue an error and recover by making this tag be anonymous. 13653 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13654 notePreviousDefinition(PrevDecl, NameLoc); 13655 Name = nullptr; 13656 Invalid = true; 13657 } 13658 13659 // The existing declaration isn't relevant to us; we're in a 13660 // new scope, so clear out the previous declaration. 13661 Previous.clear(); 13662 } 13663 } 13664 13665 CreateNewDecl: 13666 13667 TagDecl *PrevDecl = nullptr; 13668 if (Previous.isSingleResult()) 13669 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13670 13671 // If there is an identifier, use the location of the identifier as the 13672 // location of the decl, otherwise use the location of the struct/union 13673 // keyword. 13674 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13675 13676 // Otherwise, create a new declaration. If there is a previous 13677 // declaration of the same entity, the two will be linked via 13678 // PrevDecl. 13679 TagDecl *New; 13680 13681 bool IsForwardReference = false; 13682 if (Kind == TTK_Enum) { 13683 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13684 // enum X { A, B, C } D; D should chain to X. 13685 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13686 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13687 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13688 13689 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13690 StdAlignValT = cast<EnumDecl>(New); 13691 13692 // If this is an undefined enum, warn. 13693 if (TUK != TUK_Definition && !Invalid) { 13694 TagDecl *Def; 13695 if (!EnumUnderlyingIsImplicit && 13696 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13697 cast<EnumDecl>(New)->isFixed()) { 13698 // C++0x: 7.2p2: opaque-enum-declaration. 13699 // Conflicts are diagnosed above. Do nothing. 13700 } 13701 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13702 Diag(Loc, diag::ext_forward_ref_enum_def) 13703 << New; 13704 Diag(Def->getLocation(), diag::note_previous_definition); 13705 } else { 13706 unsigned DiagID = diag::ext_forward_ref_enum; 13707 if (getLangOpts().MSVCCompat) 13708 DiagID = diag::ext_ms_forward_ref_enum; 13709 else if (getLangOpts().CPlusPlus) 13710 DiagID = diag::err_forward_ref_enum; 13711 Diag(Loc, DiagID); 13712 13713 // If this is a forward-declared reference to an enumeration, make a 13714 // note of it; we won't actually be introducing the declaration into 13715 // the declaration context. 13716 if (TUK == TUK_Reference) 13717 IsForwardReference = true; 13718 } 13719 } 13720 13721 if (EnumUnderlying) { 13722 EnumDecl *ED = cast<EnumDecl>(New); 13723 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13724 ED->setIntegerTypeSourceInfo(TI); 13725 else 13726 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13727 ED->setPromotionType(ED->getIntegerType()); 13728 } 13729 } else { 13730 // struct/union/class 13731 13732 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13733 // struct X { int A; } D; D should chain to X. 13734 if (getLangOpts().CPlusPlus) { 13735 // FIXME: Look for a way to use RecordDecl for simple structs. 13736 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13737 cast_or_null<CXXRecordDecl>(PrevDecl)); 13738 13739 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13740 StdBadAlloc = cast<CXXRecordDecl>(New); 13741 } else 13742 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13743 cast_or_null<RecordDecl>(PrevDecl)); 13744 } 13745 13746 // C++11 [dcl.type]p3: 13747 // A type-specifier-seq shall not define a class or enumeration [...]. 13748 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13749 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13750 << Context.getTagDeclType(New); 13751 Invalid = true; 13752 } 13753 13754 // Maybe add qualifier info. 13755 if (SS.isNotEmpty()) { 13756 if (SS.isSet()) { 13757 // If this is either a declaration or a definition, check the 13758 // nested-name-specifier against the current context. We don't do this 13759 // for explicit specializations, because they have similar checking 13760 // (with more specific diagnostics) in the call to 13761 // CheckMemberSpecialization, below. 13762 if (!isMemberSpecialization && 13763 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13764 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13765 Invalid = true; 13766 13767 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13768 if (TemplateParameterLists.size() > 0) { 13769 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13770 } 13771 } 13772 else 13773 Invalid = true; 13774 } 13775 13776 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13777 // Add alignment attributes if necessary; these attributes are checked when 13778 // the ASTContext lays out the structure. 13779 // 13780 // It is important for implementing the correct semantics that this 13781 // happen here (in act on tag decl). The #pragma pack stack is 13782 // maintained as a result of parser callbacks which can occur at 13783 // many points during the parsing of a struct declaration (because 13784 // the #pragma tokens are effectively skipped over during the 13785 // parsing of the struct). 13786 if (TUK == TUK_Definition) { 13787 AddAlignmentAttributesForRecord(RD); 13788 AddMsStructLayoutForRecord(RD); 13789 } 13790 } 13791 13792 if (ModulePrivateLoc.isValid()) { 13793 if (isMemberSpecialization) 13794 Diag(New->getLocation(), diag::err_module_private_specialization) 13795 << 2 13796 << FixItHint::CreateRemoval(ModulePrivateLoc); 13797 // __module_private__ does not apply to local classes. However, we only 13798 // diagnose this as an error when the declaration specifiers are 13799 // freestanding. Here, we just ignore the __module_private__. 13800 else if (!SearchDC->isFunctionOrMethod()) 13801 New->setModulePrivate(); 13802 } 13803 13804 // If this is a specialization of a member class (of a class template), 13805 // check the specialization. 13806 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 13807 Invalid = true; 13808 13809 // If we're declaring or defining a tag in function prototype scope in C, 13810 // note that this type can only be used within the function and add it to 13811 // the list of decls to inject into the function definition scope. 13812 if ((Name || Kind == TTK_Enum) && 13813 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13814 if (getLangOpts().CPlusPlus) { 13815 // C++ [dcl.fct]p6: 13816 // Types shall not be defined in return or parameter types. 13817 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13818 Diag(Loc, diag::err_type_defined_in_param_type) 13819 << Name; 13820 Invalid = true; 13821 } 13822 } else if (!PrevDecl) { 13823 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13824 } 13825 } 13826 13827 if (Invalid) 13828 New->setInvalidDecl(); 13829 13830 // Set the lexical context. If the tag has a C++ scope specifier, the 13831 // lexical context will be different from the semantic context. 13832 New->setLexicalDeclContext(CurContext); 13833 13834 // Mark this as a friend decl if applicable. 13835 // In Microsoft mode, a friend declaration also acts as a forward 13836 // declaration so we always pass true to setObjectOfFriendDecl to make 13837 // the tag name visible. 13838 if (TUK == TUK_Friend) 13839 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13840 13841 // Set the access specifier. 13842 if (!Invalid && SearchDC->isRecord()) 13843 SetMemberAccessSpecifier(New, PrevDecl, AS); 13844 13845 if (TUK == TUK_Definition) 13846 New->startDefinition(); 13847 13848 if (Attr) 13849 ProcessDeclAttributeList(S, New, Attr); 13850 AddPragmaAttributes(S, New); 13851 13852 // If this has an identifier, add it to the scope stack. 13853 if (TUK == TUK_Friend) { 13854 // We might be replacing an existing declaration in the lookup tables; 13855 // if so, borrow its access specifier. 13856 if (PrevDecl) 13857 New->setAccess(PrevDecl->getAccess()); 13858 13859 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13860 DC->makeDeclVisibleInContext(New); 13861 if (Name) // can be null along some error paths 13862 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13863 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13864 } else if (Name) { 13865 S = getNonFieldDeclScope(S); 13866 PushOnScopeChains(New, S, !IsForwardReference); 13867 if (IsForwardReference) 13868 SearchDC->makeDeclVisibleInContext(New); 13869 } else { 13870 CurContext->addDecl(New); 13871 } 13872 13873 // If this is the C FILE type, notify the AST context. 13874 if (IdentifierInfo *II = New->getIdentifier()) 13875 if (!New->isInvalidDecl() && 13876 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13877 II->isStr("FILE")) 13878 Context.setFILEDecl(New); 13879 13880 if (PrevDecl) 13881 mergeDeclAttributes(New, PrevDecl); 13882 13883 // If there's a #pragma GCC visibility in scope, set the visibility of this 13884 // record. 13885 AddPushedVisibilityAttribute(New); 13886 13887 if (isMemberSpecialization && !New->isInvalidDecl()) 13888 CompleteMemberSpecialization(New, Previous); 13889 13890 OwnedDecl = true; 13891 // In C++, don't return an invalid declaration. We can't recover well from 13892 // the cases where we make the type anonymous. 13893 if (Invalid && getLangOpts().CPlusPlus) { 13894 if (New->isBeingDefined()) 13895 if (auto RD = dyn_cast<RecordDecl>(New)) 13896 RD->completeDefinition(); 13897 return nullptr; 13898 } else { 13899 return New; 13900 } 13901 } 13902 13903 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13904 AdjustDeclIfTemplate(TagD); 13905 TagDecl *Tag = cast<TagDecl>(TagD); 13906 13907 // Enter the tag context. 13908 PushDeclContext(S, Tag); 13909 13910 ActOnDocumentableDecl(TagD); 13911 13912 // If there's a #pragma GCC visibility in scope, set the visibility of this 13913 // record. 13914 AddPushedVisibilityAttribute(Tag); 13915 } 13916 13917 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13918 assert(isa<ObjCContainerDecl>(IDecl) && 13919 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13920 DeclContext *OCD = cast<DeclContext>(IDecl); 13921 assert(getContainingDC(OCD) == CurContext && 13922 "The next DeclContext should be lexically contained in the current one."); 13923 CurContext = OCD; 13924 return IDecl; 13925 } 13926 13927 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13928 SourceLocation FinalLoc, 13929 bool IsFinalSpelledSealed, 13930 SourceLocation LBraceLoc) { 13931 AdjustDeclIfTemplate(TagD); 13932 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13933 13934 FieldCollector->StartClass(); 13935 13936 if (!Record->getIdentifier()) 13937 return; 13938 13939 if (FinalLoc.isValid()) 13940 Record->addAttr(new (Context) 13941 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13942 13943 // C++ [class]p2: 13944 // [...] The class-name is also inserted into the scope of the 13945 // class itself; this is known as the injected-class-name. For 13946 // purposes of access checking, the injected-class-name is treated 13947 // as if it were a public member name. 13948 CXXRecordDecl *InjectedClassName 13949 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13950 Record->getLocStart(), Record->getLocation(), 13951 Record->getIdentifier(), 13952 /*PrevDecl=*/nullptr, 13953 /*DelayTypeCreation=*/true); 13954 Context.getTypeDeclType(InjectedClassName, Record); 13955 InjectedClassName->setImplicit(); 13956 InjectedClassName->setAccess(AS_public); 13957 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13958 InjectedClassName->setDescribedClassTemplate(Template); 13959 PushOnScopeChains(InjectedClassName, S); 13960 assert(InjectedClassName->isInjectedClassName() && 13961 "Broken injected-class-name"); 13962 } 13963 13964 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13965 SourceRange BraceRange) { 13966 AdjustDeclIfTemplate(TagD); 13967 TagDecl *Tag = cast<TagDecl>(TagD); 13968 Tag->setBraceRange(BraceRange); 13969 13970 // Make sure we "complete" the definition even it is invalid. 13971 if (Tag->isBeingDefined()) { 13972 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13973 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13974 RD->completeDefinition(); 13975 } 13976 13977 if (isa<CXXRecordDecl>(Tag)) { 13978 FieldCollector->FinishClass(); 13979 } 13980 13981 // Exit this scope of this tag's definition. 13982 PopDeclContext(); 13983 13984 if (getCurLexicalContext()->isObjCContainer() && 13985 Tag->getDeclContext()->isFileContext()) 13986 Tag->setTopLevelDeclInObjCContainer(); 13987 13988 // Notify the consumer that we've defined a tag. 13989 if (!Tag->isInvalidDecl()) 13990 Consumer.HandleTagDeclDefinition(Tag); 13991 } 13992 13993 void Sema::ActOnObjCContainerFinishDefinition() { 13994 // Exit this scope of this interface definition. 13995 PopDeclContext(); 13996 } 13997 13998 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13999 assert(DC == CurContext && "Mismatch of container contexts"); 14000 OriginalLexicalContext = DC; 14001 ActOnObjCContainerFinishDefinition(); 14002 } 14003 14004 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14005 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14006 OriginalLexicalContext = nullptr; 14007 } 14008 14009 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14010 AdjustDeclIfTemplate(TagD); 14011 TagDecl *Tag = cast<TagDecl>(TagD); 14012 Tag->setInvalidDecl(); 14013 14014 // Make sure we "complete" the definition even it is invalid. 14015 if (Tag->isBeingDefined()) { 14016 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14017 RD->completeDefinition(); 14018 } 14019 14020 // We're undoing ActOnTagStartDefinition here, not 14021 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14022 // the FieldCollector. 14023 14024 PopDeclContext(); 14025 } 14026 14027 // Note that FieldName may be null for anonymous bitfields. 14028 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14029 IdentifierInfo *FieldName, 14030 QualType FieldTy, bool IsMsStruct, 14031 Expr *BitWidth, bool *ZeroWidth) { 14032 // Default to true; that shouldn't confuse checks for emptiness 14033 if (ZeroWidth) 14034 *ZeroWidth = true; 14035 14036 // C99 6.7.2.1p4 - verify the field type. 14037 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14038 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14039 // Handle incomplete types with specific error. 14040 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14041 return ExprError(); 14042 if (FieldName) 14043 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14044 << FieldName << FieldTy << BitWidth->getSourceRange(); 14045 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14046 << FieldTy << BitWidth->getSourceRange(); 14047 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14048 UPPC_BitFieldWidth)) 14049 return ExprError(); 14050 14051 // If the bit-width is type- or value-dependent, don't try to check 14052 // it now. 14053 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14054 return BitWidth; 14055 14056 llvm::APSInt Value; 14057 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14058 if (ICE.isInvalid()) 14059 return ICE; 14060 BitWidth = ICE.get(); 14061 14062 if (Value != 0 && ZeroWidth) 14063 *ZeroWidth = false; 14064 14065 // Zero-width bitfield is ok for anonymous field. 14066 if (Value == 0 && FieldName) 14067 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14068 14069 if (Value.isSigned() && Value.isNegative()) { 14070 if (FieldName) 14071 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14072 << FieldName << Value.toString(10); 14073 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14074 << Value.toString(10); 14075 } 14076 14077 if (!FieldTy->isDependentType()) { 14078 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14079 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14080 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14081 14082 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14083 // ABI. 14084 bool CStdConstraintViolation = 14085 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14086 bool MSBitfieldViolation = 14087 Value.ugt(TypeStorageSize) && 14088 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14089 if (CStdConstraintViolation || MSBitfieldViolation) { 14090 unsigned DiagWidth = 14091 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14092 if (FieldName) 14093 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14094 << FieldName << (unsigned)Value.getZExtValue() 14095 << !CStdConstraintViolation << DiagWidth; 14096 14097 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14098 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14099 << DiagWidth; 14100 } 14101 14102 // Warn on types where the user might conceivably expect to get all 14103 // specified bits as value bits: that's all integral types other than 14104 // 'bool'. 14105 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14106 if (FieldName) 14107 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14108 << FieldName << (unsigned)Value.getZExtValue() 14109 << (unsigned)TypeWidth; 14110 else 14111 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14112 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14113 } 14114 } 14115 14116 return BitWidth; 14117 } 14118 14119 /// ActOnField - Each field of a C struct/union is passed into this in order 14120 /// to create a FieldDecl object for it. 14121 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14122 Declarator &D, Expr *BitfieldWidth) { 14123 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14124 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14125 /*InitStyle=*/ICIS_NoInit, AS_public); 14126 return Res; 14127 } 14128 14129 /// HandleField - Analyze a field of a C struct or a C++ data member. 14130 /// 14131 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14132 SourceLocation DeclStart, 14133 Declarator &D, Expr *BitWidth, 14134 InClassInitStyle InitStyle, 14135 AccessSpecifier AS) { 14136 if (D.isDecompositionDeclarator()) { 14137 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14138 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14139 << Decomp.getSourceRange(); 14140 return nullptr; 14141 } 14142 14143 IdentifierInfo *II = D.getIdentifier(); 14144 SourceLocation Loc = DeclStart; 14145 if (II) Loc = D.getIdentifierLoc(); 14146 14147 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14148 QualType T = TInfo->getType(); 14149 if (getLangOpts().CPlusPlus) { 14150 CheckExtraCXXDefaultArguments(D); 14151 14152 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14153 UPPC_DataMemberType)) { 14154 D.setInvalidType(); 14155 T = Context.IntTy; 14156 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14157 } 14158 } 14159 14160 // TR 18037 does not allow fields to be declared with address spaces. 14161 if (T.getQualifiers().hasAddressSpace()) { 14162 Diag(Loc, diag::err_field_with_address_space); 14163 D.setInvalidType(); 14164 } 14165 14166 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14167 // used as structure or union field: image, sampler, event or block types. 14168 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14169 T->isSamplerT() || T->isBlockPointerType())) { 14170 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14171 D.setInvalidType(); 14172 } 14173 14174 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14175 14176 if (D.getDeclSpec().isInlineSpecified()) 14177 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14178 << getLangOpts().CPlusPlus1z; 14179 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14180 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14181 diag::err_invalid_thread) 14182 << DeclSpec::getSpecifierName(TSCS); 14183 14184 // Check to see if this name was declared as a member previously 14185 NamedDecl *PrevDecl = nullptr; 14186 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14187 LookupName(Previous, S); 14188 switch (Previous.getResultKind()) { 14189 case LookupResult::Found: 14190 case LookupResult::FoundUnresolvedValue: 14191 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14192 break; 14193 14194 case LookupResult::FoundOverloaded: 14195 PrevDecl = Previous.getRepresentativeDecl(); 14196 break; 14197 14198 case LookupResult::NotFound: 14199 case LookupResult::NotFoundInCurrentInstantiation: 14200 case LookupResult::Ambiguous: 14201 break; 14202 } 14203 Previous.suppressDiagnostics(); 14204 14205 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14206 // Maybe we will complain about the shadowed template parameter. 14207 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14208 // Just pretend that we didn't see the previous declaration. 14209 PrevDecl = nullptr; 14210 } 14211 14212 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14213 PrevDecl = nullptr; 14214 14215 bool Mutable 14216 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14217 SourceLocation TSSL = D.getLocStart(); 14218 FieldDecl *NewFD 14219 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14220 TSSL, AS, PrevDecl, &D); 14221 14222 if (NewFD->isInvalidDecl()) 14223 Record->setInvalidDecl(); 14224 14225 if (D.getDeclSpec().isModulePrivateSpecified()) 14226 NewFD->setModulePrivate(); 14227 14228 if (NewFD->isInvalidDecl() && PrevDecl) { 14229 // Don't introduce NewFD into scope; there's already something 14230 // with the same name in the same scope. 14231 } else if (II) { 14232 PushOnScopeChains(NewFD, S); 14233 } else 14234 Record->addDecl(NewFD); 14235 14236 return NewFD; 14237 } 14238 14239 /// \brief Build a new FieldDecl and check its well-formedness. 14240 /// 14241 /// This routine builds a new FieldDecl given the fields name, type, 14242 /// record, etc. \p PrevDecl should refer to any previous declaration 14243 /// with the same name and in the same scope as the field to be 14244 /// created. 14245 /// 14246 /// \returns a new FieldDecl. 14247 /// 14248 /// \todo The Declarator argument is a hack. It will be removed once 14249 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14250 TypeSourceInfo *TInfo, 14251 RecordDecl *Record, SourceLocation Loc, 14252 bool Mutable, Expr *BitWidth, 14253 InClassInitStyle InitStyle, 14254 SourceLocation TSSL, 14255 AccessSpecifier AS, NamedDecl *PrevDecl, 14256 Declarator *D) { 14257 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14258 bool InvalidDecl = false; 14259 if (D) InvalidDecl = D->isInvalidType(); 14260 14261 // If we receive a broken type, recover by assuming 'int' and 14262 // marking this declaration as invalid. 14263 if (T.isNull()) { 14264 InvalidDecl = true; 14265 T = Context.IntTy; 14266 } 14267 14268 QualType EltTy = Context.getBaseElementType(T); 14269 if (!EltTy->isDependentType()) { 14270 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14271 // Fields of incomplete type force their record to be invalid. 14272 Record->setInvalidDecl(); 14273 InvalidDecl = true; 14274 } else { 14275 NamedDecl *Def; 14276 EltTy->isIncompleteType(&Def); 14277 if (Def && Def->isInvalidDecl()) { 14278 Record->setInvalidDecl(); 14279 InvalidDecl = true; 14280 } 14281 } 14282 } 14283 14284 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14285 if (BitWidth && getLangOpts().OpenCL) { 14286 Diag(Loc, diag::err_opencl_bitfields); 14287 InvalidDecl = true; 14288 } 14289 14290 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14291 // than a variably modified type. 14292 if (!InvalidDecl && T->isVariablyModifiedType()) { 14293 bool SizeIsNegative; 14294 llvm::APSInt Oversized; 14295 14296 TypeSourceInfo *FixedTInfo = 14297 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14298 SizeIsNegative, 14299 Oversized); 14300 if (FixedTInfo) { 14301 Diag(Loc, diag::warn_illegal_constant_array_size); 14302 TInfo = FixedTInfo; 14303 T = FixedTInfo->getType(); 14304 } else { 14305 if (SizeIsNegative) 14306 Diag(Loc, diag::err_typecheck_negative_array_size); 14307 else if (Oversized.getBoolValue()) 14308 Diag(Loc, diag::err_array_too_large) 14309 << Oversized.toString(10); 14310 else 14311 Diag(Loc, diag::err_typecheck_field_variable_size); 14312 InvalidDecl = true; 14313 } 14314 } 14315 14316 // Fields can not have abstract class types 14317 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14318 diag::err_abstract_type_in_decl, 14319 AbstractFieldType)) 14320 InvalidDecl = true; 14321 14322 bool ZeroWidth = false; 14323 if (InvalidDecl) 14324 BitWidth = nullptr; 14325 // If this is declared as a bit-field, check the bit-field. 14326 if (BitWidth) { 14327 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14328 &ZeroWidth).get(); 14329 if (!BitWidth) { 14330 InvalidDecl = true; 14331 BitWidth = nullptr; 14332 ZeroWidth = false; 14333 } 14334 } 14335 14336 // Check that 'mutable' is consistent with the type of the declaration. 14337 if (!InvalidDecl && Mutable) { 14338 unsigned DiagID = 0; 14339 if (T->isReferenceType()) 14340 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14341 : diag::err_mutable_reference; 14342 else if (T.isConstQualified()) 14343 DiagID = diag::err_mutable_const; 14344 14345 if (DiagID) { 14346 SourceLocation ErrLoc = Loc; 14347 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14348 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14349 Diag(ErrLoc, DiagID); 14350 if (DiagID != diag::ext_mutable_reference) { 14351 Mutable = false; 14352 InvalidDecl = true; 14353 } 14354 } 14355 } 14356 14357 // C++11 [class.union]p8 (DR1460): 14358 // At most one variant member of a union may have a 14359 // brace-or-equal-initializer. 14360 if (InitStyle != ICIS_NoInit) 14361 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14362 14363 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14364 BitWidth, Mutable, InitStyle); 14365 if (InvalidDecl) 14366 NewFD->setInvalidDecl(); 14367 14368 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14369 Diag(Loc, diag::err_duplicate_member) << II; 14370 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14371 NewFD->setInvalidDecl(); 14372 } 14373 14374 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14375 if (Record->isUnion()) { 14376 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14377 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14378 if (RDecl->getDefinition()) { 14379 // C++ [class.union]p1: An object of a class with a non-trivial 14380 // constructor, a non-trivial copy constructor, a non-trivial 14381 // destructor, or a non-trivial copy assignment operator 14382 // cannot be a member of a union, nor can an array of such 14383 // objects. 14384 if (CheckNontrivialField(NewFD)) 14385 NewFD->setInvalidDecl(); 14386 } 14387 } 14388 14389 // C++ [class.union]p1: If a union contains a member of reference type, 14390 // the program is ill-formed, except when compiling with MSVC extensions 14391 // enabled. 14392 if (EltTy->isReferenceType()) { 14393 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14394 diag::ext_union_member_of_reference_type : 14395 diag::err_union_member_of_reference_type) 14396 << NewFD->getDeclName() << EltTy; 14397 if (!getLangOpts().MicrosoftExt) 14398 NewFD->setInvalidDecl(); 14399 } 14400 } 14401 } 14402 14403 // FIXME: We need to pass in the attributes given an AST 14404 // representation, not a parser representation. 14405 if (D) { 14406 // FIXME: The current scope is almost... but not entirely... correct here. 14407 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14408 14409 if (NewFD->hasAttrs()) 14410 CheckAlignasUnderalignment(NewFD); 14411 } 14412 14413 // In auto-retain/release, infer strong retension for fields of 14414 // retainable type. 14415 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14416 NewFD->setInvalidDecl(); 14417 14418 if (T.isObjCGCWeak()) 14419 Diag(Loc, diag::warn_attribute_weak_on_field); 14420 14421 NewFD->setAccess(AS); 14422 return NewFD; 14423 } 14424 14425 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14426 assert(FD); 14427 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14428 14429 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14430 return false; 14431 14432 QualType EltTy = Context.getBaseElementType(FD->getType()); 14433 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14434 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14435 if (RDecl->getDefinition()) { 14436 // We check for copy constructors before constructors 14437 // because otherwise we'll never get complaints about 14438 // copy constructors. 14439 14440 CXXSpecialMember member = CXXInvalid; 14441 // We're required to check for any non-trivial constructors. Since the 14442 // implicit default constructor is suppressed if there are any 14443 // user-declared constructors, we just need to check that there is a 14444 // trivial default constructor and a trivial copy constructor. (We don't 14445 // worry about move constructors here, since this is a C++98 check.) 14446 if (RDecl->hasNonTrivialCopyConstructor()) 14447 member = CXXCopyConstructor; 14448 else if (!RDecl->hasTrivialDefaultConstructor()) 14449 member = CXXDefaultConstructor; 14450 else if (RDecl->hasNonTrivialCopyAssignment()) 14451 member = CXXCopyAssignment; 14452 else if (RDecl->hasNonTrivialDestructor()) 14453 member = CXXDestructor; 14454 14455 if (member != CXXInvalid) { 14456 if (!getLangOpts().CPlusPlus11 && 14457 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14458 // Objective-C++ ARC: it is an error to have a non-trivial field of 14459 // a union. However, system headers in Objective-C programs 14460 // occasionally have Objective-C lifetime objects within unions, 14461 // and rather than cause the program to fail, we make those 14462 // members unavailable. 14463 SourceLocation Loc = FD->getLocation(); 14464 if (getSourceManager().isInSystemHeader(Loc)) { 14465 if (!FD->hasAttr<UnavailableAttr>()) 14466 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14467 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14468 return false; 14469 } 14470 } 14471 14472 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14473 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14474 diag::err_illegal_union_or_anon_struct_member) 14475 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14476 DiagnoseNontrivial(RDecl, member); 14477 return !getLangOpts().CPlusPlus11; 14478 } 14479 } 14480 } 14481 14482 return false; 14483 } 14484 14485 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14486 /// AST enum value. 14487 static ObjCIvarDecl::AccessControl 14488 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14489 switch (ivarVisibility) { 14490 default: llvm_unreachable("Unknown visitibility kind"); 14491 case tok::objc_private: return ObjCIvarDecl::Private; 14492 case tok::objc_public: return ObjCIvarDecl::Public; 14493 case tok::objc_protected: return ObjCIvarDecl::Protected; 14494 case tok::objc_package: return ObjCIvarDecl::Package; 14495 } 14496 } 14497 14498 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14499 /// in order to create an IvarDecl object for it. 14500 Decl *Sema::ActOnIvar(Scope *S, 14501 SourceLocation DeclStart, 14502 Declarator &D, Expr *BitfieldWidth, 14503 tok::ObjCKeywordKind Visibility) { 14504 14505 IdentifierInfo *II = D.getIdentifier(); 14506 Expr *BitWidth = (Expr*)BitfieldWidth; 14507 SourceLocation Loc = DeclStart; 14508 if (II) Loc = D.getIdentifierLoc(); 14509 14510 // FIXME: Unnamed fields can be handled in various different ways, for 14511 // example, unnamed unions inject all members into the struct namespace! 14512 14513 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14514 QualType T = TInfo->getType(); 14515 14516 if (BitWidth) { 14517 // 6.7.2.1p3, 6.7.2.1p4 14518 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14519 if (!BitWidth) 14520 D.setInvalidType(); 14521 } else { 14522 // Not a bitfield. 14523 14524 // validate II. 14525 14526 } 14527 if (T->isReferenceType()) { 14528 Diag(Loc, diag::err_ivar_reference_type); 14529 D.setInvalidType(); 14530 } 14531 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14532 // than a variably modified type. 14533 else if (T->isVariablyModifiedType()) { 14534 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14535 D.setInvalidType(); 14536 } 14537 14538 // Get the visibility (access control) for this ivar. 14539 ObjCIvarDecl::AccessControl ac = 14540 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14541 : ObjCIvarDecl::None; 14542 // Must set ivar's DeclContext to its enclosing interface. 14543 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14544 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14545 return nullptr; 14546 ObjCContainerDecl *EnclosingContext; 14547 if (ObjCImplementationDecl *IMPDecl = 14548 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14549 if (LangOpts.ObjCRuntime.isFragile()) { 14550 // Case of ivar declared in an implementation. Context is that of its class. 14551 EnclosingContext = IMPDecl->getClassInterface(); 14552 assert(EnclosingContext && "Implementation has no class interface!"); 14553 } 14554 else 14555 EnclosingContext = EnclosingDecl; 14556 } else { 14557 if (ObjCCategoryDecl *CDecl = 14558 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14559 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14560 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14561 return nullptr; 14562 } 14563 } 14564 EnclosingContext = EnclosingDecl; 14565 } 14566 14567 // Construct the decl. 14568 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14569 DeclStart, Loc, II, T, 14570 TInfo, ac, (Expr *)BitfieldWidth); 14571 14572 if (II) { 14573 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14574 ForRedeclaration); 14575 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14576 && !isa<TagDecl>(PrevDecl)) { 14577 Diag(Loc, diag::err_duplicate_member) << II; 14578 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14579 NewID->setInvalidDecl(); 14580 } 14581 } 14582 14583 // Process attributes attached to the ivar. 14584 ProcessDeclAttributes(S, NewID, D); 14585 14586 if (D.isInvalidType()) 14587 NewID->setInvalidDecl(); 14588 14589 // In ARC, infer 'retaining' for ivars of retainable type. 14590 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14591 NewID->setInvalidDecl(); 14592 14593 if (D.getDeclSpec().isModulePrivateSpecified()) 14594 NewID->setModulePrivate(); 14595 14596 if (II) { 14597 // FIXME: When interfaces are DeclContexts, we'll need to add 14598 // these to the interface. 14599 S->AddDecl(NewID); 14600 IdResolver.AddDecl(NewID); 14601 } 14602 14603 if (LangOpts.ObjCRuntime.isNonFragile() && 14604 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14605 Diag(Loc, diag::warn_ivars_in_interface); 14606 14607 return NewID; 14608 } 14609 14610 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14611 /// class and class extensions. For every class \@interface and class 14612 /// extension \@interface, if the last ivar is a bitfield of any type, 14613 /// then add an implicit `char :0` ivar to the end of that interface. 14614 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14615 SmallVectorImpl<Decl *> &AllIvarDecls) { 14616 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14617 return; 14618 14619 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14620 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14621 14622 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14623 return; 14624 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14625 if (!ID) { 14626 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14627 if (!CD->IsClassExtension()) 14628 return; 14629 } 14630 // No need to add this to end of @implementation. 14631 else 14632 return; 14633 } 14634 // All conditions are met. Add a new bitfield to the tail end of ivars. 14635 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14636 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14637 14638 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14639 DeclLoc, DeclLoc, nullptr, 14640 Context.CharTy, 14641 Context.getTrivialTypeSourceInfo(Context.CharTy, 14642 DeclLoc), 14643 ObjCIvarDecl::Private, BW, 14644 true); 14645 AllIvarDecls.push_back(Ivar); 14646 } 14647 14648 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14649 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14650 SourceLocation RBrac, AttributeList *Attr) { 14651 assert(EnclosingDecl && "missing record or interface decl"); 14652 14653 // If this is an Objective-C @implementation or category and we have 14654 // new fields here we should reset the layout of the interface since 14655 // it will now change. 14656 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14657 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14658 switch (DC->getKind()) { 14659 default: break; 14660 case Decl::ObjCCategory: 14661 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14662 break; 14663 case Decl::ObjCImplementation: 14664 Context. 14665 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14666 break; 14667 } 14668 } 14669 14670 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14671 14672 // Start counting up the number of named members; make sure to include 14673 // members of anonymous structs and unions in the total. 14674 unsigned NumNamedMembers = 0; 14675 if (Record) { 14676 for (const auto *I : Record->decls()) { 14677 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14678 if (IFD->getDeclName()) 14679 ++NumNamedMembers; 14680 } 14681 } 14682 14683 // Verify that all the fields are okay. 14684 SmallVector<FieldDecl*, 32> RecFields; 14685 14686 bool ObjCFieldLifetimeErrReported = false; 14687 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14688 i != end; ++i) { 14689 FieldDecl *FD = cast<FieldDecl>(*i); 14690 14691 // Get the type for the field. 14692 const Type *FDTy = FD->getType().getTypePtr(); 14693 14694 if (!FD->isAnonymousStructOrUnion()) { 14695 // Remember all fields written by the user. 14696 RecFields.push_back(FD); 14697 } 14698 14699 // If the field is already invalid for some reason, don't emit more 14700 // diagnostics about it. 14701 if (FD->isInvalidDecl()) { 14702 EnclosingDecl->setInvalidDecl(); 14703 continue; 14704 } 14705 14706 // C99 6.7.2.1p2: 14707 // A structure or union shall not contain a member with 14708 // incomplete or function type (hence, a structure shall not 14709 // contain an instance of itself, but may contain a pointer to 14710 // an instance of itself), except that the last member of a 14711 // structure with more than one named member may have incomplete 14712 // array type; such a structure (and any union containing, 14713 // possibly recursively, a member that is such a structure) 14714 // shall not be a member of a structure or an element of an 14715 // array. 14716 if (FDTy->isFunctionType()) { 14717 // Field declared as a function. 14718 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14719 << FD->getDeclName(); 14720 FD->setInvalidDecl(); 14721 EnclosingDecl->setInvalidDecl(); 14722 continue; 14723 } else if (FDTy->isIncompleteArrayType() && Record && 14724 ((i + 1 == Fields.end() && !Record->isUnion()) || 14725 ((getLangOpts().MicrosoftExt || 14726 getLangOpts().CPlusPlus) && 14727 (i + 1 == Fields.end() || Record->isUnion())))) { 14728 // Flexible array member. 14729 // Microsoft and g++ is more permissive regarding flexible array. 14730 // It will accept flexible array in union and also 14731 // as the sole element of a struct/class. 14732 unsigned DiagID = 0; 14733 if (Record->isUnion()) 14734 DiagID = getLangOpts().MicrosoftExt 14735 ? diag::ext_flexible_array_union_ms 14736 : getLangOpts().CPlusPlus 14737 ? diag::ext_flexible_array_union_gnu 14738 : diag::err_flexible_array_union; 14739 else if (NumNamedMembers < 1) 14740 DiagID = getLangOpts().MicrosoftExt 14741 ? diag::ext_flexible_array_empty_aggregate_ms 14742 : getLangOpts().CPlusPlus 14743 ? diag::ext_flexible_array_empty_aggregate_gnu 14744 : diag::err_flexible_array_empty_aggregate; 14745 14746 if (DiagID) 14747 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14748 << Record->getTagKind(); 14749 // While the layout of types that contain virtual bases is not specified 14750 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14751 // virtual bases after the derived members. This would make a flexible 14752 // array member declared at the end of an object not adjacent to the end 14753 // of the type. 14754 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14755 if (RD->getNumVBases() != 0) 14756 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14757 << FD->getDeclName() << Record->getTagKind(); 14758 if (!getLangOpts().C99) 14759 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14760 << FD->getDeclName() << Record->getTagKind(); 14761 14762 // If the element type has a non-trivial destructor, we would not 14763 // implicitly destroy the elements, so disallow it for now. 14764 // 14765 // FIXME: GCC allows this. We should probably either implicitly delete 14766 // the destructor of the containing class, or just allow this. 14767 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14768 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14769 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14770 << FD->getDeclName() << FD->getType(); 14771 FD->setInvalidDecl(); 14772 EnclosingDecl->setInvalidDecl(); 14773 continue; 14774 } 14775 // Okay, we have a legal flexible array member at the end of the struct. 14776 Record->setHasFlexibleArrayMember(true); 14777 } else if (!FDTy->isDependentType() && 14778 RequireCompleteType(FD->getLocation(), FD->getType(), 14779 diag::err_field_incomplete)) { 14780 // Incomplete type 14781 FD->setInvalidDecl(); 14782 EnclosingDecl->setInvalidDecl(); 14783 continue; 14784 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14785 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14786 // A type which contains a flexible array member is considered to be a 14787 // flexible array member. 14788 Record->setHasFlexibleArrayMember(true); 14789 if (!Record->isUnion()) { 14790 // If this is a struct/class and this is not the last element, reject 14791 // it. Note that GCC supports variable sized arrays in the middle of 14792 // structures. 14793 if (i + 1 != Fields.end()) 14794 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14795 << FD->getDeclName() << FD->getType(); 14796 else { 14797 // We support flexible arrays at the end of structs in 14798 // other structs as an extension. 14799 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14800 << FD->getDeclName(); 14801 } 14802 } 14803 } 14804 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14805 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14806 diag::err_abstract_type_in_decl, 14807 AbstractIvarType)) { 14808 // Ivars can not have abstract class types 14809 FD->setInvalidDecl(); 14810 } 14811 if (Record && FDTTy->getDecl()->hasObjectMember()) 14812 Record->setHasObjectMember(true); 14813 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14814 Record->setHasVolatileMember(true); 14815 } else if (FDTy->isObjCObjectType()) { 14816 /// A field cannot be an Objective-c object 14817 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14818 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14819 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14820 FD->setType(T); 14821 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 14822 Record && !ObjCFieldLifetimeErrReported && 14823 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14824 // It's an error in ARC or Weak if a field has lifetime. 14825 // We don't want to report this in a system header, though, 14826 // so we just make the field unavailable. 14827 // FIXME: that's really not sufficient; we need to make the type 14828 // itself invalid to, say, initialize or copy. 14829 QualType T = FD->getType(); 14830 if (T.hasNonTrivialObjCLifetime()) { 14831 SourceLocation loc = FD->getLocation(); 14832 if (getSourceManager().isInSystemHeader(loc)) { 14833 if (!FD->hasAttr<UnavailableAttr>()) { 14834 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14835 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14836 } 14837 } else { 14838 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14839 << T->isBlockPointerType() << Record->getTagKind(); 14840 } 14841 ObjCFieldLifetimeErrReported = true; 14842 } 14843 } else if (getLangOpts().ObjC1 && 14844 getLangOpts().getGC() != LangOptions::NonGC && 14845 Record && !Record->hasObjectMember()) { 14846 if (FD->getType()->isObjCObjectPointerType() || 14847 FD->getType().isObjCGCStrong()) 14848 Record->setHasObjectMember(true); 14849 else if (Context.getAsArrayType(FD->getType())) { 14850 QualType BaseType = Context.getBaseElementType(FD->getType()); 14851 if (BaseType->isRecordType() && 14852 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14853 Record->setHasObjectMember(true); 14854 else if (BaseType->isObjCObjectPointerType() || 14855 BaseType.isObjCGCStrong()) 14856 Record->setHasObjectMember(true); 14857 } 14858 } 14859 if (Record && FD->getType().isVolatileQualified()) 14860 Record->setHasVolatileMember(true); 14861 // Keep track of the number of named members. 14862 if (FD->getIdentifier()) 14863 ++NumNamedMembers; 14864 } 14865 14866 // Okay, we successfully defined 'Record'. 14867 if (Record) { 14868 bool Completed = false; 14869 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14870 if (!CXXRecord->isInvalidDecl()) { 14871 // Set access bits correctly on the directly-declared conversions. 14872 for (CXXRecordDecl::conversion_iterator 14873 I = CXXRecord->conversion_begin(), 14874 E = CXXRecord->conversion_end(); I != E; ++I) 14875 I.setAccess((*I)->getAccess()); 14876 } 14877 14878 if (!CXXRecord->isDependentType()) { 14879 if (CXXRecord->hasUserDeclaredDestructor()) { 14880 // Adjust user-defined destructor exception spec. 14881 if (getLangOpts().CPlusPlus11) 14882 AdjustDestructorExceptionSpec(CXXRecord, 14883 CXXRecord->getDestructor()); 14884 } 14885 14886 if (!CXXRecord->isInvalidDecl()) { 14887 // Add any implicitly-declared members to this class. 14888 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14889 14890 // If we have virtual base classes, we may end up finding multiple 14891 // final overriders for a given virtual function. Check for this 14892 // problem now. 14893 if (CXXRecord->getNumVBases()) { 14894 CXXFinalOverriderMap FinalOverriders; 14895 CXXRecord->getFinalOverriders(FinalOverriders); 14896 14897 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14898 MEnd = FinalOverriders.end(); 14899 M != MEnd; ++M) { 14900 for (OverridingMethods::iterator SO = M->second.begin(), 14901 SOEnd = M->second.end(); 14902 SO != SOEnd; ++SO) { 14903 assert(SO->second.size() > 0 && 14904 "Virtual function without overridding functions?"); 14905 if (SO->second.size() == 1) 14906 continue; 14907 14908 // C++ [class.virtual]p2: 14909 // In a derived class, if a virtual member function of a base 14910 // class subobject has more than one final overrider the 14911 // program is ill-formed. 14912 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14913 << (const NamedDecl *)M->first << Record; 14914 Diag(M->first->getLocation(), 14915 diag::note_overridden_virtual_function); 14916 for (OverridingMethods::overriding_iterator 14917 OM = SO->second.begin(), 14918 OMEnd = SO->second.end(); 14919 OM != OMEnd; ++OM) 14920 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14921 << (const NamedDecl *)M->first << OM->Method->getParent(); 14922 14923 Record->setInvalidDecl(); 14924 } 14925 } 14926 CXXRecord->completeDefinition(&FinalOverriders); 14927 Completed = true; 14928 } 14929 } 14930 } 14931 } 14932 14933 if (!Completed) 14934 Record->completeDefinition(); 14935 14936 // We may have deferred checking for a deleted destructor. Check now. 14937 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14938 auto *Dtor = CXXRecord->getDestructor(); 14939 if (Dtor && Dtor->isImplicit() && 14940 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14941 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14942 } 14943 14944 if (Record->hasAttrs()) { 14945 CheckAlignasUnderalignment(Record); 14946 14947 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14948 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14949 IA->getRange(), IA->getBestCase(), 14950 IA->getSemanticSpelling()); 14951 } 14952 14953 // Check if the structure/union declaration is a type that can have zero 14954 // size in C. For C this is a language extension, for C++ it may cause 14955 // compatibility problems. 14956 bool CheckForZeroSize; 14957 if (!getLangOpts().CPlusPlus) { 14958 CheckForZeroSize = true; 14959 } else { 14960 // For C++ filter out types that cannot be referenced in C code. 14961 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14962 CheckForZeroSize = 14963 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14964 !CXXRecord->isDependentType() && 14965 CXXRecord->isCLike(); 14966 } 14967 if (CheckForZeroSize) { 14968 bool ZeroSize = true; 14969 bool IsEmpty = true; 14970 unsigned NonBitFields = 0; 14971 for (RecordDecl::field_iterator I = Record->field_begin(), 14972 E = Record->field_end(); 14973 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14974 IsEmpty = false; 14975 if (I->isUnnamedBitfield()) { 14976 if (I->getBitWidthValue(Context) > 0) 14977 ZeroSize = false; 14978 } else { 14979 ++NonBitFields; 14980 QualType FieldType = I->getType(); 14981 if (FieldType->isIncompleteType() || 14982 !Context.getTypeSizeInChars(FieldType).isZero()) 14983 ZeroSize = false; 14984 } 14985 } 14986 14987 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14988 // allowed in C++, but warn if its declaration is inside 14989 // extern "C" block. 14990 if (ZeroSize) { 14991 Diag(RecLoc, getLangOpts().CPlusPlus ? 14992 diag::warn_zero_size_struct_union_in_extern_c : 14993 diag::warn_zero_size_struct_union_compat) 14994 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14995 } 14996 14997 // Structs without named members are extension in C (C99 6.7.2.1p7), 14998 // but are accepted by GCC. 14999 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15000 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15001 diag::ext_no_named_members_in_struct_union) 15002 << Record->isUnion(); 15003 } 15004 } 15005 } else { 15006 ObjCIvarDecl **ClsFields = 15007 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15008 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15009 ID->setEndOfDefinitionLoc(RBrac); 15010 // Add ivar's to class's DeclContext. 15011 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15012 ClsFields[i]->setLexicalDeclContext(ID); 15013 ID->addDecl(ClsFields[i]); 15014 } 15015 // Must enforce the rule that ivars in the base classes may not be 15016 // duplicates. 15017 if (ID->getSuperClass()) 15018 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15019 } else if (ObjCImplementationDecl *IMPDecl = 15020 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15021 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15022 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15023 // Ivar declared in @implementation never belongs to the implementation. 15024 // Only it is in implementation's lexical context. 15025 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15026 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15027 IMPDecl->setIvarLBraceLoc(LBrac); 15028 IMPDecl->setIvarRBraceLoc(RBrac); 15029 } else if (ObjCCategoryDecl *CDecl = 15030 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15031 // case of ivars in class extension; all other cases have been 15032 // reported as errors elsewhere. 15033 // FIXME. Class extension does not have a LocEnd field. 15034 // CDecl->setLocEnd(RBrac); 15035 // Add ivar's to class extension's DeclContext. 15036 // Diagnose redeclaration of private ivars. 15037 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15038 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15039 if (IDecl) { 15040 if (const ObjCIvarDecl *ClsIvar = 15041 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15042 Diag(ClsFields[i]->getLocation(), 15043 diag::err_duplicate_ivar_declaration); 15044 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15045 continue; 15046 } 15047 for (const auto *Ext : IDecl->known_extensions()) { 15048 if (const ObjCIvarDecl *ClsExtIvar 15049 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15050 Diag(ClsFields[i]->getLocation(), 15051 diag::err_duplicate_ivar_declaration); 15052 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15053 continue; 15054 } 15055 } 15056 } 15057 ClsFields[i]->setLexicalDeclContext(CDecl); 15058 CDecl->addDecl(ClsFields[i]); 15059 } 15060 CDecl->setIvarLBraceLoc(LBrac); 15061 CDecl->setIvarRBraceLoc(RBrac); 15062 } 15063 } 15064 15065 if (Attr) 15066 ProcessDeclAttributeList(S, Record, Attr); 15067 } 15068 15069 /// \brief Determine whether the given integral value is representable within 15070 /// the given type T. 15071 static bool isRepresentableIntegerValue(ASTContext &Context, 15072 llvm::APSInt &Value, 15073 QualType T) { 15074 assert(T->isIntegralType(Context) && "Integral type required!"); 15075 unsigned BitWidth = Context.getIntWidth(T); 15076 15077 if (Value.isUnsigned() || Value.isNonNegative()) { 15078 if (T->isSignedIntegerOrEnumerationType()) 15079 --BitWidth; 15080 return Value.getActiveBits() <= BitWidth; 15081 } 15082 return Value.getMinSignedBits() <= BitWidth; 15083 } 15084 15085 // \brief Given an integral type, return the next larger integral type 15086 // (or a NULL type of no such type exists). 15087 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15088 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15089 // enum checking below. 15090 assert(T->isIntegralType(Context) && "Integral type required!"); 15091 const unsigned NumTypes = 4; 15092 QualType SignedIntegralTypes[NumTypes] = { 15093 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15094 }; 15095 QualType UnsignedIntegralTypes[NumTypes] = { 15096 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15097 Context.UnsignedLongLongTy 15098 }; 15099 15100 unsigned BitWidth = Context.getTypeSize(T); 15101 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15102 : UnsignedIntegralTypes; 15103 for (unsigned I = 0; I != NumTypes; ++I) 15104 if (Context.getTypeSize(Types[I]) > BitWidth) 15105 return Types[I]; 15106 15107 return QualType(); 15108 } 15109 15110 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15111 EnumConstantDecl *LastEnumConst, 15112 SourceLocation IdLoc, 15113 IdentifierInfo *Id, 15114 Expr *Val) { 15115 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15116 llvm::APSInt EnumVal(IntWidth); 15117 QualType EltTy; 15118 15119 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15120 Val = nullptr; 15121 15122 if (Val) 15123 Val = DefaultLvalueConversion(Val).get(); 15124 15125 if (Val) { 15126 if (Enum->isDependentType() || Val->isTypeDependent()) 15127 EltTy = Context.DependentTy; 15128 else { 15129 SourceLocation ExpLoc; 15130 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15131 !getLangOpts().MSVCCompat) { 15132 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15133 // constant-expression in the enumerator-definition shall be a converted 15134 // constant expression of the underlying type. 15135 EltTy = Enum->getIntegerType(); 15136 ExprResult Converted = 15137 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15138 CCEK_Enumerator); 15139 if (Converted.isInvalid()) 15140 Val = nullptr; 15141 else 15142 Val = Converted.get(); 15143 } else if (!Val->isValueDependent() && 15144 !(Val = VerifyIntegerConstantExpression(Val, 15145 &EnumVal).get())) { 15146 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15147 } else { 15148 if (Enum->isFixed()) { 15149 EltTy = Enum->getIntegerType(); 15150 15151 // In Obj-C and Microsoft mode, require the enumeration value to be 15152 // representable in the underlying type of the enumeration. In C++11, 15153 // we perform a non-narrowing conversion as part of converted constant 15154 // expression checking. 15155 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15156 if (getLangOpts().MSVCCompat) { 15157 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15158 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15159 } else 15160 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15161 } else 15162 Val = ImpCastExprToType(Val, EltTy, 15163 EltTy->isBooleanType() ? 15164 CK_IntegralToBoolean : CK_IntegralCast) 15165 .get(); 15166 } else if (getLangOpts().CPlusPlus) { 15167 // C++11 [dcl.enum]p5: 15168 // If the underlying type is not fixed, the type of each enumerator 15169 // is the type of its initializing value: 15170 // - If an initializer is specified for an enumerator, the 15171 // initializing value has the same type as the expression. 15172 EltTy = Val->getType(); 15173 } else { 15174 // C99 6.7.2.2p2: 15175 // The expression that defines the value of an enumeration constant 15176 // shall be an integer constant expression that has a value 15177 // representable as an int. 15178 15179 // Complain if the value is not representable in an int. 15180 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15181 Diag(IdLoc, diag::ext_enum_value_not_int) 15182 << EnumVal.toString(10) << Val->getSourceRange() 15183 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15184 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15185 // Force the type of the expression to 'int'. 15186 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15187 } 15188 EltTy = Val->getType(); 15189 } 15190 } 15191 } 15192 } 15193 15194 if (!Val) { 15195 if (Enum->isDependentType()) 15196 EltTy = Context.DependentTy; 15197 else if (!LastEnumConst) { 15198 // C++0x [dcl.enum]p5: 15199 // If the underlying type is not fixed, the type of each enumerator 15200 // is the type of its initializing value: 15201 // - If no initializer is specified for the first enumerator, the 15202 // initializing value has an unspecified integral type. 15203 // 15204 // GCC uses 'int' for its unspecified integral type, as does 15205 // C99 6.7.2.2p3. 15206 if (Enum->isFixed()) { 15207 EltTy = Enum->getIntegerType(); 15208 } 15209 else { 15210 EltTy = Context.IntTy; 15211 } 15212 } else { 15213 // Assign the last value + 1. 15214 EnumVal = LastEnumConst->getInitVal(); 15215 ++EnumVal; 15216 EltTy = LastEnumConst->getType(); 15217 15218 // Check for overflow on increment. 15219 if (EnumVal < LastEnumConst->getInitVal()) { 15220 // C++0x [dcl.enum]p5: 15221 // If the underlying type is not fixed, the type of each enumerator 15222 // is the type of its initializing value: 15223 // 15224 // - Otherwise the type of the initializing value is the same as 15225 // the type of the initializing value of the preceding enumerator 15226 // unless the incremented value is not representable in that type, 15227 // in which case the type is an unspecified integral type 15228 // sufficient to contain the incremented value. If no such type 15229 // exists, the program is ill-formed. 15230 QualType T = getNextLargerIntegralType(Context, EltTy); 15231 if (T.isNull() || Enum->isFixed()) { 15232 // There is no integral type larger enough to represent this 15233 // value. Complain, then allow the value to wrap around. 15234 EnumVal = LastEnumConst->getInitVal(); 15235 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15236 ++EnumVal; 15237 if (Enum->isFixed()) 15238 // When the underlying type is fixed, this is ill-formed. 15239 Diag(IdLoc, diag::err_enumerator_wrapped) 15240 << EnumVal.toString(10) 15241 << EltTy; 15242 else 15243 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15244 << EnumVal.toString(10); 15245 } else { 15246 EltTy = T; 15247 } 15248 15249 // Retrieve the last enumerator's value, extent that type to the 15250 // type that is supposed to be large enough to represent the incremented 15251 // value, then increment. 15252 EnumVal = LastEnumConst->getInitVal(); 15253 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15254 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15255 ++EnumVal; 15256 15257 // If we're not in C++, diagnose the overflow of enumerator values, 15258 // which in C99 means that the enumerator value is not representable in 15259 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15260 // permits enumerator values that are representable in some larger 15261 // integral type. 15262 if (!getLangOpts().CPlusPlus && !T.isNull()) 15263 Diag(IdLoc, diag::warn_enum_value_overflow); 15264 } else if (!getLangOpts().CPlusPlus && 15265 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15266 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15267 Diag(IdLoc, diag::ext_enum_value_not_int) 15268 << EnumVal.toString(10) << 1; 15269 } 15270 } 15271 } 15272 15273 if (!EltTy->isDependentType()) { 15274 // Make the enumerator value match the signedness and size of the 15275 // enumerator's type. 15276 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15277 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15278 } 15279 15280 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15281 Val, EnumVal); 15282 } 15283 15284 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15285 SourceLocation IILoc) { 15286 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15287 !getLangOpts().CPlusPlus) 15288 return SkipBodyInfo(); 15289 15290 // We have an anonymous enum definition. Look up the first enumerator to 15291 // determine if we should merge the definition with an existing one and 15292 // skip the body. 15293 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15294 ForRedeclaration); 15295 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15296 if (!PrevECD) 15297 return SkipBodyInfo(); 15298 15299 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15300 NamedDecl *Hidden; 15301 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15302 SkipBodyInfo Skip; 15303 Skip.Previous = Hidden; 15304 return Skip; 15305 } 15306 15307 return SkipBodyInfo(); 15308 } 15309 15310 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15311 SourceLocation IdLoc, IdentifierInfo *Id, 15312 AttributeList *Attr, 15313 SourceLocation EqualLoc, Expr *Val) { 15314 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15315 EnumConstantDecl *LastEnumConst = 15316 cast_or_null<EnumConstantDecl>(lastEnumConst); 15317 15318 // The scope passed in may not be a decl scope. Zip up the scope tree until 15319 // we find one that is. 15320 S = getNonFieldDeclScope(S); 15321 15322 // Verify that there isn't already something declared with this name in this 15323 // scope. 15324 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15325 ForRedeclaration); 15326 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15327 // Maybe we will complain about the shadowed template parameter. 15328 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15329 // Just pretend that we didn't see the previous declaration. 15330 PrevDecl = nullptr; 15331 } 15332 15333 // C++ [class.mem]p15: 15334 // If T is the name of a class, then each of the following shall have a name 15335 // different from T: 15336 // - every enumerator of every member of class T that is an unscoped 15337 // enumerated type 15338 if (!TheEnumDecl->isScoped()) 15339 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15340 DeclarationNameInfo(Id, IdLoc)); 15341 15342 EnumConstantDecl *New = 15343 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15344 if (!New) 15345 return nullptr; 15346 15347 if (PrevDecl) { 15348 // When in C++, we may get a TagDecl with the same name; in this case the 15349 // enum constant will 'hide' the tag. 15350 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15351 "Received TagDecl when not in C++!"); 15352 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15353 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15354 if (isa<EnumConstantDecl>(PrevDecl)) 15355 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15356 else 15357 Diag(IdLoc, diag::err_redefinition) << Id; 15358 notePreviousDefinition(PrevDecl, IdLoc); 15359 return nullptr; 15360 } 15361 } 15362 15363 // Process attributes. 15364 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15365 AddPragmaAttributes(S, New); 15366 15367 // Register this decl in the current scope stack. 15368 New->setAccess(TheEnumDecl->getAccess()); 15369 PushOnScopeChains(New, S); 15370 15371 ActOnDocumentableDecl(New); 15372 15373 return New; 15374 } 15375 15376 // Returns true when the enum initial expression does not trigger the 15377 // duplicate enum warning. A few common cases are exempted as follows: 15378 // Element2 = Element1 15379 // Element2 = Element1 + 1 15380 // Element2 = Element1 - 1 15381 // Where Element2 and Element1 are from the same enum. 15382 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15383 Expr *InitExpr = ECD->getInitExpr(); 15384 if (!InitExpr) 15385 return true; 15386 InitExpr = InitExpr->IgnoreImpCasts(); 15387 15388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15389 if (!BO->isAdditiveOp()) 15390 return true; 15391 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15392 if (!IL) 15393 return true; 15394 if (IL->getValue() != 1) 15395 return true; 15396 15397 InitExpr = BO->getLHS(); 15398 } 15399 15400 // This checks if the elements are from the same enum. 15401 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15402 if (!DRE) 15403 return true; 15404 15405 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15406 if (!EnumConstant) 15407 return true; 15408 15409 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15410 Enum) 15411 return true; 15412 15413 return false; 15414 } 15415 15416 namespace { 15417 struct DupKey { 15418 int64_t val; 15419 bool isTombstoneOrEmptyKey; 15420 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15421 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15422 }; 15423 15424 static DupKey GetDupKey(const llvm::APSInt& Val) { 15425 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15426 false); 15427 } 15428 15429 struct DenseMapInfoDupKey { 15430 static DupKey getEmptyKey() { return DupKey(0, true); } 15431 static DupKey getTombstoneKey() { return DupKey(1, true); } 15432 static unsigned getHashValue(const DupKey Key) { 15433 return (unsigned)(Key.val * 37); 15434 } 15435 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15436 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15437 LHS.val == RHS.val; 15438 } 15439 }; 15440 } // end anonymous namespace 15441 15442 // Emits a warning when an element is implicitly set a value that 15443 // a previous element has already been set to. 15444 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15445 EnumDecl *Enum, 15446 QualType EnumType) { 15447 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15448 return; 15449 // Avoid anonymous enums 15450 if (!Enum->getIdentifier()) 15451 return; 15452 15453 // Only check for small enums. 15454 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15455 return; 15456 15457 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15458 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15459 15460 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15461 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15462 ValueToVectorMap; 15463 15464 DuplicatesVector DupVector; 15465 ValueToVectorMap EnumMap; 15466 15467 // Populate the EnumMap with all values represented by enum constants without 15468 // an initialier. 15469 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15470 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15471 15472 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15473 // this constant. Skip this enum since it may be ill-formed. 15474 if (!ECD) { 15475 return; 15476 } 15477 15478 if (ECD->getInitExpr()) 15479 continue; 15480 15481 DupKey Key = GetDupKey(ECD->getInitVal()); 15482 DeclOrVector &Entry = EnumMap[Key]; 15483 15484 // First time encountering this value. 15485 if (Entry.isNull()) 15486 Entry = ECD; 15487 } 15488 15489 // Create vectors for any values that has duplicates. 15490 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15491 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15492 if (!ValidDuplicateEnum(ECD, Enum)) 15493 continue; 15494 15495 DupKey Key = GetDupKey(ECD->getInitVal()); 15496 15497 DeclOrVector& Entry = EnumMap[Key]; 15498 if (Entry.isNull()) 15499 continue; 15500 15501 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15502 // Ensure constants are different. 15503 if (D == ECD) 15504 continue; 15505 15506 // Create new vector and push values onto it. 15507 ECDVector *Vec = new ECDVector(); 15508 Vec->push_back(D); 15509 Vec->push_back(ECD); 15510 15511 // Update entry to point to the duplicates vector. 15512 Entry = Vec; 15513 15514 // Store the vector somewhere we can consult later for quick emission of 15515 // diagnostics. 15516 DupVector.push_back(Vec); 15517 continue; 15518 } 15519 15520 ECDVector *Vec = Entry.get<ECDVector*>(); 15521 // Make sure constants are not added more than once. 15522 if (*Vec->begin() == ECD) 15523 continue; 15524 15525 Vec->push_back(ECD); 15526 } 15527 15528 // Emit diagnostics. 15529 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15530 DupVectorEnd = DupVector.end(); 15531 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15532 ECDVector *Vec = *DupVectorIter; 15533 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15534 15535 // Emit warning for one enum constant. 15536 ECDVector::iterator I = Vec->begin(); 15537 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15538 << (*I)->getName() << (*I)->getInitVal().toString(10) 15539 << (*I)->getSourceRange(); 15540 ++I; 15541 15542 // Emit one note for each of the remaining enum constants with 15543 // the same value. 15544 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15545 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15546 << (*I)->getName() << (*I)->getInitVal().toString(10) 15547 << (*I)->getSourceRange(); 15548 delete Vec; 15549 } 15550 } 15551 15552 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15553 bool AllowMask) const { 15554 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 15555 assert(ED->isCompleteDefinition() && "expected enum definition"); 15556 15557 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15558 llvm::APInt &FlagBits = R.first->second; 15559 15560 if (R.second) { 15561 for (auto *E : ED->enumerators()) { 15562 const auto &EVal = E->getInitVal(); 15563 // Only single-bit enumerators introduce new flag values. 15564 if (EVal.isPowerOf2()) 15565 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15566 } 15567 } 15568 15569 // A value is in a flag enum if either its bits are a subset of the enum's 15570 // flag bits (the first condition) or we are allowing masks and the same is 15571 // true of its complement (the second condition). When masks are allowed, we 15572 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15573 // 15574 // While it's true that any value could be used as a mask, the assumption is 15575 // that a mask will have all of the insignificant bits set. Anything else is 15576 // likely a logic error. 15577 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15578 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15579 } 15580 15581 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15582 Decl *EnumDeclX, 15583 ArrayRef<Decl *> Elements, 15584 Scope *S, AttributeList *Attr) { 15585 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15586 QualType EnumType = Context.getTypeDeclType(Enum); 15587 15588 if (Attr) 15589 ProcessDeclAttributeList(S, Enum, Attr); 15590 15591 if (Enum->isDependentType()) { 15592 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15593 EnumConstantDecl *ECD = 15594 cast_or_null<EnumConstantDecl>(Elements[i]); 15595 if (!ECD) continue; 15596 15597 ECD->setType(EnumType); 15598 } 15599 15600 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15601 return; 15602 } 15603 15604 // TODO: If the result value doesn't fit in an int, it must be a long or long 15605 // long value. ISO C does not support this, but GCC does as an extension, 15606 // emit a warning. 15607 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15608 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15609 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15610 15611 // Verify that all the values are okay, compute the size of the values, and 15612 // reverse the list. 15613 unsigned NumNegativeBits = 0; 15614 unsigned NumPositiveBits = 0; 15615 15616 // Keep track of whether all elements have type int. 15617 bool AllElementsInt = true; 15618 15619 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15620 EnumConstantDecl *ECD = 15621 cast_or_null<EnumConstantDecl>(Elements[i]); 15622 if (!ECD) continue; // Already issued a diagnostic. 15623 15624 const llvm::APSInt &InitVal = ECD->getInitVal(); 15625 15626 // Keep track of the size of positive and negative values. 15627 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15628 NumPositiveBits = std::max(NumPositiveBits, 15629 (unsigned)InitVal.getActiveBits()); 15630 else 15631 NumNegativeBits = std::max(NumNegativeBits, 15632 (unsigned)InitVal.getMinSignedBits()); 15633 15634 // Keep track of whether every enum element has type int (very commmon). 15635 if (AllElementsInt) 15636 AllElementsInt = ECD->getType() == Context.IntTy; 15637 } 15638 15639 // Figure out the type that should be used for this enum. 15640 QualType BestType; 15641 unsigned BestWidth; 15642 15643 // C++0x N3000 [conv.prom]p3: 15644 // An rvalue of an unscoped enumeration type whose underlying 15645 // type is not fixed can be converted to an rvalue of the first 15646 // of the following types that can represent all the values of 15647 // the enumeration: int, unsigned int, long int, unsigned long 15648 // int, long long int, or unsigned long long int. 15649 // C99 6.4.4.3p2: 15650 // An identifier declared as an enumeration constant has type int. 15651 // The C99 rule is modified by a gcc extension 15652 QualType BestPromotionType; 15653 15654 bool Packed = Enum->hasAttr<PackedAttr>(); 15655 // -fshort-enums is the equivalent to specifying the packed attribute on all 15656 // enum definitions. 15657 if (LangOpts.ShortEnums) 15658 Packed = true; 15659 15660 if (Enum->isFixed()) { 15661 BestType = Enum->getIntegerType(); 15662 if (BestType->isPromotableIntegerType()) 15663 BestPromotionType = Context.getPromotedIntegerType(BestType); 15664 else 15665 BestPromotionType = BestType; 15666 15667 BestWidth = Context.getIntWidth(BestType); 15668 } 15669 else if (NumNegativeBits) { 15670 // If there is a negative value, figure out the smallest integer type (of 15671 // int/long/longlong) that fits. 15672 // If it's packed, check also if it fits a char or a short. 15673 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15674 BestType = Context.SignedCharTy; 15675 BestWidth = CharWidth; 15676 } else if (Packed && NumNegativeBits <= ShortWidth && 15677 NumPositiveBits < ShortWidth) { 15678 BestType = Context.ShortTy; 15679 BestWidth = ShortWidth; 15680 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15681 BestType = Context.IntTy; 15682 BestWidth = IntWidth; 15683 } else { 15684 BestWidth = Context.getTargetInfo().getLongWidth(); 15685 15686 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15687 BestType = Context.LongTy; 15688 } else { 15689 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15690 15691 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15692 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15693 BestType = Context.LongLongTy; 15694 } 15695 } 15696 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15697 } else { 15698 // If there is no negative value, figure out the smallest type that fits 15699 // all of the enumerator values. 15700 // If it's packed, check also if it fits a char or a short. 15701 if (Packed && NumPositiveBits <= CharWidth) { 15702 BestType = Context.UnsignedCharTy; 15703 BestPromotionType = Context.IntTy; 15704 BestWidth = CharWidth; 15705 } else if (Packed && NumPositiveBits <= ShortWidth) { 15706 BestType = Context.UnsignedShortTy; 15707 BestPromotionType = Context.IntTy; 15708 BestWidth = ShortWidth; 15709 } else if (NumPositiveBits <= IntWidth) { 15710 BestType = Context.UnsignedIntTy; 15711 BestWidth = IntWidth; 15712 BestPromotionType 15713 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15714 ? Context.UnsignedIntTy : Context.IntTy; 15715 } else if (NumPositiveBits <= 15716 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15717 BestType = Context.UnsignedLongTy; 15718 BestPromotionType 15719 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15720 ? Context.UnsignedLongTy : Context.LongTy; 15721 } else { 15722 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15723 assert(NumPositiveBits <= BestWidth && 15724 "How could an initializer get larger than ULL?"); 15725 BestType = Context.UnsignedLongLongTy; 15726 BestPromotionType 15727 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15728 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15729 } 15730 } 15731 15732 // Loop over all of the enumerator constants, changing their types to match 15733 // the type of the enum if needed. 15734 for (auto *D : Elements) { 15735 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15736 if (!ECD) continue; // Already issued a diagnostic. 15737 15738 // Standard C says the enumerators have int type, but we allow, as an 15739 // extension, the enumerators to be larger than int size. If each 15740 // enumerator value fits in an int, type it as an int, otherwise type it the 15741 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15742 // that X has type 'int', not 'unsigned'. 15743 15744 // Determine whether the value fits into an int. 15745 llvm::APSInt InitVal = ECD->getInitVal(); 15746 15747 // If it fits into an integer type, force it. Otherwise force it to match 15748 // the enum decl type. 15749 QualType NewTy; 15750 unsigned NewWidth; 15751 bool NewSign; 15752 if (!getLangOpts().CPlusPlus && 15753 !Enum->isFixed() && 15754 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15755 NewTy = Context.IntTy; 15756 NewWidth = IntWidth; 15757 NewSign = true; 15758 } else if (ECD->getType() == BestType) { 15759 // Already the right type! 15760 if (getLangOpts().CPlusPlus) 15761 // C++ [dcl.enum]p4: Following the closing brace of an 15762 // enum-specifier, each enumerator has the type of its 15763 // enumeration. 15764 ECD->setType(EnumType); 15765 continue; 15766 } else { 15767 NewTy = BestType; 15768 NewWidth = BestWidth; 15769 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15770 } 15771 15772 // Adjust the APSInt value. 15773 InitVal = InitVal.extOrTrunc(NewWidth); 15774 InitVal.setIsSigned(NewSign); 15775 ECD->setInitVal(InitVal); 15776 15777 // Adjust the Expr initializer and type. 15778 if (ECD->getInitExpr() && 15779 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15780 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15781 CK_IntegralCast, 15782 ECD->getInitExpr(), 15783 /*base paths*/ nullptr, 15784 VK_RValue)); 15785 if (getLangOpts().CPlusPlus) 15786 // C++ [dcl.enum]p4: Following the closing brace of an 15787 // enum-specifier, each enumerator has the type of its 15788 // enumeration. 15789 ECD->setType(EnumType); 15790 else 15791 ECD->setType(NewTy); 15792 } 15793 15794 Enum->completeDefinition(BestType, BestPromotionType, 15795 NumPositiveBits, NumNegativeBits); 15796 15797 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15798 15799 if (Enum->isClosedFlag()) { 15800 for (Decl *D : Elements) { 15801 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15802 if (!ECD) continue; // Already issued a diagnostic. 15803 15804 llvm::APSInt InitVal = ECD->getInitVal(); 15805 if (InitVal != 0 && !InitVal.isPowerOf2() && 15806 !IsValueInFlagEnum(Enum, InitVal, true)) 15807 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15808 << ECD << Enum; 15809 } 15810 } 15811 15812 // Now that the enum type is defined, ensure it's not been underaligned. 15813 if (Enum->hasAttrs()) 15814 CheckAlignasUnderalignment(Enum); 15815 } 15816 15817 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15818 SourceLocation StartLoc, 15819 SourceLocation EndLoc) { 15820 StringLiteral *AsmString = cast<StringLiteral>(expr); 15821 15822 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15823 AsmString, StartLoc, 15824 EndLoc); 15825 CurContext->addDecl(New); 15826 return New; 15827 } 15828 15829 static void checkModuleImportContext(Sema &S, Module *M, 15830 SourceLocation ImportLoc, DeclContext *DC, 15831 bool FromInclude = false) { 15832 SourceLocation ExternCLoc; 15833 15834 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15835 switch (LSD->getLanguage()) { 15836 case LinkageSpecDecl::lang_c: 15837 if (ExternCLoc.isInvalid()) 15838 ExternCLoc = LSD->getLocStart(); 15839 break; 15840 case LinkageSpecDecl::lang_cxx: 15841 break; 15842 } 15843 DC = LSD->getParent(); 15844 } 15845 15846 while (isa<LinkageSpecDecl>(DC)) 15847 DC = DC->getParent(); 15848 15849 if (!isa<TranslationUnitDecl>(DC)) { 15850 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15851 ? diag::ext_module_import_not_at_top_level_noop 15852 : diag::err_module_import_not_at_top_level_fatal) 15853 << M->getFullModuleName() << DC; 15854 S.Diag(cast<Decl>(DC)->getLocStart(), 15855 diag::note_module_import_not_at_top_level) << DC; 15856 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15857 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15858 << M->getFullModuleName(); 15859 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 15860 } 15861 } 15862 15863 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 15864 SourceLocation ModuleLoc, 15865 ModuleDeclKind MDK, 15866 ModuleIdPath Path) { 15867 // A module implementation unit requires that we are not compiling a module 15868 // of any kind. A module interface unit requires that we are not compiling a 15869 // module map. 15870 switch (getLangOpts().getCompilingModule()) { 15871 case LangOptions::CMK_None: 15872 // It's OK to compile a module interface as a normal translation unit. 15873 break; 15874 15875 case LangOptions::CMK_ModuleInterface: 15876 if (MDK != ModuleDeclKind::Implementation) 15877 break; 15878 15879 // We were asked to compile a module interface unit but this is a module 15880 // implementation unit. That indicates the 'export' is missing. 15881 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15882 << FixItHint::CreateInsertion(ModuleLoc, "export "); 15883 break; 15884 15885 case LangOptions::CMK_ModuleMap: 15886 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 15887 return nullptr; 15888 } 15889 15890 // FIXME: Create a ModuleDecl and return it. 15891 15892 // FIXME: Most of this work should be done by the preprocessor rather than 15893 // here, in order to support macro import. 15894 15895 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 15896 // modules, the dots here are just another character that can appear in a 15897 // module name. 15898 std::string ModuleName; 15899 for (auto &Piece : Path) { 15900 if (!ModuleName.empty()) 15901 ModuleName += "."; 15902 ModuleName += Piece.first->getName(); 15903 } 15904 15905 // If a module name was explicitly specified on the command line, it must be 15906 // correct. 15907 if (!getLangOpts().CurrentModule.empty() && 15908 getLangOpts().CurrentModule != ModuleName) { 15909 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15910 << SourceRange(Path.front().second, Path.back().second) 15911 << getLangOpts().CurrentModule; 15912 return nullptr; 15913 } 15914 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15915 15916 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15917 15918 switch (MDK) { 15919 case ModuleDeclKind::Module: { 15920 // FIXME: Check we're not in a submodule. 15921 15922 // We can't have parsed or imported a definition of this module or parsed a 15923 // module map defining it already. 15924 if (auto *M = Map.findModule(ModuleName)) { 15925 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15926 if (M->DefinitionLoc.isValid()) 15927 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15928 else if (const auto *FE = M->getASTFile()) 15929 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15930 << FE->getName(); 15931 return nullptr; 15932 } 15933 15934 // Create a Module for the module that we're defining. 15935 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15936 assert(Mod && "module creation should not fail"); 15937 15938 // Enter the semantic scope of the module. 15939 ActOnModuleBegin(ModuleLoc, Mod); 15940 return nullptr; 15941 } 15942 15943 case ModuleDeclKind::Partition: 15944 // FIXME: Check we are in a submodule of the named module. 15945 return nullptr; 15946 15947 case ModuleDeclKind::Implementation: 15948 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15949 PP.getIdentifierInfo(ModuleName), Path[0].second); 15950 15951 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15952 if (Import.isInvalid()) 15953 return nullptr; 15954 return ConvertDeclToDeclGroup(Import.get()); 15955 } 15956 15957 llvm_unreachable("unexpected module decl kind"); 15958 } 15959 15960 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15961 SourceLocation ImportLoc, 15962 ModuleIdPath Path) { 15963 Module *Mod = 15964 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15965 /*IsIncludeDirective=*/false); 15966 if (!Mod) 15967 return true; 15968 15969 VisibleModules.setVisible(Mod, ImportLoc); 15970 15971 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15972 15973 // FIXME: we should support importing a submodule within a different submodule 15974 // of the same top-level module. Until we do, make it an error rather than 15975 // silently ignoring the import. 15976 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15977 // warn on a redundant import of the current module? 15978 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15979 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15980 Diag(ImportLoc, getLangOpts().isCompilingModule() 15981 ? diag::err_module_self_import 15982 : diag::err_module_import_in_implementation) 15983 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15984 15985 SmallVector<SourceLocation, 2> IdentifierLocs; 15986 Module *ModCheck = Mod; 15987 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15988 // If we've run out of module parents, just drop the remaining identifiers. 15989 // We need the length to be consistent. 15990 if (!ModCheck) 15991 break; 15992 ModCheck = ModCheck->Parent; 15993 15994 IdentifierLocs.push_back(Path[I].second); 15995 } 15996 15997 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15998 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15999 Mod, IdentifierLocs); 16000 if (!ModuleScopes.empty()) 16001 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16002 TU->addDecl(Import); 16003 return Import; 16004 } 16005 16006 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16007 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16008 BuildModuleInclude(DirectiveLoc, Mod); 16009 } 16010 16011 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16012 // Determine whether we're in the #include buffer for a module. The #includes 16013 // in that buffer do not qualify as module imports; they're just an 16014 // implementation detail of us building the module. 16015 // 16016 // FIXME: Should we even get ActOnModuleInclude calls for those? 16017 bool IsInModuleIncludes = 16018 TUKind == TU_Module && 16019 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16020 16021 bool ShouldAddImport = !IsInModuleIncludes; 16022 16023 // If this module import was due to an inclusion directive, create an 16024 // implicit import declaration to capture it in the AST. 16025 if (ShouldAddImport) { 16026 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16027 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16028 DirectiveLoc, Mod, 16029 DirectiveLoc); 16030 if (!ModuleScopes.empty()) 16031 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16032 TU->addDecl(ImportD); 16033 Consumer.HandleImplicitImportDecl(ImportD); 16034 } 16035 16036 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16037 VisibleModules.setVisible(Mod, DirectiveLoc); 16038 } 16039 16040 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16041 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16042 16043 ModuleScopes.push_back({}); 16044 ModuleScopes.back().Module = Mod; 16045 if (getLangOpts().ModulesLocalVisibility) 16046 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16047 16048 VisibleModules.setVisible(Mod, DirectiveLoc); 16049 16050 // The enclosing context is now part of this module. 16051 // FIXME: Consider creating a child DeclContext to hold the entities 16052 // lexically within the module. 16053 if (getLangOpts().trackLocalOwningModule()) { 16054 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16055 cast<Decl>(DC)->setHidden(true); 16056 cast<Decl>(DC)->setLocalOwningModule(Mod); 16057 } 16058 } 16059 } 16060 16061 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16062 if (getLangOpts().ModulesLocalVisibility) { 16063 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16064 // Leaving a module hides namespace names, so our visible namespace cache 16065 // is now out of date. 16066 VisibleNamespaceCache.clear(); 16067 } 16068 16069 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16070 "left the wrong module scope"); 16071 ModuleScopes.pop_back(); 16072 16073 // We got to the end of processing a local module. Create an 16074 // ImportDecl as we would for an imported module. 16075 FileID File = getSourceManager().getFileID(EomLoc); 16076 SourceLocation DirectiveLoc; 16077 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16078 // We reached the end of a #included module header. Use the #include loc. 16079 assert(File != getSourceManager().getMainFileID() && 16080 "end of submodule in main source file"); 16081 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16082 } else { 16083 // We reached an EOM pragma. Use the pragma location. 16084 DirectiveLoc = EomLoc; 16085 } 16086 BuildModuleInclude(DirectiveLoc, Mod); 16087 16088 // Any further declarations are in whatever module we returned to. 16089 if (getLangOpts().trackLocalOwningModule()) { 16090 // The parser guarantees that this is the same context that we entered 16091 // the module within. 16092 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16093 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16094 if (!getCurrentModule()) 16095 cast<Decl>(DC)->setHidden(false); 16096 } 16097 } 16098 } 16099 16100 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16101 Module *Mod) { 16102 // Bail if we're not allowed to implicitly import a module here. 16103 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16104 VisibleModules.isVisible(Mod)) 16105 return; 16106 16107 // Create the implicit import declaration. 16108 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16109 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16110 Loc, Mod, Loc); 16111 TU->addDecl(ImportD); 16112 Consumer.HandleImplicitImportDecl(ImportD); 16113 16114 // Make the module visible. 16115 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16116 VisibleModules.setVisible(Mod, Loc); 16117 } 16118 16119 /// We have parsed the start of an export declaration, including the '{' 16120 /// (if present). 16121 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16122 SourceLocation LBraceLoc) { 16123 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16124 16125 // C++ Modules TS draft: 16126 // An export-declaration shall appear in the purview of a module other than 16127 // the global module. 16128 if (ModuleScopes.empty() || !ModuleScopes.back().Module || 16129 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit) 16130 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16131 16132 // An export-declaration [...] shall not contain more than one 16133 // export keyword. 16134 // 16135 // The intent here is that an export-declaration cannot appear within another 16136 // export-declaration. 16137 if (D->isExported()) 16138 Diag(ExportLoc, diag::err_export_within_export); 16139 16140 CurContext->addDecl(D); 16141 PushDeclContext(S, D); 16142 return D; 16143 } 16144 16145 /// Complete the definition of an export declaration. 16146 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16147 auto *ED = cast<ExportDecl>(D); 16148 if (RBraceLoc.isValid()) 16149 ED->setRBraceLoc(RBraceLoc); 16150 16151 // FIXME: Diagnose export of internal-linkage declaration (including 16152 // anonymous namespace). 16153 16154 PopDeclContext(); 16155 return D; 16156 } 16157 16158 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16159 IdentifierInfo* AliasName, 16160 SourceLocation PragmaLoc, 16161 SourceLocation NameLoc, 16162 SourceLocation AliasNameLoc) { 16163 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16164 LookupOrdinaryName); 16165 AsmLabelAttr *Attr = 16166 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16167 16168 // If a declaration that: 16169 // 1) declares a function or a variable 16170 // 2) has external linkage 16171 // already exists, add a label attribute to it. 16172 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16173 if (isDeclExternC(PrevDecl)) 16174 PrevDecl->addAttr(Attr); 16175 else 16176 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16177 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16178 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16179 } else 16180 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16181 } 16182 16183 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16184 SourceLocation PragmaLoc, 16185 SourceLocation NameLoc) { 16186 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16187 16188 if (PrevDecl) { 16189 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16190 } else { 16191 (void)WeakUndeclaredIdentifiers.insert( 16192 std::pair<IdentifierInfo*,WeakInfo> 16193 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16194 } 16195 } 16196 16197 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16198 IdentifierInfo* AliasName, 16199 SourceLocation PragmaLoc, 16200 SourceLocation NameLoc, 16201 SourceLocation AliasNameLoc) { 16202 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16203 LookupOrdinaryName); 16204 WeakInfo W = WeakInfo(Name, NameLoc); 16205 16206 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16207 if (!PrevDecl->hasAttr<AliasAttr>()) 16208 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16209 DeclApplyPragmaWeak(TUScope, ND, W); 16210 } else { 16211 (void)WeakUndeclaredIdentifiers.insert( 16212 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16213 } 16214 } 16215 16216 Decl *Sema::getObjCDeclContext() const { 16217 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16218 } 16219