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 "clang/Sema/SemaInternal.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/CommentDiagnostic.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/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 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 70 AllowClassTemplates(AllowTemplates) { 71 WantExpressionKeywords = false; 72 WantCXXNamedCasts = false; 73 WantRemainingKeywords = false; 74 } 75 76 bool ValidateCandidate(const TypoCorrection &candidate) override { 77 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND); 80 return (IsType || AllowedTemplate) && 81 (AllowInvalidDecl || !ND->isInvalidDecl()); 82 } 83 return !WantClassName && candidate.isKeyword(); 84 } 85 86 private: 87 bool AllowInvalidDecl; 88 bool WantClassName; 89 bool AllowClassTemplates; 90 }; 91 92 } // end anonymous namespace 93 94 /// \brief Determine whether the token kind starts a simple-type-specifier. 95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 96 switch (Kind) { 97 // FIXME: Take into account the current language when deciding whether a 98 // token kind is a valid type specifier 99 case tok::kw_short: 100 case tok::kw_long: 101 case tok::kw___int64: 102 case tok::kw___int128: 103 case tok::kw_signed: 104 case tok::kw_unsigned: 105 case tok::kw_void: 106 case tok::kw_char: 107 case tok::kw_int: 108 case tok::kw_half: 109 case tok::kw_float: 110 case tok::kw_double: 111 case tok::kw_wchar_t: 112 case tok::kw_bool: 113 case tok::kw___underlying_type: 114 case tok::kw___auto_type: 115 return true; 116 117 case tok::annot_typename: 118 case tok::kw_char16_t: 119 case tok::kw_char32_t: 120 case tok::kw_typeof: 121 case tok::annot_decltype: 122 case tok::kw_decltype: 123 return getLangOpts().CPlusPlus; 124 125 default: 126 break; 127 } 128 129 return false; 130 } 131 132 namespace { 133 enum class UnqualifiedTypeNameLookupResult { 134 NotFound, 135 FoundNonType, 136 FoundType 137 }; 138 } // end anonymous namespace 139 140 /// \brief Tries to perform unqualified lookup of the type decls in bases for 141 /// dependent class. 142 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 143 /// type decl, \a FoundType if only type decls are found. 144 static UnqualifiedTypeNameLookupResult 145 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 146 SourceLocation NameLoc, 147 const CXXRecordDecl *RD) { 148 if (!RD->hasDefinition()) 149 return UnqualifiedTypeNameLookupResult::NotFound; 150 // Look for type decls in base classes. 151 UnqualifiedTypeNameLookupResult FoundTypeDecl = 152 UnqualifiedTypeNameLookupResult::NotFound; 153 for (const auto &Base : RD->bases()) { 154 const CXXRecordDecl *BaseRD = nullptr; 155 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 156 BaseRD = BaseTT->getAsCXXRecordDecl(); 157 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 158 // Look for type decls in dependent base classes that have known primary 159 // templates. 160 if (!TST || !TST->isDependentType()) 161 continue; 162 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 163 if (!TD) 164 continue; 165 auto *BasePrimaryTemplate = 166 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl()); 167 if (!BasePrimaryTemplate) 168 continue; 169 BaseRD = BasePrimaryTemplate; 170 } 171 if (BaseRD) { 172 for (NamedDecl *ND : BaseRD->lookup(&II)) { 173 if (!isa<TypeDecl>(ND)) 174 return UnqualifiedTypeNameLookupResult::FoundNonType; 175 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 176 } 177 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 178 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 179 case UnqualifiedTypeNameLookupResult::FoundNonType: 180 return UnqualifiedTypeNameLookupResult::FoundNonType; 181 case UnqualifiedTypeNameLookupResult::FoundType: 182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 183 break; 184 case UnqualifiedTypeNameLookupResult::NotFound: 185 break; 186 } 187 } 188 } 189 } 190 191 return FoundTypeDecl; 192 } 193 194 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 195 const IdentifierInfo &II, 196 SourceLocation NameLoc) { 197 // Lookup in the parent class template context, if any. 198 const CXXRecordDecl *RD = nullptr; 199 UnqualifiedTypeNameLookupResult FoundTypeDecl = 200 UnqualifiedTypeNameLookupResult::NotFound; 201 for (DeclContext *DC = S.CurContext; 202 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 203 DC = DC->getParent()) { 204 // Look for type decls in dependent base classes that have known primary 205 // templates. 206 RD = dyn_cast<CXXRecordDecl>(DC); 207 if (RD && RD->getDescribedClassTemplate()) 208 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 209 } 210 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 211 return nullptr; 212 213 // We found some types in dependent base classes. Recover as if the user 214 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 215 // lookup during template instantiation. 216 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 217 218 ASTContext &Context = S.Context; 219 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 220 cast<Type>(Context.getRecordType(RD))); 221 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 222 223 CXXScopeSpec SS; 224 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 225 226 TypeLocBuilder Builder; 227 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 228 DepTL.setNameLoc(NameLoc); 229 DepTL.setElaboratedKeywordLoc(SourceLocation()); 230 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 231 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 232 } 233 234 /// \brief If the identifier refers to a type name within this scope, 235 /// return the declaration of that type. 236 /// 237 /// This routine performs ordinary name lookup of the identifier II 238 /// within the given scope, with optional C++ scope specifier SS, to 239 /// determine whether the name refers to a type. If so, returns an 240 /// opaque pointer (actually a QualType) corresponding to that 241 /// type. Otherwise, returns NULL. 242 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 243 Scope *S, CXXScopeSpec *SS, 244 bool isClassName, bool HasTrailingDot, 245 ParsedType ObjectTypePtr, 246 bool IsCtorOrDtorName, 247 bool WantNontrivialTypeSourceInfo, 248 IdentifierInfo **CorrectedII) { 249 // Determine where we will perform name lookup. 250 DeclContext *LookupCtx = nullptr; 251 if (ObjectTypePtr) { 252 QualType ObjectType = ObjectTypePtr.get(); 253 if (ObjectType->isRecordType()) 254 LookupCtx = computeDeclContext(ObjectType); 255 } else if (SS && SS->isNotEmpty()) { 256 LookupCtx = computeDeclContext(*SS, false); 257 258 if (!LookupCtx) { 259 if (isDependentScopeSpecifier(*SS)) { 260 // C++ [temp.res]p3: 261 // A qualified-id that refers to a type and in which the 262 // nested-name-specifier depends on a template-parameter (14.6.2) 263 // shall be prefixed by the keyword typename to indicate that the 264 // qualified-id denotes a type, forming an 265 // elaborated-type-specifier (7.1.5.3). 266 // 267 // We therefore do not perform any name lookup if the result would 268 // refer to a member of an unknown specialization. 269 if (!isClassName && !IsCtorOrDtorName) 270 return nullptr; 271 272 // We know from the grammar that this name refers to a type, 273 // so build a dependent node to describe the type. 274 if (WantNontrivialTypeSourceInfo) 275 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 276 277 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 278 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 279 II, NameLoc); 280 return ParsedType::make(T); 281 } 282 283 return nullptr; 284 } 285 286 if (!LookupCtx->isDependentContext() && 287 RequireCompleteDeclContext(*SS, LookupCtx)) 288 return nullptr; 289 } 290 291 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 292 // lookup for class-names. 293 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 294 LookupOrdinaryName; 295 LookupResult Result(*this, &II, NameLoc, Kind); 296 if (LookupCtx) { 297 // Perform "qualified" name lookup into the declaration context we 298 // computed, which is either the type of the base of a member access 299 // expression or the declaration context associated with a prior 300 // nested-name-specifier. 301 LookupQualifiedName(Result, LookupCtx); 302 303 if (ObjectTypePtr && Result.empty()) { 304 // C++ [basic.lookup.classref]p3: 305 // If the unqualified-id is ~type-name, the type-name is looked up 306 // in the context of the entire postfix-expression. If the type T of 307 // the object expression is of a class type C, the type-name is also 308 // looked up in the scope of class C. At least one of the lookups shall 309 // find a name that refers to (possibly cv-qualified) T. 310 LookupName(Result, S); 311 } 312 } else { 313 // Perform unqualified name lookup. 314 LookupName(Result, S); 315 316 // For unqualified lookup in a class template in MSVC mode, look into 317 // dependent base classes where the primary class template is known. 318 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 319 if (ParsedType TypeInBase = 320 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 321 return TypeInBase; 322 } 323 } 324 325 NamedDecl *IIDecl = nullptr; 326 switch (Result.getResultKind()) { 327 case LookupResult::NotFound: 328 case LookupResult::NotFoundInCurrentInstantiation: 329 if (CorrectedII) { 330 TypoCorrection Correction = CorrectTypo( 331 Result.getLookupNameInfo(), Kind, S, SS, 332 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName), 333 CTK_ErrorRecovery); 334 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 335 TemplateTy Template; 336 bool MemberOfUnknownSpecialization; 337 UnqualifiedId TemplateName; 338 TemplateName.setIdentifier(NewII, NameLoc); 339 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 340 CXXScopeSpec NewSS, *NewSSPtr = SS; 341 if (SS && NNS) { 342 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 343 NewSSPtr = &NewSS; 344 } 345 if (Correction && (NNS || NewII != &II) && 346 // Ignore a correction to a template type as the to-be-corrected 347 // identifier is not a template (typo correction for template names 348 // is handled elsewhere). 349 !(getLangOpts().CPlusPlus && NewSSPtr && 350 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 351 Template, MemberOfUnknownSpecialization))) { 352 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 353 isClassName, HasTrailingDot, ObjectTypePtr, 354 IsCtorOrDtorName, 355 WantNontrivialTypeSourceInfo); 356 if (Ty) { 357 diagnoseTypo(Correction, 358 PDiag(diag::err_unknown_type_or_class_name_suggest) 359 << Result.getLookupName() << isClassName); 360 if (SS && NNS) 361 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 362 *CorrectedII = NewII; 363 return Ty; 364 } 365 } 366 } 367 // If typo correction failed or was not performed, fall through 368 case LookupResult::FoundOverloaded: 369 case LookupResult::FoundUnresolvedValue: 370 Result.suppressDiagnostics(); 371 return nullptr; 372 373 case LookupResult::Ambiguous: 374 // Recover from type-hiding ambiguities by hiding the type. We'll 375 // do the lookup again when looking for an object, and we can 376 // diagnose the error then. If we don't do this, then the error 377 // about hiding the type will be immediately followed by an error 378 // that only makes sense if the identifier was treated like a type. 379 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 380 Result.suppressDiagnostics(); 381 return nullptr; 382 } 383 384 // Look to see if we have a type anywhere in the list of results. 385 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 386 Res != ResEnd; ++Res) { 387 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 388 if (!IIDecl || 389 (*Res)->getLocation().getRawEncoding() < 390 IIDecl->getLocation().getRawEncoding()) 391 IIDecl = *Res; 392 } 393 } 394 395 if (!IIDecl) { 396 // None of the entities we found is a type, so there is no way 397 // to even assume that the result is a type. In this case, don't 398 // complain about the ambiguity. The parser will either try to 399 // perform this lookup again (e.g., as an object name), which 400 // will produce the ambiguity, or will complain that it expected 401 // a type name. 402 Result.suppressDiagnostics(); 403 return nullptr; 404 } 405 406 // We found a type within the ambiguous lookup; diagnose the 407 // ambiguity and then return that type. This might be the right 408 // answer, or it might not be, but it suppresses any attempt to 409 // perform the name lookup again. 410 break; 411 412 case LookupResult::Found: 413 IIDecl = Result.getFoundDecl(); 414 break; 415 } 416 417 assert(IIDecl && "Didn't find decl"); 418 419 QualType T; 420 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 421 DiagnoseUseOfDecl(IIDecl, NameLoc); 422 423 T = Context.getTypeDeclType(TD); 424 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 425 426 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 427 // constructor or destructor name (in such a case, the scope specifier 428 // will be attached to the enclosing Expr or Decl node). 429 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 430 if (WantNontrivialTypeSourceInfo) { 431 // Construct a type with type-source information. 432 TypeLocBuilder Builder; 433 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 434 435 T = getElaboratedType(ETK_None, *SS, T); 436 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 437 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 438 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 439 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 440 } else { 441 T = getElaboratedType(ETK_None, *SS, T); 442 } 443 } 444 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 445 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 446 if (!HasTrailingDot) 447 T = Context.getObjCInterfaceType(IDecl); 448 } 449 450 if (T.isNull()) { 451 // If it's not plausibly a type, suppress diagnostics. 452 Result.suppressDiagnostics(); 453 return nullptr; 454 } 455 return ParsedType::make(T); 456 } 457 458 // Builds a fake NNS for the given decl context. 459 static NestedNameSpecifier * 460 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 461 for (;; DC = DC->getLookupParent()) { 462 DC = DC->getPrimaryContext(); 463 auto *ND = dyn_cast<NamespaceDecl>(DC); 464 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 465 return NestedNameSpecifier::Create(Context, nullptr, ND); 466 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 467 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 468 RD->getTypeForDecl()); 469 else if (isa<TranslationUnitDecl>(DC)) 470 return NestedNameSpecifier::GlobalSpecifier(Context); 471 } 472 llvm_unreachable("something isn't in TU scope?"); 473 } 474 475 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 476 SourceLocation NameLoc) { 477 // Accepting an undeclared identifier as a default argument for a template 478 // type parameter is a Microsoft extension. 479 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 480 481 // Build a fake DependentNameType that will perform lookup into CurContext at 482 // instantiation time. The name specifier isn't dependent, so template 483 // instantiation won't transform it. It will retry the lookup, however. 484 NestedNameSpecifier *NNS = 485 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 486 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 487 488 // Build type location information. We synthesized the qualifier, so we have 489 // to build a fake NestedNameSpecifierLoc. 490 NestedNameSpecifierLocBuilder NNSLocBuilder; 491 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 492 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 493 494 TypeLocBuilder Builder; 495 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 496 DepTL.setNameLoc(NameLoc); 497 DepTL.setElaboratedKeywordLoc(SourceLocation()); 498 DepTL.setQualifierLoc(QualifierLoc); 499 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 500 } 501 502 /// isTagName() - This method is called *for error recovery purposes only* 503 /// to determine if the specified name is a valid tag name ("struct foo"). If 504 /// so, this returns the TST for the tag corresponding to it (TST_enum, 505 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 506 /// cases in C where the user forgot to specify the tag. 507 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 508 // Do a tag name lookup in this scope. 509 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 510 LookupName(R, S, false); 511 R.suppressDiagnostics(); 512 if (R.getResultKind() == LookupResult::Found) 513 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 514 switch (TD->getTagKind()) { 515 case TTK_Struct: return DeclSpec::TST_struct; 516 case TTK_Interface: return DeclSpec::TST_interface; 517 case TTK_Union: return DeclSpec::TST_union; 518 case TTK_Class: return DeclSpec::TST_class; 519 case TTK_Enum: return DeclSpec::TST_enum; 520 } 521 } 522 523 return DeclSpec::TST_unspecified; 524 } 525 526 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 527 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 528 /// then downgrade the missing typename error to a warning. 529 /// This is needed for MSVC compatibility; Example: 530 /// @code 531 /// template<class T> class A { 532 /// public: 533 /// typedef int TYPE; 534 /// }; 535 /// template<class T> class B : public A<T> { 536 /// public: 537 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 538 /// }; 539 /// @endcode 540 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 541 if (CurContext->isRecord()) { 542 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 543 return true; 544 545 const Type *Ty = SS->getScopeRep()->getAsType(); 546 547 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 548 for (const auto &Base : RD->bases()) 549 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 550 return true; 551 return S->isFunctionPrototypeScope(); 552 } 553 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 554 } 555 556 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 557 SourceLocation IILoc, 558 Scope *S, 559 CXXScopeSpec *SS, 560 ParsedType &SuggestedType, 561 bool AllowClassTemplates) { 562 // We don't have anything to suggest (yet). 563 SuggestedType = nullptr; 564 565 // There may have been a typo in the name of the type. Look up typo 566 // results, in case we have something that we can suggest. 567 if (TypoCorrection Corrected = 568 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 569 llvm::make_unique<TypeNameValidatorCCC>( 570 false, false, AllowClassTemplates), 571 CTK_ErrorRecovery)) { 572 if (Corrected.isKeyword()) { 573 // We corrected to a keyword. 574 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 575 II = Corrected.getCorrectionAsIdentifierInfo(); 576 } else { 577 // We found a similarly-named type or interface; suggest that. 578 if (!SS || !SS->isSet()) { 579 diagnoseTypo(Corrected, 580 PDiag(diag::err_unknown_typename_suggest) << II); 581 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 582 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 583 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 584 II->getName().equals(CorrectedStr); 585 diagnoseTypo(Corrected, 586 PDiag(diag::err_unknown_nested_typename_suggest) 587 << II << DC << DroppedSpecifier << SS->getRange()); 588 } else { 589 llvm_unreachable("could not have corrected a typo here"); 590 } 591 592 CXXScopeSpec tmpSS; 593 if (Corrected.getCorrectionSpecifier()) 594 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 595 SourceRange(IILoc)); 596 SuggestedType = 597 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 598 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 599 /*IsCtorOrDtorName=*/false, 600 /*NonTrivialTypeSourceInfo=*/true); 601 } 602 return; 603 } 604 605 if (getLangOpts().CPlusPlus) { 606 // See if II is a class template that the user forgot to pass arguments to. 607 UnqualifiedId Name; 608 Name.setIdentifier(II, IILoc); 609 CXXScopeSpec EmptySS; 610 TemplateTy TemplateResult; 611 bool MemberOfUnknownSpecialization; 612 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 613 Name, nullptr, true, TemplateResult, 614 MemberOfUnknownSpecialization) == TNK_Type_template) { 615 TemplateName TplName = TemplateResult.get(); 616 Diag(IILoc, diag::err_template_missing_args) << TplName; 617 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 618 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 619 << TplDecl->getTemplateParameters()->getSourceRange(); 620 } 621 return; 622 } 623 } 624 625 // FIXME: Should we move the logic that tries to recover from a missing tag 626 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 627 628 if (!SS || (!SS->isSet() && !SS->isInvalid())) 629 Diag(IILoc, diag::err_unknown_typename) << II; 630 else if (DeclContext *DC = computeDeclContext(*SS, false)) 631 Diag(IILoc, diag::err_typename_nested_not_found) 632 << II << DC << SS->getRange(); 633 else if (isDependentScopeSpecifier(*SS)) { 634 unsigned DiagID = diag::err_typename_missing; 635 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 636 DiagID = diag::ext_typename_missing; 637 638 Diag(SS->getRange().getBegin(), DiagID) 639 << SS->getScopeRep() << II->getName() 640 << SourceRange(SS->getRange().getBegin(), IILoc) 641 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 642 SuggestedType = ActOnTypenameType(S, SourceLocation(), 643 *SS, *II, IILoc).get(); 644 } else { 645 assert(SS && SS->isInvalid() && 646 "Invalid scope specifier has already been diagnosed"); 647 } 648 } 649 650 /// \brief Determine whether the given result set contains either a type name 651 /// or 652 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 653 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 654 NextToken.is(tok::less); 655 656 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 657 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 658 return true; 659 660 if (CheckTemplate && isa<TemplateDecl>(*I)) 661 return true; 662 } 663 664 return false; 665 } 666 667 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 668 Scope *S, CXXScopeSpec &SS, 669 IdentifierInfo *&Name, 670 SourceLocation NameLoc) { 671 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 672 SemaRef.LookupParsedName(R, S, &SS); 673 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 674 StringRef FixItTagName; 675 switch (Tag->getTagKind()) { 676 case TTK_Class: 677 FixItTagName = "class "; 678 break; 679 680 case TTK_Enum: 681 FixItTagName = "enum "; 682 break; 683 684 case TTK_Struct: 685 FixItTagName = "struct "; 686 break; 687 688 case TTK_Interface: 689 FixItTagName = "__interface "; 690 break; 691 692 case TTK_Union: 693 FixItTagName = "union "; 694 break; 695 } 696 697 StringRef TagName = FixItTagName.drop_back(); 698 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 699 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 700 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 701 702 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 703 I != IEnd; ++I) 704 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 705 << Name << TagName; 706 707 // Replace lookup results with just the tag decl. 708 Result.clear(Sema::LookupTagName); 709 SemaRef.LookupParsedName(Result, S, &SS); 710 return true; 711 } 712 713 return false; 714 } 715 716 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 717 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 718 QualType T, SourceLocation NameLoc) { 719 ASTContext &Context = S.Context; 720 721 TypeLocBuilder Builder; 722 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 723 724 T = S.getElaboratedType(ETK_None, SS, T); 725 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 726 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 727 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 728 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 729 } 730 731 Sema::NameClassification 732 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 733 SourceLocation NameLoc, const Token &NextToken, 734 bool IsAddressOfOperand, 735 std::unique_ptr<CorrectionCandidateCallback> CCC) { 736 DeclarationNameInfo NameInfo(Name, NameLoc); 737 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 738 739 if (NextToken.is(tok::coloncolon)) { 740 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 741 QualType(), false, SS, nullptr, false); 742 } 743 744 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 745 LookupParsedName(Result, S, &SS, !CurMethod); 746 747 // For unqualified lookup in a class template in MSVC mode, look into 748 // dependent base classes where the primary class template is known. 749 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 750 if (ParsedType TypeInBase = 751 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 752 return TypeInBase; 753 } 754 755 // Perform lookup for Objective-C instance variables (including automatically 756 // synthesized instance variables), if we're in an Objective-C method. 757 // FIXME: This lookup really, really needs to be folded in to the normal 758 // unqualified lookup mechanism. 759 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 760 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 761 if (E.get() || E.isInvalid()) 762 return E; 763 } 764 765 bool SecondTry = false; 766 bool IsFilteredTemplateName = false; 767 768 Corrected: 769 switch (Result.getResultKind()) { 770 case LookupResult::NotFound: 771 // If an unqualified-id is followed by a '(', then we have a function 772 // call. 773 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 774 // In C++, this is an ADL-only call. 775 // FIXME: Reference? 776 if (getLangOpts().CPlusPlus) 777 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 778 779 // C90 6.3.2.2: 780 // If the expression that precedes the parenthesized argument list in a 781 // function call consists solely of an identifier, and if no 782 // declaration is visible for this identifier, the identifier is 783 // implicitly declared exactly as if, in the innermost block containing 784 // the function call, the declaration 785 // 786 // extern int identifier (); 787 // 788 // appeared. 789 // 790 // We also allow this in C99 as an extension. 791 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 792 Result.addDecl(D); 793 Result.resolveKind(); 794 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 795 } 796 } 797 798 // In C, we first see whether there is a tag type by the same name, in 799 // which case it's likely that the user just forgot to write "enum", 800 // "struct", or "union". 801 if (!getLangOpts().CPlusPlus && !SecondTry && 802 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 803 break; 804 } 805 806 // Perform typo correction to determine if there is another name that is 807 // close to this name. 808 if (!SecondTry && CCC) { 809 SecondTry = true; 810 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 811 Result.getLookupKind(), S, 812 &SS, std::move(CCC), 813 CTK_ErrorRecovery)) { 814 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 815 unsigned QualifiedDiag = diag::err_no_member_suggest; 816 817 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 818 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 819 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 820 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 821 UnqualifiedDiag = diag::err_no_template_suggest; 822 QualifiedDiag = diag::err_no_member_template_suggest; 823 } else if (UnderlyingFirstDecl && 824 (isa<TypeDecl>(UnderlyingFirstDecl) || 825 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 826 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 827 UnqualifiedDiag = diag::err_unknown_typename_suggest; 828 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 829 } 830 831 if (SS.isEmpty()) { 832 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 833 } else {// FIXME: is this even reachable? Test it. 834 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 835 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 836 Name->getName().equals(CorrectedStr); 837 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 838 << Name << computeDeclContext(SS, false) 839 << DroppedSpecifier << SS.getRange()); 840 } 841 842 // Update the name, so that the caller has the new name. 843 Name = Corrected.getCorrectionAsIdentifierInfo(); 844 845 // Typo correction corrected to a keyword. 846 if (Corrected.isKeyword()) 847 return Name; 848 849 // Also update the LookupResult... 850 // FIXME: This should probably go away at some point 851 Result.clear(); 852 Result.setLookupName(Corrected.getCorrection()); 853 if (FirstDecl) 854 Result.addDecl(FirstDecl); 855 856 // If we found an Objective-C instance variable, let 857 // LookupInObjCMethod build the appropriate expression to 858 // reference the ivar. 859 // FIXME: This is a gross hack. 860 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 861 Result.clear(); 862 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 863 return E; 864 } 865 866 goto Corrected; 867 } 868 } 869 870 // We failed to correct; just fall through and let the parser deal with it. 871 Result.suppressDiagnostics(); 872 return NameClassification::Unknown(); 873 874 case LookupResult::NotFoundInCurrentInstantiation: { 875 // We performed name lookup into the current instantiation, and there were 876 // dependent bases, so we treat this result the same way as any other 877 // dependent nested-name-specifier. 878 879 // C++ [temp.res]p2: 880 // A name used in a template declaration or definition and that is 881 // dependent on a template-parameter is assumed not to name a type 882 // unless the applicable name lookup finds a type name or the name is 883 // qualified by the keyword typename. 884 // 885 // FIXME: If the next token is '<', we might want to ask the parser to 886 // perform some heroics to see if we actually have a 887 // template-argument-list, which would indicate a missing 'template' 888 // keyword here. 889 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 890 NameInfo, IsAddressOfOperand, 891 /*TemplateArgs=*/nullptr); 892 } 893 894 case LookupResult::Found: 895 case LookupResult::FoundOverloaded: 896 case LookupResult::FoundUnresolvedValue: 897 break; 898 899 case LookupResult::Ambiguous: 900 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 901 hasAnyAcceptableTemplateNames(Result)) { 902 // C++ [temp.local]p3: 903 // A lookup that finds an injected-class-name (10.2) can result in an 904 // ambiguity in certain cases (for example, if it is found in more than 905 // one base class). If all of the injected-class-names that are found 906 // refer to specializations of the same class template, and if the name 907 // is followed by a template-argument-list, the reference refers to the 908 // class template itself and not a specialization thereof, and is not 909 // ambiguous. 910 // 911 // This filtering can make an ambiguous result into an unambiguous one, 912 // so try again after filtering out template names. 913 FilterAcceptableTemplateNames(Result); 914 if (!Result.isAmbiguous()) { 915 IsFilteredTemplateName = true; 916 break; 917 } 918 } 919 920 // Diagnose the ambiguity and return an error. 921 return NameClassification::Error(); 922 } 923 924 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 925 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 926 // C++ [temp.names]p3: 927 // After name lookup (3.4) finds that a name is a template-name or that 928 // an operator-function-id or a literal- operator-id refers to a set of 929 // overloaded functions any member of which is a function template if 930 // this is followed by a <, the < is always taken as the delimiter of a 931 // template-argument-list and never as the less-than operator. 932 if (!IsFilteredTemplateName) 933 FilterAcceptableTemplateNames(Result); 934 935 if (!Result.empty()) { 936 bool IsFunctionTemplate; 937 bool IsVarTemplate; 938 TemplateName Template; 939 if (Result.end() - Result.begin() > 1) { 940 IsFunctionTemplate = true; 941 Template = Context.getOverloadedTemplateName(Result.begin(), 942 Result.end()); 943 } else { 944 TemplateDecl *TD 945 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 946 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 947 IsVarTemplate = isa<VarTemplateDecl>(TD); 948 949 if (SS.isSet() && !SS.isInvalid()) 950 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 951 /*TemplateKeyword=*/false, 952 TD); 953 else 954 Template = TemplateName(TD); 955 } 956 957 if (IsFunctionTemplate) { 958 // Function templates always go through overload resolution, at which 959 // point we'll perform the various checks (e.g., accessibility) we need 960 // to based on which function we selected. 961 Result.suppressDiagnostics(); 962 963 return NameClassification::FunctionTemplate(Template); 964 } 965 966 return IsVarTemplate ? NameClassification::VarTemplate(Template) 967 : NameClassification::TypeTemplate(Template); 968 } 969 } 970 971 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 972 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 973 DiagnoseUseOfDecl(Type, NameLoc); 974 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 975 QualType T = Context.getTypeDeclType(Type); 976 if (SS.isNotEmpty()) 977 return buildNestedType(*this, SS, T, NameLoc); 978 return ParsedType::make(T); 979 } 980 981 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 982 if (!Class) { 983 // FIXME: It's unfortunate that we don't have a Type node for handling this. 984 if (ObjCCompatibleAliasDecl *Alias = 985 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 986 Class = Alias->getClassInterface(); 987 } 988 989 if (Class) { 990 DiagnoseUseOfDecl(Class, NameLoc); 991 992 if (NextToken.is(tok::period)) { 993 // Interface. <something> is parsed as a property reference expression. 994 // Just return "unknown" as a fall-through for now. 995 Result.suppressDiagnostics(); 996 return NameClassification::Unknown(); 997 } 998 999 QualType T = Context.getObjCInterfaceType(Class); 1000 return ParsedType::make(T); 1001 } 1002 1003 // We can have a type template here if we're classifying a template argument. 1004 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 1005 return NameClassification::TypeTemplate( 1006 TemplateName(cast<TemplateDecl>(FirstDecl))); 1007 1008 // Check for a tag type hidden by a non-type decl in a few cases where it 1009 // seems likely a type is wanted instead of the non-type that was found. 1010 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1011 if ((NextToken.is(tok::identifier) || 1012 (NextIsOp && 1013 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1014 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1015 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1016 DiagnoseUseOfDecl(Type, NameLoc); 1017 QualType T = Context.getTypeDeclType(Type); 1018 if (SS.isNotEmpty()) 1019 return buildNestedType(*this, SS, T, NameLoc); 1020 return ParsedType::make(T); 1021 } 1022 1023 if (FirstDecl->isCXXClassMember()) 1024 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1025 nullptr, S); 1026 1027 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1028 return BuildDeclarationNameExpr(SS, Result, ADL); 1029 } 1030 1031 // Determines the context to return to after temporarily entering a 1032 // context. This depends in an unnecessarily complicated way on the 1033 // exact ordering of callbacks from the parser. 1034 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1035 1036 // Functions defined inline within classes aren't parsed until we've 1037 // finished parsing the top-level class, so the top-level class is 1038 // the context we'll need to return to. 1039 // A Lambda call operator whose parent is a class must not be treated 1040 // as an inline member function. A Lambda can be used legally 1041 // either as an in-class member initializer or a default argument. These 1042 // are parsed once the class has been marked complete and so the containing 1043 // context would be the nested class (when the lambda is defined in one); 1044 // If the class is not complete, then the lambda is being used in an 1045 // ill-formed fashion (such as to specify the width of a bit-field, or 1046 // in an array-bound) - in which case we still want to return the 1047 // lexically containing DC (which could be a nested class). 1048 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1049 DC = DC->getLexicalParent(); 1050 1051 // A function not defined within a class will always return to its 1052 // lexical context. 1053 if (!isa<CXXRecordDecl>(DC)) 1054 return DC; 1055 1056 // A C++ inline method/friend is parsed *after* the topmost class 1057 // it was declared in is fully parsed ("complete"); the topmost 1058 // class is the context we need to return to. 1059 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1060 DC = RD; 1061 1062 // Return the declaration context of the topmost class the inline method is 1063 // declared in. 1064 return DC; 1065 } 1066 1067 return DC->getLexicalParent(); 1068 } 1069 1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1071 assert(getContainingDC(DC) == CurContext && 1072 "The next DeclContext should be lexically contained in the current one."); 1073 CurContext = DC; 1074 S->setEntity(DC); 1075 } 1076 1077 void Sema::PopDeclContext() { 1078 assert(CurContext && "DeclContext imbalance!"); 1079 1080 CurContext = getContainingDC(CurContext); 1081 assert(CurContext && "Popped translation unit!"); 1082 } 1083 1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1085 Decl *D) { 1086 // Unlike PushDeclContext, the context to which we return is not necessarily 1087 // the containing DC of TD, because the new context will be some pre-existing 1088 // TagDecl definition instead of a fresh one. 1089 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1090 CurContext = cast<TagDecl>(D)->getDefinition(); 1091 assert(CurContext && "skipping definition of undefined tag"); 1092 // Start lookups from the parent of the current context; we don't want to look 1093 // into the pre-existing complete definition. 1094 S->setEntity(CurContext->getLookupParent()); 1095 return Result; 1096 } 1097 1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1099 CurContext = static_cast<decltype(CurContext)>(Context); 1100 } 1101 1102 /// EnterDeclaratorContext - Used when we must lookup names in the context 1103 /// of a declarator's nested name specifier. 1104 /// 1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1106 // C++0x [basic.lookup.unqual]p13: 1107 // A name used in the definition of a static data member of class 1108 // X (after the qualified-id of the static member) is looked up as 1109 // if the name was used in a member function of X. 1110 // C++0x [basic.lookup.unqual]p14: 1111 // If a variable member of a namespace is defined outside of the 1112 // scope of its namespace then any name used in the definition of 1113 // the variable member (after the declarator-id) is looked up as 1114 // if the definition of the variable member occurred in its 1115 // namespace. 1116 // Both of these imply that we should push a scope whose context 1117 // is the semantic context of the declaration. We can't use 1118 // PushDeclContext here because that context is not necessarily 1119 // lexically contained in the current context. Fortunately, 1120 // the containing scope should have the appropriate information. 1121 1122 assert(!S->getEntity() && "scope already has entity"); 1123 1124 #ifndef NDEBUG 1125 Scope *Ancestor = S->getParent(); 1126 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1127 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1128 #endif 1129 1130 CurContext = DC; 1131 S->setEntity(DC); 1132 } 1133 1134 void Sema::ExitDeclaratorContext(Scope *S) { 1135 assert(S->getEntity() == CurContext && "Context imbalance!"); 1136 1137 // Switch back to the lexical context. The safety of this is 1138 // enforced by an assert in EnterDeclaratorContext. 1139 Scope *Ancestor = S->getParent(); 1140 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1141 CurContext = Ancestor->getEntity(); 1142 1143 // We don't need to do anything with the scope, which is going to 1144 // disappear. 1145 } 1146 1147 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1148 // We assume that the caller has already called 1149 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1150 FunctionDecl *FD = D->getAsFunction(); 1151 if (!FD) 1152 return; 1153 1154 // Same implementation as PushDeclContext, but enters the context 1155 // from the lexical parent, rather than the top-level class. 1156 assert(CurContext == FD->getLexicalParent() && 1157 "The next DeclContext should be lexically contained in the current one."); 1158 CurContext = FD; 1159 S->setEntity(CurContext); 1160 1161 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1162 ParmVarDecl *Param = FD->getParamDecl(P); 1163 // If the parameter has an identifier, then add it to the scope 1164 if (Param->getIdentifier()) { 1165 S->AddDecl(Param); 1166 IdResolver.AddDecl(Param); 1167 } 1168 } 1169 } 1170 1171 void Sema::ActOnExitFunctionContext() { 1172 // Same implementation as PopDeclContext, but returns to the lexical parent, 1173 // rather than the top-level class. 1174 assert(CurContext && "DeclContext imbalance!"); 1175 CurContext = CurContext->getLexicalParent(); 1176 assert(CurContext && "Popped translation unit!"); 1177 } 1178 1179 /// \brief Determine whether we allow overloading of the function 1180 /// PrevDecl with another declaration. 1181 /// 1182 /// This routine determines whether overloading is possible, not 1183 /// whether some new function is actually an overload. It will return 1184 /// true in C++ (where we can always provide overloads) or, as an 1185 /// extension, in C when the previous function is already an 1186 /// overloaded function declaration or has the "overloadable" 1187 /// attribute. 1188 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1189 ASTContext &Context) { 1190 if (Context.getLangOpts().CPlusPlus) 1191 return true; 1192 1193 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1194 return true; 1195 1196 return (Previous.getResultKind() == LookupResult::Found 1197 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1198 } 1199 1200 /// Add this decl to the scope shadowed decl chains. 1201 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1202 // Move up the scope chain until we find the nearest enclosing 1203 // non-transparent context. The declaration will be introduced into this 1204 // scope. 1205 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1206 S = S->getParent(); 1207 1208 // Add scoped declarations into their context, so that they can be 1209 // found later. Declarations without a context won't be inserted 1210 // into any context. 1211 if (AddToContext) 1212 CurContext->addDecl(D); 1213 1214 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1215 // are function-local declarations. 1216 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1217 !D->getDeclContext()->getRedeclContext()->Equals( 1218 D->getLexicalDeclContext()->getRedeclContext()) && 1219 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1220 return; 1221 1222 // Template instantiations should also not be pushed into scope. 1223 if (isa<FunctionDecl>(D) && 1224 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1225 return; 1226 1227 // If this replaces anything in the current scope, 1228 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1229 IEnd = IdResolver.end(); 1230 for (; I != IEnd; ++I) { 1231 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1232 S->RemoveDecl(*I); 1233 IdResolver.RemoveDecl(*I); 1234 1235 // Should only need to replace one decl. 1236 break; 1237 } 1238 } 1239 1240 S->AddDecl(D); 1241 1242 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1243 // Implicitly-generated labels may end up getting generated in an order that 1244 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1245 // the label at the appropriate place in the identifier chain. 1246 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1247 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1248 if (IDC == CurContext) { 1249 if (!S->isDeclScope(*I)) 1250 continue; 1251 } else if (IDC->Encloses(CurContext)) 1252 break; 1253 } 1254 1255 IdResolver.InsertDeclAfter(I, D); 1256 } else { 1257 IdResolver.AddDecl(D); 1258 } 1259 } 1260 1261 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1262 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1263 TUScope->AddDecl(D); 1264 } 1265 1266 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1267 bool AllowInlineNamespace) { 1268 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1269 } 1270 1271 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1272 DeclContext *TargetDC = DC->getPrimaryContext(); 1273 do { 1274 if (DeclContext *ScopeDC = S->getEntity()) 1275 if (ScopeDC->getPrimaryContext() == TargetDC) 1276 return S; 1277 } while ((S = S->getParent())); 1278 1279 return nullptr; 1280 } 1281 1282 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1283 DeclContext*, 1284 ASTContext&); 1285 1286 /// Filters out lookup results that don't fall within the given scope 1287 /// as determined by isDeclInScope. 1288 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1289 bool ConsiderLinkage, 1290 bool AllowInlineNamespace) { 1291 LookupResult::Filter F = R.makeFilter(); 1292 while (F.hasNext()) { 1293 NamedDecl *D = F.next(); 1294 1295 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1296 continue; 1297 1298 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1299 continue; 1300 1301 F.erase(); 1302 } 1303 1304 F.done(); 1305 } 1306 1307 static bool isUsingDecl(NamedDecl *D) { 1308 return isa<UsingShadowDecl>(D) || 1309 isa<UnresolvedUsingTypenameDecl>(D) || 1310 isa<UnresolvedUsingValueDecl>(D); 1311 } 1312 1313 /// Removes using shadow declarations from the lookup results. 1314 static void RemoveUsingDecls(LookupResult &R) { 1315 LookupResult::Filter F = R.makeFilter(); 1316 while (F.hasNext()) 1317 if (isUsingDecl(F.next())) 1318 F.erase(); 1319 1320 F.done(); 1321 } 1322 1323 /// \brief Check for this common pattern: 1324 /// @code 1325 /// class S { 1326 /// S(const S&); // DO NOT IMPLEMENT 1327 /// void operator=(const S&); // DO NOT IMPLEMENT 1328 /// }; 1329 /// @endcode 1330 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1331 // FIXME: Should check for private access too but access is set after we get 1332 // the decl here. 1333 if (D->doesThisDeclarationHaveABody()) 1334 return false; 1335 1336 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1337 return CD->isCopyConstructor(); 1338 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1339 return Method->isCopyAssignmentOperator(); 1340 return false; 1341 } 1342 1343 // We need this to handle 1344 // 1345 // typedef struct { 1346 // void *foo() { return 0; } 1347 // } A; 1348 // 1349 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1350 // for example. If 'A', foo will have external linkage. If we have '*A', 1351 // foo will have no linkage. Since we can't know until we get to the end 1352 // of the typedef, this function finds out if D might have non-external linkage. 1353 // Callers should verify at the end of the TU if it D has external linkage or 1354 // not. 1355 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1356 const DeclContext *DC = D->getDeclContext(); 1357 while (!DC->isTranslationUnit()) { 1358 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1359 if (!RD->hasNameForLinkage()) 1360 return true; 1361 } 1362 DC = DC->getParent(); 1363 } 1364 1365 return !D->isExternallyVisible(); 1366 } 1367 1368 // FIXME: This needs to be refactored; some other isInMainFile users want 1369 // these semantics. 1370 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1371 if (S.TUKind != TU_Complete) 1372 return false; 1373 return S.SourceMgr.isInMainFile(Loc); 1374 } 1375 1376 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1377 assert(D); 1378 1379 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1380 return false; 1381 1382 // Ignore all entities declared within templates, and out-of-line definitions 1383 // of members of class templates. 1384 if (D->getDeclContext()->isDependentContext() || 1385 D->getLexicalDeclContext()->isDependentContext()) 1386 return false; 1387 1388 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1389 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1390 return false; 1391 1392 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1393 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1394 return false; 1395 } else { 1396 // 'static inline' functions are defined in headers; don't warn. 1397 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1398 return false; 1399 } 1400 1401 if (FD->doesThisDeclarationHaveABody() && 1402 Context.DeclMustBeEmitted(FD)) 1403 return false; 1404 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1405 // Constants and utility variables are defined in headers with internal 1406 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1407 // like "inline".) 1408 if (!isMainFileLoc(*this, VD->getLocation())) 1409 return false; 1410 1411 if (Context.DeclMustBeEmitted(VD)) 1412 return false; 1413 1414 if (VD->isStaticDataMember() && 1415 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1416 return false; 1417 } else { 1418 return false; 1419 } 1420 1421 // Only warn for unused decls internal to the translation unit. 1422 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1423 // for inline functions defined in the main source file, for instance. 1424 return mightHaveNonExternalLinkage(D); 1425 } 1426 1427 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1428 if (!D) 1429 return; 1430 1431 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1432 const FunctionDecl *First = FD->getFirstDecl(); 1433 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1434 return; // First should already be in the vector. 1435 } 1436 1437 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1438 const VarDecl *First = VD->getFirstDecl(); 1439 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1440 return; // First should already be in the vector. 1441 } 1442 1443 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1444 UnusedFileScopedDecls.push_back(D); 1445 } 1446 1447 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1448 if (D->isInvalidDecl()) 1449 return false; 1450 1451 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1452 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1453 return false; 1454 1455 if (isa<LabelDecl>(D)) 1456 return true; 1457 1458 // Except for labels, we only care about unused decls that are local to 1459 // functions. 1460 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1461 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1462 // For dependent types, the diagnostic is deferred. 1463 WithinFunction = 1464 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1465 if (!WithinFunction) 1466 return false; 1467 1468 if (isa<TypedefNameDecl>(D)) 1469 return true; 1470 1471 // White-list anything that isn't a local variable. 1472 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1473 return false; 1474 1475 // Types of valid local variables should be complete, so this should succeed. 1476 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1477 1478 // White-list anything with an __attribute__((unused)) type. 1479 QualType Ty = VD->getType(); 1480 1481 // Only look at the outermost level of typedef. 1482 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1483 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1484 return false; 1485 } 1486 1487 // If we failed to complete the type for some reason, or if the type is 1488 // dependent, don't diagnose the variable. 1489 if (Ty->isIncompleteType() || Ty->isDependentType()) 1490 return false; 1491 1492 if (const TagType *TT = Ty->getAs<TagType>()) { 1493 const TagDecl *Tag = TT->getDecl(); 1494 if (Tag->hasAttr<UnusedAttr>()) 1495 return false; 1496 1497 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1498 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1499 return false; 1500 1501 if (const Expr *Init = VD->getInit()) { 1502 if (const ExprWithCleanups *Cleanups = 1503 dyn_cast<ExprWithCleanups>(Init)) 1504 Init = Cleanups->getSubExpr(); 1505 const CXXConstructExpr *Construct = 1506 dyn_cast<CXXConstructExpr>(Init); 1507 if (Construct && !Construct->isElidable()) { 1508 CXXConstructorDecl *CD = Construct->getConstructor(); 1509 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1510 return false; 1511 } 1512 } 1513 } 1514 } 1515 1516 // TODO: __attribute__((unused)) templates? 1517 } 1518 1519 return true; 1520 } 1521 1522 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1523 FixItHint &Hint) { 1524 if (isa<LabelDecl>(D)) { 1525 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1526 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1527 if (AfterColon.isInvalid()) 1528 return; 1529 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1530 getCharRange(D->getLocStart(), AfterColon)); 1531 } 1532 } 1533 1534 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1535 if (D->getTypeForDecl()->isDependentType()) 1536 return; 1537 1538 for (auto *TmpD : D->decls()) { 1539 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1540 DiagnoseUnusedDecl(T); 1541 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1542 DiagnoseUnusedNestedTypedefs(R); 1543 } 1544 } 1545 1546 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1547 /// unless they are marked attr(unused). 1548 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1549 if (!ShouldDiagnoseUnusedDecl(D)) 1550 return; 1551 1552 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1553 // typedefs can be referenced later on, so the diagnostics are emitted 1554 // at end-of-translation-unit. 1555 UnusedLocalTypedefNameCandidates.insert(TD); 1556 return; 1557 } 1558 1559 FixItHint Hint; 1560 GenerateFixForUnusedDecl(D, Context, Hint); 1561 1562 unsigned DiagID; 1563 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1564 DiagID = diag::warn_unused_exception_param; 1565 else if (isa<LabelDecl>(D)) 1566 DiagID = diag::warn_unused_label; 1567 else 1568 DiagID = diag::warn_unused_variable; 1569 1570 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1571 } 1572 1573 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1574 // Verify that we have no forward references left. If so, there was a goto 1575 // or address of a label taken, but no definition of it. Label fwd 1576 // definitions are indicated with a null substmt which is also not a resolved 1577 // MS inline assembly label name. 1578 bool Diagnose = false; 1579 if (L->isMSAsmLabel()) 1580 Diagnose = !L->isResolvedMSAsmLabel(); 1581 else 1582 Diagnose = L->getStmt() == nullptr; 1583 if (Diagnose) 1584 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1585 } 1586 1587 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1588 S->mergeNRVOIntoParent(); 1589 1590 if (S->decl_empty()) return; 1591 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1592 "Scope shouldn't contain decls!"); 1593 1594 for (auto *TmpD : S->decls()) { 1595 assert(TmpD && "This decl didn't get pushed??"); 1596 1597 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1598 NamedDecl *D = cast<NamedDecl>(TmpD); 1599 1600 if (!D->getDeclName()) continue; 1601 1602 // Diagnose unused variables in this scope. 1603 if (!S->hasUnrecoverableErrorOccurred()) { 1604 DiagnoseUnusedDecl(D); 1605 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1606 DiagnoseUnusedNestedTypedefs(RD); 1607 } 1608 1609 // If this was a forward reference to a label, verify it was defined. 1610 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1611 CheckPoppedLabel(LD, *this); 1612 1613 // Remove this name from our lexical scope, and warn on it if we haven't 1614 // already. 1615 IdResolver.RemoveDecl(D); 1616 auto ShadowI = ShadowingDecls.find(D); 1617 if (ShadowI != ShadowingDecls.end()) { 1618 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1619 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1620 << D << FD << FD->getParent(); 1621 Diag(FD->getLocation(), diag::note_previous_declaration); 1622 } 1623 ShadowingDecls.erase(ShadowI); 1624 } 1625 } 1626 } 1627 1628 /// \brief Look for an Objective-C class in the translation unit. 1629 /// 1630 /// \param Id The name of the Objective-C class we're looking for. If 1631 /// typo-correction fixes this name, the Id will be updated 1632 /// to the fixed name. 1633 /// 1634 /// \param IdLoc The location of the name in the translation unit. 1635 /// 1636 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1637 /// if there is no class with the given name. 1638 /// 1639 /// \returns The declaration of the named Objective-C class, or NULL if the 1640 /// class could not be found. 1641 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1642 SourceLocation IdLoc, 1643 bool DoTypoCorrection) { 1644 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1645 // creation from this context. 1646 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1647 1648 if (!IDecl && DoTypoCorrection) { 1649 // Perform typo correction at the given location, but only if we 1650 // find an Objective-C class name. 1651 if (TypoCorrection C = CorrectTypo( 1652 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1653 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1654 CTK_ErrorRecovery)) { 1655 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1656 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1657 Id = IDecl->getIdentifier(); 1658 } 1659 } 1660 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1661 // This routine must always return a class definition, if any. 1662 if (Def && Def->getDefinition()) 1663 Def = Def->getDefinition(); 1664 return Def; 1665 } 1666 1667 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1668 /// from S, where a non-field would be declared. This routine copes 1669 /// with the difference between C and C++ scoping rules in structs and 1670 /// unions. For example, the following code is well-formed in C but 1671 /// ill-formed in C++: 1672 /// @code 1673 /// struct S6 { 1674 /// enum { BAR } e; 1675 /// }; 1676 /// 1677 /// void test_S6() { 1678 /// struct S6 a; 1679 /// a.e = BAR; 1680 /// } 1681 /// @endcode 1682 /// For the declaration of BAR, this routine will return a different 1683 /// scope. The scope S will be the scope of the unnamed enumeration 1684 /// within S6. In C++, this routine will return the scope associated 1685 /// with S6, because the enumeration's scope is a transparent 1686 /// context but structures can contain non-field names. In C, this 1687 /// routine will return the translation unit scope, since the 1688 /// enumeration's scope is a transparent context and structures cannot 1689 /// contain non-field names. 1690 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1691 while (((S->getFlags() & Scope::DeclScope) == 0) || 1692 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1693 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1694 S = S->getParent(); 1695 return S; 1696 } 1697 1698 /// \brief Looks up the declaration of "struct objc_super" and 1699 /// saves it for later use in building builtin declaration of 1700 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1701 /// pre-existing declaration exists no action takes place. 1702 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1703 IdentifierInfo *II) { 1704 if (!II->isStr("objc_msgSendSuper")) 1705 return; 1706 ASTContext &Context = ThisSema.Context; 1707 1708 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1709 SourceLocation(), Sema::LookupTagName); 1710 ThisSema.LookupName(Result, S); 1711 if (Result.getResultKind() == LookupResult::Found) 1712 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1713 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1714 } 1715 1716 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1717 switch (Error) { 1718 case ASTContext::GE_None: 1719 return ""; 1720 case ASTContext::GE_Missing_stdio: 1721 return "stdio.h"; 1722 case ASTContext::GE_Missing_setjmp: 1723 return "setjmp.h"; 1724 case ASTContext::GE_Missing_ucontext: 1725 return "ucontext.h"; 1726 } 1727 llvm_unreachable("unhandled error kind"); 1728 } 1729 1730 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1731 /// file scope. lazily create a decl for it. ForRedeclaration is true 1732 /// if we're creating this built-in in anticipation of redeclaring the 1733 /// built-in. 1734 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1735 Scope *S, bool ForRedeclaration, 1736 SourceLocation Loc) { 1737 LookupPredefedObjCSuperType(*this, S, II); 1738 1739 ASTContext::GetBuiltinTypeError Error; 1740 QualType R = Context.GetBuiltinType(ID, Error); 1741 if (Error) { 1742 if (ForRedeclaration) 1743 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1744 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1745 return nullptr; 1746 } 1747 1748 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1749 Diag(Loc, diag::ext_implicit_lib_function_decl) 1750 << Context.BuiltinInfo.getName(ID) << R; 1751 if (Context.BuiltinInfo.getHeaderName(ID) && 1752 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1753 Diag(Loc, diag::note_include_header_or_declare) 1754 << Context.BuiltinInfo.getHeaderName(ID) 1755 << Context.BuiltinInfo.getName(ID); 1756 } 1757 1758 if (R.isNull()) 1759 return nullptr; 1760 1761 DeclContext *Parent = Context.getTranslationUnitDecl(); 1762 if (getLangOpts().CPlusPlus) { 1763 LinkageSpecDecl *CLinkageDecl = 1764 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1765 LinkageSpecDecl::lang_c, false); 1766 CLinkageDecl->setImplicit(); 1767 Parent->addDecl(CLinkageDecl); 1768 Parent = CLinkageDecl; 1769 } 1770 1771 FunctionDecl *New = FunctionDecl::Create(Context, 1772 Parent, 1773 Loc, Loc, II, R, /*TInfo=*/nullptr, 1774 SC_Extern, 1775 false, 1776 R->isFunctionProtoType()); 1777 New->setImplicit(); 1778 1779 // Create Decl objects for each parameter, adding them to the 1780 // FunctionDecl. 1781 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1782 SmallVector<ParmVarDecl*, 16> Params; 1783 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1784 ParmVarDecl *parm = 1785 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1786 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1787 SC_None, nullptr); 1788 parm->setScopeInfo(0, i); 1789 Params.push_back(parm); 1790 } 1791 New->setParams(Params); 1792 } 1793 1794 AddKnownFunctionAttributes(New); 1795 RegisterLocallyScopedExternCDecl(New, S); 1796 1797 // TUScope is the translation-unit scope to insert this function into. 1798 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1799 // relate Scopes to DeclContexts, and probably eliminate CurContext 1800 // entirely, but we're not there yet. 1801 DeclContext *SavedContext = CurContext; 1802 CurContext = Parent; 1803 PushOnScopeChains(New, TUScope); 1804 CurContext = SavedContext; 1805 return New; 1806 } 1807 1808 /// Typedef declarations don't have linkage, but they still denote the same 1809 /// entity if their types are the same. 1810 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1811 /// isSameEntity. 1812 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1813 TypedefNameDecl *Decl, 1814 LookupResult &Previous) { 1815 // This is only interesting when modules are enabled. 1816 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1817 return; 1818 1819 // Empty sets are uninteresting. 1820 if (Previous.empty()) 1821 return; 1822 1823 LookupResult::Filter Filter = Previous.makeFilter(); 1824 while (Filter.hasNext()) { 1825 NamedDecl *Old = Filter.next(); 1826 1827 // Non-hidden declarations are never ignored. 1828 if (S.isVisible(Old)) 1829 continue; 1830 1831 // Declarations of the same entity are not ignored, even if they have 1832 // different linkages. 1833 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1834 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1835 Decl->getUnderlyingType())) 1836 continue; 1837 1838 // If both declarations give a tag declaration a typedef name for linkage 1839 // purposes, then they declare the same entity. 1840 if (S.getLangOpts().CPlusPlus && 1841 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1842 Decl->getAnonDeclWithTypedefName()) 1843 continue; 1844 } 1845 1846 Filter.erase(); 1847 } 1848 1849 Filter.done(); 1850 } 1851 1852 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1853 QualType OldType; 1854 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1855 OldType = OldTypedef->getUnderlyingType(); 1856 else 1857 OldType = Context.getTypeDeclType(Old); 1858 QualType NewType = New->getUnderlyingType(); 1859 1860 if (NewType->isVariablyModifiedType()) { 1861 // Must not redefine a typedef with a variably-modified type. 1862 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1863 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1864 << Kind << NewType; 1865 if (Old->getLocation().isValid()) 1866 Diag(Old->getLocation(), diag::note_previous_definition); 1867 New->setInvalidDecl(); 1868 return true; 1869 } 1870 1871 if (OldType != NewType && 1872 !OldType->isDependentType() && 1873 !NewType->isDependentType() && 1874 !Context.hasSameType(OldType, NewType)) { 1875 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1876 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1877 << Kind << NewType << OldType; 1878 if (Old->getLocation().isValid()) 1879 Diag(Old->getLocation(), diag::note_previous_definition); 1880 New->setInvalidDecl(); 1881 return true; 1882 } 1883 return false; 1884 } 1885 1886 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1887 /// same name and scope as a previous declaration 'Old'. Figure out 1888 /// how to resolve this situation, merging decls or emitting 1889 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1890 /// 1891 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 1892 LookupResult &OldDecls) { 1893 // If the new decl is known invalid already, don't bother doing any 1894 // merging checks. 1895 if (New->isInvalidDecl()) return; 1896 1897 // Allow multiple definitions for ObjC built-in typedefs. 1898 // FIXME: Verify the underlying types are equivalent! 1899 if (getLangOpts().ObjC1) { 1900 const IdentifierInfo *TypeID = New->getIdentifier(); 1901 switch (TypeID->getLength()) { 1902 default: break; 1903 case 2: 1904 { 1905 if (!TypeID->isStr("id")) 1906 break; 1907 QualType T = New->getUnderlyingType(); 1908 if (!T->isPointerType()) 1909 break; 1910 if (!T->isVoidPointerType()) { 1911 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1912 if (!PT->isStructureType()) 1913 break; 1914 } 1915 Context.setObjCIdRedefinitionType(T); 1916 // Install the built-in type for 'id', ignoring the current definition. 1917 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1918 return; 1919 } 1920 case 5: 1921 if (!TypeID->isStr("Class")) 1922 break; 1923 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1924 // Install the built-in type for 'Class', ignoring the current definition. 1925 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1926 return; 1927 case 3: 1928 if (!TypeID->isStr("SEL")) 1929 break; 1930 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1931 // Install the built-in type for 'SEL', ignoring the current definition. 1932 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1933 return; 1934 } 1935 // Fall through - the typedef name was not a builtin type. 1936 } 1937 1938 // Verify the old decl was also a type. 1939 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1940 if (!Old) { 1941 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1942 << New->getDeclName(); 1943 1944 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1945 if (OldD->getLocation().isValid()) 1946 Diag(OldD->getLocation(), diag::note_previous_definition); 1947 1948 return New->setInvalidDecl(); 1949 } 1950 1951 // If the old declaration is invalid, just give up here. 1952 if (Old->isInvalidDecl()) 1953 return New->setInvalidDecl(); 1954 1955 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1956 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 1957 auto *NewTag = New->getAnonDeclWithTypedefName(); 1958 NamedDecl *Hidden = nullptr; 1959 if (getLangOpts().CPlusPlus && OldTag && NewTag && 1960 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 1961 !hasVisibleDefinition(OldTag, &Hidden)) { 1962 // There is a definition of this tag, but it is not visible. Use it 1963 // instead of our tag. 1964 New->setTypeForDecl(OldTD->getTypeForDecl()); 1965 if (OldTD->isModed()) 1966 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 1967 OldTD->getUnderlyingType()); 1968 else 1969 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 1970 1971 // Make the old tag definition visible. 1972 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 1973 1974 // If this was an unscoped enumeration, yank all of its enumerators 1975 // out of the scope. 1976 if (isa<EnumDecl>(NewTag)) { 1977 Scope *EnumScope = getNonFieldDeclScope(S); 1978 for (auto *D : NewTag->decls()) { 1979 auto *ED = cast<EnumConstantDecl>(D); 1980 assert(EnumScope->isDeclScope(ED)); 1981 EnumScope->RemoveDecl(ED); 1982 IdResolver.RemoveDecl(ED); 1983 ED->getLexicalDeclContext()->removeDecl(ED); 1984 } 1985 } 1986 } 1987 } 1988 1989 // If the typedef types are not identical, reject them in all languages and 1990 // with any extensions enabled. 1991 if (isIncompatibleTypedef(Old, New)) 1992 return; 1993 1994 // The types match. Link up the redeclaration chain and merge attributes if 1995 // the old declaration was a typedef. 1996 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1997 New->setPreviousDecl(Typedef); 1998 mergeDeclAttributes(New, Old); 1999 } 2000 2001 if (getLangOpts().MicrosoftExt) 2002 return; 2003 2004 if (getLangOpts().CPlusPlus) { 2005 // C++ [dcl.typedef]p2: 2006 // In a given non-class scope, a typedef specifier can be used to 2007 // redefine the name of any type declared in that scope to refer 2008 // to the type to which it already refers. 2009 if (!isa<CXXRecordDecl>(CurContext)) 2010 return; 2011 2012 // C++0x [dcl.typedef]p4: 2013 // In a given class scope, a typedef specifier can be used to redefine 2014 // any class-name declared in that scope that is not also a typedef-name 2015 // to refer to the type to which it already refers. 2016 // 2017 // This wording came in via DR424, which was a correction to the 2018 // wording in DR56, which accidentally banned code like: 2019 // 2020 // struct S { 2021 // typedef struct A { } A; 2022 // }; 2023 // 2024 // in the C++03 standard. We implement the C++0x semantics, which 2025 // allow the above but disallow 2026 // 2027 // struct S { 2028 // typedef int I; 2029 // typedef int I; 2030 // }; 2031 // 2032 // since that was the intent of DR56. 2033 if (!isa<TypedefNameDecl>(Old)) 2034 return; 2035 2036 Diag(New->getLocation(), diag::err_redefinition) 2037 << New->getDeclName(); 2038 Diag(Old->getLocation(), diag::note_previous_definition); 2039 return New->setInvalidDecl(); 2040 } 2041 2042 // Modules always permit redefinition of typedefs, as does C11. 2043 if (getLangOpts().Modules || getLangOpts().C11) 2044 return; 2045 2046 // If we have a redefinition of a typedef in C, emit a warning. This warning 2047 // is normally mapped to an error, but can be controlled with 2048 // -Wtypedef-redefinition. If either the original or the redefinition is 2049 // in a system header, don't emit this for compatibility with GCC. 2050 if (getDiagnostics().getSuppressSystemWarnings() && 2051 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2052 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2053 return; 2054 2055 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2056 << New->getDeclName(); 2057 Diag(Old->getLocation(), diag::note_previous_definition); 2058 } 2059 2060 /// DeclhasAttr - returns true if decl Declaration already has the target 2061 /// attribute. 2062 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2063 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2064 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2065 for (const auto *i : D->attrs()) 2066 if (i->getKind() == A->getKind()) { 2067 if (Ann) { 2068 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2069 return true; 2070 continue; 2071 } 2072 // FIXME: Don't hardcode this check 2073 if (OA && isa<OwnershipAttr>(i)) 2074 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2075 return true; 2076 } 2077 2078 return false; 2079 } 2080 2081 static bool isAttributeTargetADefinition(Decl *D) { 2082 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2083 return VD->isThisDeclarationADefinition(); 2084 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2085 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2086 return true; 2087 } 2088 2089 /// Merge alignment attributes from \p Old to \p New, taking into account the 2090 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2091 /// 2092 /// \return \c true if any attributes were added to \p New. 2093 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2094 // Look for alignas attributes on Old, and pick out whichever attribute 2095 // specifies the strictest alignment requirement. 2096 AlignedAttr *OldAlignasAttr = nullptr; 2097 AlignedAttr *OldStrictestAlignAttr = nullptr; 2098 unsigned OldAlign = 0; 2099 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2100 // FIXME: We have no way of representing inherited dependent alignments 2101 // in a case like: 2102 // template<int A, int B> struct alignas(A) X; 2103 // template<int A, int B> struct alignas(B) X {}; 2104 // For now, we just ignore any alignas attributes which are not on the 2105 // definition in such a case. 2106 if (I->isAlignmentDependent()) 2107 return false; 2108 2109 if (I->isAlignas()) 2110 OldAlignasAttr = I; 2111 2112 unsigned Align = I->getAlignment(S.Context); 2113 if (Align > OldAlign) { 2114 OldAlign = Align; 2115 OldStrictestAlignAttr = I; 2116 } 2117 } 2118 2119 // Look for alignas attributes on New. 2120 AlignedAttr *NewAlignasAttr = nullptr; 2121 unsigned NewAlign = 0; 2122 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2123 if (I->isAlignmentDependent()) 2124 return false; 2125 2126 if (I->isAlignas()) 2127 NewAlignasAttr = I; 2128 2129 unsigned Align = I->getAlignment(S.Context); 2130 if (Align > NewAlign) 2131 NewAlign = Align; 2132 } 2133 2134 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2135 // Both declarations have 'alignas' attributes. We require them to match. 2136 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2137 // fall short. (If two declarations both have alignas, they must both match 2138 // every definition, and so must match each other if there is a definition.) 2139 2140 // If either declaration only contains 'alignas(0)' specifiers, then it 2141 // specifies the natural alignment for the type. 2142 if (OldAlign == 0 || NewAlign == 0) { 2143 QualType Ty; 2144 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2145 Ty = VD->getType(); 2146 else 2147 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2148 2149 if (OldAlign == 0) 2150 OldAlign = S.Context.getTypeAlign(Ty); 2151 if (NewAlign == 0) 2152 NewAlign = S.Context.getTypeAlign(Ty); 2153 } 2154 2155 if (OldAlign != NewAlign) { 2156 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2157 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2158 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2159 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2160 } 2161 } 2162 2163 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2164 // C++11 [dcl.align]p6: 2165 // if any declaration of an entity has an alignment-specifier, 2166 // every defining declaration of that entity shall specify an 2167 // equivalent alignment. 2168 // C11 6.7.5/7: 2169 // If the definition of an object does not have an alignment 2170 // specifier, any other declaration of that object shall also 2171 // have no alignment specifier. 2172 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2173 << OldAlignasAttr; 2174 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2175 << OldAlignasAttr; 2176 } 2177 2178 bool AnyAdded = false; 2179 2180 // Ensure we have an attribute representing the strictest alignment. 2181 if (OldAlign > NewAlign) { 2182 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2183 Clone->setInherited(true); 2184 New->addAttr(Clone); 2185 AnyAdded = true; 2186 } 2187 2188 // Ensure we have an alignas attribute if the old declaration had one. 2189 if (OldAlignasAttr && !NewAlignasAttr && 2190 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2191 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2192 Clone->setInherited(true); 2193 New->addAttr(Clone); 2194 AnyAdded = true; 2195 } 2196 2197 return AnyAdded; 2198 } 2199 2200 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2201 const InheritableAttr *Attr, 2202 Sema::AvailabilityMergeKind AMK) { 2203 InheritableAttr *NewAttr = nullptr; 2204 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2205 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2206 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2207 AA->isImplicit(), AA->getIntroduced(), 2208 AA->getDeprecated(), 2209 AA->getObsoleted(), AA->getUnavailable(), 2210 AA->getMessage(), AA->getStrict(), 2211 AA->getReplacement(), AMK, 2212 AttrSpellingListIndex); 2213 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2214 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2215 AttrSpellingListIndex); 2216 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2217 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2218 AttrSpellingListIndex); 2219 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2220 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2221 AttrSpellingListIndex); 2222 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2223 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2224 AttrSpellingListIndex); 2225 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2226 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2227 FA->getFormatIdx(), FA->getFirstArg(), 2228 AttrSpellingListIndex); 2229 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2230 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2231 AttrSpellingListIndex); 2232 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2233 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2234 AttrSpellingListIndex, 2235 IA->getSemanticSpelling()); 2236 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2237 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2238 &S.Context.Idents.get(AA->getSpelling()), 2239 AttrSpellingListIndex); 2240 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2241 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2242 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2243 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2244 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2245 NewAttr = S.mergeInternalLinkageAttr( 2246 D, InternalLinkageA->getRange(), 2247 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2248 AttrSpellingListIndex); 2249 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2250 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2251 &S.Context.Idents.get(CommonA->getSpelling()), 2252 AttrSpellingListIndex); 2253 else if (isa<AlignedAttr>(Attr)) 2254 // AlignedAttrs are handled separately, because we need to handle all 2255 // such attributes on a declaration at the same time. 2256 NewAttr = nullptr; 2257 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2258 (AMK == Sema::AMK_Override || 2259 AMK == Sema::AMK_ProtocolImplementation)) 2260 NewAttr = nullptr; 2261 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2262 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2263 2264 if (NewAttr) { 2265 NewAttr->setInherited(true); 2266 D->addAttr(NewAttr); 2267 if (isa<MSInheritanceAttr>(NewAttr)) 2268 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2269 return true; 2270 } 2271 2272 return false; 2273 } 2274 2275 static const Decl *getDefinition(const Decl *D) { 2276 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2277 return TD->getDefinition(); 2278 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2279 const VarDecl *Def = VD->getDefinition(); 2280 if (Def) 2281 return Def; 2282 return VD->getActingDefinition(); 2283 } 2284 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2285 const FunctionDecl* Def; 2286 if (FD->isDefined(Def)) 2287 return Def; 2288 } 2289 return nullptr; 2290 } 2291 2292 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2293 for (const auto *Attribute : D->attrs()) 2294 if (Attribute->getKind() == Kind) 2295 return true; 2296 return false; 2297 } 2298 2299 /// checkNewAttributesAfterDef - If we already have a definition, check that 2300 /// there are no new attributes in this declaration. 2301 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2302 if (!New->hasAttrs()) 2303 return; 2304 2305 const Decl *Def = getDefinition(Old); 2306 if (!Def || Def == New) 2307 return; 2308 2309 AttrVec &NewAttributes = New->getAttrs(); 2310 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2311 const Attr *NewAttribute = NewAttributes[I]; 2312 2313 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2314 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2315 Sema::SkipBodyInfo SkipBody; 2316 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2317 2318 // If we're skipping this definition, drop the "alias" attribute. 2319 if (SkipBody.ShouldSkip) { 2320 NewAttributes.erase(NewAttributes.begin() + I); 2321 --E; 2322 continue; 2323 } 2324 } else { 2325 VarDecl *VD = cast<VarDecl>(New); 2326 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2327 VarDecl::TentativeDefinition 2328 ? diag::err_alias_after_tentative 2329 : diag::err_redefinition; 2330 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2331 S.Diag(Def->getLocation(), diag::note_previous_definition); 2332 VD->setInvalidDecl(); 2333 } 2334 ++I; 2335 continue; 2336 } 2337 2338 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2339 // Tentative definitions are only interesting for the alias check above. 2340 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2341 ++I; 2342 continue; 2343 } 2344 } 2345 2346 if (hasAttribute(Def, NewAttribute->getKind())) { 2347 ++I; 2348 continue; // regular attr merging will take care of validating this. 2349 } 2350 2351 if (isa<C11NoReturnAttr>(NewAttribute)) { 2352 // C's _Noreturn is allowed to be added to a function after it is defined. 2353 ++I; 2354 continue; 2355 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2356 if (AA->isAlignas()) { 2357 // C++11 [dcl.align]p6: 2358 // if any declaration of an entity has an alignment-specifier, 2359 // every defining declaration of that entity shall specify an 2360 // equivalent alignment. 2361 // C11 6.7.5/7: 2362 // If the definition of an object does not have an alignment 2363 // specifier, any other declaration of that object shall also 2364 // have no alignment specifier. 2365 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2366 << AA; 2367 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2368 << AA; 2369 NewAttributes.erase(NewAttributes.begin() + I); 2370 --E; 2371 continue; 2372 } 2373 } 2374 2375 S.Diag(NewAttribute->getLocation(), 2376 diag::warn_attribute_precede_definition); 2377 S.Diag(Def->getLocation(), diag::note_previous_definition); 2378 NewAttributes.erase(NewAttributes.begin() + I); 2379 --E; 2380 } 2381 } 2382 2383 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2384 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2385 AvailabilityMergeKind AMK) { 2386 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2387 UsedAttr *NewAttr = OldAttr->clone(Context); 2388 NewAttr->setInherited(true); 2389 New->addAttr(NewAttr); 2390 } 2391 2392 if (!Old->hasAttrs() && !New->hasAttrs()) 2393 return; 2394 2395 // Attributes declared post-definition are currently ignored. 2396 checkNewAttributesAfterDef(*this, New, Old); 2397 2398 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2399 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2400 if (OldA->getLabel() != NewA->getLabel()) { 2401 // This redeclaration changes __asm__ label. 2402 Diag(New->getLocation(), diag::err_different_asm_label); 2403 Diag(OldA->getLocation(), diag::note_previous_declaration); 2404 } 2405 } else if (Old->isUsed()) { 2406 // This redeclaration adds an __asm__ label to a declaration that has 2407 // already been ODR-used. 2408 Diag(New->getLocation(), diag::err_late_asm_label_name) 2409 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2410 } 2411 } 2412 2413 // Re-declaration cannot add abi_tag's. 2414 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2415 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2416 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2417 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2418 NewTag) == OldAbiTagAttr->tags_end()) { 2419 Diag(NewAbiTagAttr->getLocation(), 2420 diag::err_new_abi_tag_on_redeclaration) 2421 << NewTag; 2422 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2423 } 2424 } 2425 } else { 2426 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2427 Diag(Old->getLocation(), diag::note_previous_declaration); 2428 } 2429 } 2430 2431 if (!Old->hasAttrs()) 2432 return; 2433 2434 bool foundAny = New->hasAttrs(); 2435 2436 // Ensure that any moving of objects within the allocated map is done before 2437 // we process them. 2438 if (!foundAny) New->setAttrs(AttrVec()); 2439 2440 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2441 // Ignore deprecated/unavailable/availability attributes if requested. 2442 AvailabilityMergeKind LocalAMK = AMK_None; 2443 if (isa<DeprecatedAttr>(I) || 2444 isa<UnavailableAttr>(I) || 2445 isa<AvailabilityAttr>(I)) { 2446 switch (AMK) { 2447 case AMK_None: 2448 continue; 2449 2450 case AMK_Redeclaration: 2451 case AMK_Override: 2452 case AMK_ProtocolImplementation: 2453 LocalAMK = AMK; 2454 break; 2455 } 2456 } 2457 2458 // Already handled. 2459 if (isa<UsedAttr>(I)) 2460 continue; 2461 2462 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2463 foundAny = true; 2464 } 2465 2466 if (mergeAlignedAttrs(*this, New, Old)) 2467 foundAny = true; 2468 2469 if (!foundAny) New->dropAttrs(); 2470 } 2471 2472 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2473 /// to the new one. 2474 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2475 const ParmVarDecl *oldDecl, 2476 Sema &S) { 2477 // C++11 [dcl.attr.depend]p2: 2478 // The first declaration of a function shall specify the 2479 // carries_dependency attribute for its declarator-id if any declaration 2480 // of the function specifies the carries_dependency attribute. 2481 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2482 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2483 S.Diag(CDA->getLocation(), 2484 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2485 // Find the first declaration of the parameter. 2486 // FIXME: Should we build redeclaration chains for function parameters? 2487 const FunctionDecl *FirstFD = 2488 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2489 const ParmVarDecl *FirstVD = 2490 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2491 S.Diag(FirstVD->getLocation(), 2492 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2493 } 2494 2495 if (!oldDecl->hasAttrs()) 2496 return; 2497 2498 bool foundAny = newDecl->hasAttrs(); 2499 2500 // Ensure that any moving of objects within the allocated map is 2501 // done before we process them. 2502 if (!foundAny) newDecl->setAttrs(AttrVec()); 2503 2504 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2505 if (!DeclHasAttr(newDecl, I)) { 2506 InheritableAttr *newAttr = 2507 cast<InheritableParamAttr>(I->clone(S.Context)); 2508 newAttr->setInherited(true); 2509 newDecl->addAttr(newAttr); 2510 foundAny = true; 2511 } 2512 } 2513 2514 if (!foundAny) newDecl->dropAttrs(); 2515 } 2516 2517 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2518 const ParmVarDecl *OldParam, 2519 Sema &S) { 2520 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2521 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2522 if (*Oldnullability != *Newnullability) { 2523 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2524 << DiagNullabilityKind( 2525 *Newnullability, 2526 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2527 != 0)) 2528 << DiagNullabilityKind( 2529 *Oldnullability, 2530 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2531 != 0)); 2532 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2533 } 2534 } else { 2535 QualType NewT = NewParam->getType(); 2536 NewT = S.Context.getAttributedType( 2537 AttributedType::getNullabilityAttrKind(*Oldnullability), 2538 NewT, NewT); 2539 NewParam->setType(NewT); 2540 } 2541 } 2542 } 2543 2544 namespace { 2545 2546 /// Used in MergeFunctionDecl to keep track of function parameters in 2547 /// C. 2548 struct GNUCompatibleParamWarning { 2549 ParmVarDecl *OldParm; 2550 ParmVarDecl *NewParm; 2551 QualType PromotedType; 2552 }; 2553 2554 } // end anonymous namespace 2555 2556 /// getSpecialMember - get the special member enum for a method. 2557 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2558 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2559 if (Ctor->isDefaultConstructor()) 2560 return Sema::CXXDefaultConstructor; 2561 2562 if (Ctor->isCopyConstructor()) 2563 return Sema::CXXCopyConstructor; 2564 2565 if (Ctor->isMoveConstructor()) 2566 return Sema::CXXMoveConstructor; 2567 } else if (isa<CXXDestructorDecl>(MD)) { 2568 return Sema::CXXDestructor; 2569 } else if (MD->isCopyAssignmentOperator()) { 2570 return Sema::CXXCopyAssignment; 2571 } else if (MD->isMoveAssignmentOperator()) { 2572 return Sema::CXXMoveAssignment; 2573 } 2574 2575 return Sema::CXXInvalid; 2576 } 2577 2578 // Determine whether the previous declaration was a definition, implicit 2579 // declaration, or a declaration. 2580 template <typename T> 2581 static std::pair<diag::kind, SourceLocation> 2582 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2583 diag::kind PrevDiag; 2584 SourceLocation OldLocation = Old->getLocation(); 2585 if (Old->isThisDeclarationADefinition()) 2586 PrevDiag = diag::note_previous_definition; 2587 else if (Old->isImplicit()) { 2588 PrevDiag = diag::note_previous_implicit_declaration; 2589 if (OldLocation.isInvalid()) 2590 OldLocation = New->getLocation(); 2591 } else 2592 PrevDiag = diag::note_previous_declaration; 2593 return std::make_pair(PrevDiag, OldLocation); 2594 } 2595 2596 /// canRedefineFunction - checks if a function can be redefined. Currently, 2597 /// only extern inline functions can be redefined, and even then only in 2598 /// GNU89 mode. 2599 static bool canRedefineFunction(const FunctionDecl *FD, 2600 const LangOptions& LangOpts) { 2601 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2602 !LangOpts.CPlusPlus && 2603 FD->isInlineSpecified() && 2604 FD->getStorageClass() == SC_Extern); 2605 } 2606 2607 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2608 const AttributedType *AT = T->getAs<AttributedType>(); 2609 while (AT && !AT->isCallingConv()) 2610 AT = AT->getModifiedType()->getAs<AttributedType>(); 2611 return AT; 2612 } 2613 2614 template <typename T> 2615 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2616 const DeclContext *DC = Old->getDeclContext(); 2617 if (DC->isRecord()) 2618 return false; 2619 2620 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2621 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2622 return true; 2623 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2624 return true; 2625 return false; 2626 } 2627 2628 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2629 static bool isExternC(VarTemplateDecl *) { return false; } 2630 2631 /// \brief Check whether a redeclaration of an entity introduced by a 2632 /// using-declaration is valid, given that we know it's not an overload 2633 /// (nor a hidden tag declaration). 2634 template<typename ExpectedDecl> 2635 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2636 ExpectedDecl *New) { 2637 // C++11 [basic.scope.declarative]p4: 2638 // Given a set of declarations in a single declarative region, each of 2639 // which specifies the same unqualified name, 2640 // -- they shall all refer to the same entity, or all refer to functions 2641 // and function templates; or 2642 // -- exactly one declaration shall declare a class name or enumeration 2643 // name that is not a typedef name and the other declarations shall all 2644 // refer to the same variable or enumerator, or all refer to functions 2645 // and function templates; in this case the class name or enumeration 2646 // name is hidden (3.3.10). 2647 2648 // C++11 [namespace.udecl]p14: 2649 // If a function declaration in namespace scope or block scope has the 2650 // same name and the same parameter-type-list as a function introduced 2651 // by a using-declaration, and the declarations do not declare the same 2652 // function, the program is ill-formed. 2653 2654 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2655 if (Old && 2656 !Old->getDeclContext()->getRedeclContext()->Equals( 2657 New->getDeclContext()->getRedeclContext()) && 2658 !(isExternC(Old) && isExternC(New))) 2659 Old = nullptr; 2660 2661 if (!Old) { 2662 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2663 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2664 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2665 return true; 2666 } 2667 return false; 2668 } 2669 2670 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2671 const FunctionDecl *B) { 2672 assert(A->getNumParams() == B->getNumParams()); 2673 2674 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2675 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2676 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2677 if (AttrA == AttrB) 2678 return true; 2679 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2680 }; 2681 2682 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2683 } 2684 2685 /// MergeFunctionDecl - We just parsed a function 'New' from 2686 /// declarator D which has the same name and scope as a previous 2687 /// declaration 'Old'. Figure out how to resolve this situation, 2688 /// merging decls or emitting diagnostics as appropriate. 2689 /// 2690 /// In C++, New and Old must be declarations that are not 2691 /// overloaded. Use IsOverload to determine whether New and Old are 2692 /// overloaded, and to select the Old declaration that New should be 2693 /// merged with. 2694 /// 2695 /// Returns true if there was an error, false otherwise. 2696 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2697 Scope *S, bool MergeTypeWithOld) { 2698 // Verify the old decl was also a function. 2699 FunctionDecl *Old = OldD->getAsFunction(); 2700 if (!Old) { 2701 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2702 if (New->getFriendObjectKind()) { 2703 Diag(New->getLocation(), diag::err_using_decl_friend); 2704 Diag(Shadow->getTargetDecl()->getLocation(), 2705 diag::note_using_decl_target); 2706 Diag(Shadow->getUsingDecl()->getLocation(), 2707 diag::note_using_decl) << 0; 2708 return true; 2709 } 2710 2711 // Check whether the two declarations might declare the same function. 2712 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2713 return true; 2714 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2715 } else { 2716 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2717 << New->getDeclName(); 2718 Diag(OldD->getLocation(), diag::note_previous_definition); 2719 return true; 2720 } 2721 } 2722 2723 // If the old declaration is invalid, just give up here. 2724 if (Old->isInvalidDecl()) 2725 return true; 2726 2727 diag::kind PrevDiag; 2728 SourceLocation OldLocation; 2729 std::tie(PrevDiag, OldLocation) = 2730 getNoteDiagForInvalidRedeclaration(Old, New); 2731 2732 // Don't complain about this if we're in GNU89 mode and the old function 2733 // is an extern inline function. 2734 // Don't complain about specializations. They are not supposed to have 2735 // storage classes. 2736 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2737 New->getStorageClass() == SC_Static && 2738 Old->hasExternalFormalLinkage() && 2739 !New->getTemplateSpecializationInfo() && 2740 !canRedefineFunction(Old, getLangOpts())) { 2741 if (getLangOpts().MicrosoftExt) { 2742 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2743 Diag(OldLocation, PrevDiag); 2744 } else { 2745 Diag(New->getLocation(), diag::err_static_non_static) << New; 2746 Diag(OldLocation, PrevDiag); 2747 return true; 2748 } 2749 } 2750 2751 if (New->hasAttr<InternalLinkageAttr>() && 2752 !Old->hasAttr<InternalLinkageAttr>()) { 2753 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2754 << New->getDeclName(); 2755 Diag(Old->getLocation(), diag::note_previous_definition); 2756 New->dropAttr<InternalLinkageAttr>(); 2757 } 2758 2759 // If a function is first declared with a calling convention, but is later 2760 // declared or defined without one, all following decls assume the calling 2761 // convention of the first. 2762 // 2763 // It's OK if a function is first declared without a calling convention, 2764 // but is later declared or defined with the default calling convention. 2765 // 2766 // To test if either decl has an explicit calling convention, we look for 2767 // AttributedType sugar nodes on the type as written. If they are missing or 2768 // were canonicalized away, we assume the calling convention was implicit. 2769 // 2770 // Note also that we DO NOT return at this point, because we still have 2771 // other tests to run. 2772 QualType OldQType = Context.getCanonicalType(Old->getType()); 2773 QualType NewQType = Context.getCanonicalType(New->getType()); 2774 const FunctionType *OldType = cast<FunctionType>(OldQType); 2775 const FunctionType *NewType = cast<FunctionType>(NewQType); 2776 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2777 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2778 bool RequiresAdjustment = false; 2779 2780 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2781 FunctionDecl *First = Old->getFirstDecl(); 2782 const FunctionType *FT = 2783 First->getType().getCanonicalType()->castAs<FunctionType>(); 2784 FunctionType::ExtInfo FI = FT->getExtInfo(); 2785 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2786 if (!NewCCExplicit) { 2787 // Inherit the CC from the previous declaration if it was specified 2788 // there but not here. 2789 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2790 RequiresAdjustment = true; 2791 } else { 2792 // Calling conventions aren't compatible, so complain. 2793 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2794 Diag(New->getLocation(), diag::err_cconv_change) 2795 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2796 << !FirstCCExplicit 2797 << (!FirstCCExplicit ? "" : 2798 FunctionType::getNameForCallConv(FI.getCC())); 2799 2800 // Put the note on the first decl, since it is the one that matters. 2801 Diag(First->getLocation(), diag::note_previous_declaration); 2802 return true; 2803 } 2804 } 2805 2806 // FIXME: diagnose the other way around? 2807 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2808 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2809 RequiresAdjustment = true; 2810 } 2811 2812 // Merge regparm attribute. 2813 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2814 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2815 if (NewTypeInfo.getHasRegParm()) { 2816 Diag(New->getLocation(), diag::err_regparm_mismatch) 2817 << NewType->getRegParmType() 2818 << OldType->getRegParmType(); 2819 Diag(OldLocation, diag::note_previous_declaration); 2820 return true; 2821 } 2822 2823 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2824 RequiresAdjustment = true; 2825 } 2826 2827 // Merge ns_returns_retained attribute. 2828 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2829 if (NewTypeInfo.getProducesResult()) { 2830 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2831 Diag(OldLocation, diag::note_previous_declaration); 2832 return true; 2833 } 2834 2835 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2836 RequiresAdjustment = true; 2837 } 2838 2839 if (RequiresAdjustment) { 2840 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2841 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2842 New->setType(QualType(AdjustedType, 0)); 2843 NewQType = Context.getCanonicalType(New->getType()); 2844 NewType = cast<FunctionType>(NewQType); 2845 } 2846 2847 // If this redeclaration makes the function inline, we may need to add it to 2848 // UndefinedButUsed. 2849 if (!Old->isInlined() && New->isInlined() && 2850 !New->hasAttr<GNUInlineAttr>() && 2851 !getLangOpts().GNUInline && 2852 Old->isUsed(false) && 2853 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2854 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2855 SourceLocation())); 2856 2857 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2858 // about it. 2859 if (New->hasAttr<GNUInlineAttr>() && 2860 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2861 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2862 } 2863 2864 // If pass_object_size params don't match up perfectly, this isn't a valid 2865 // redeclaration. 2866 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 2867 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 2868 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 2869 << New->getDeclName(); 2870 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2871 return true; 2872 } 2873 2874 if (getLangOpts().CPlusPlus) { 2875 // (C++98 13.1p2): 2876 // Certain function declarations cannot be overloaded: 2877 // -- Function declarations that differ only in the return type 2878 // cannot be overloaded. 2879 2880 // Go back to the type source info to compare the declared return types, 2881 // per C++1y [dcl.type.auto]p13: 2882 // Redeclarations or specializations of a function or function template 2883 // with a declared return type that uses a placeholder type shall also 2884 // use that placeholder, not a deduced type. 2885 QualType OldDeclaredReturnType = 2886 (Old->getTypeSourceInfo() 2887 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2888 : OldType)->getReturnType(); 2889 QualType NewDeclaredReturnType = 2890 (New->getTypeSourceInfo() 2891 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2892 : NewType)->getReturnType(); 2893 QualType ResQT; 2894 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2895 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2896 New->isLocalExternDecl())) { 2897 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2898 OldDeclaredReturnType->isObjCObjectPointerType()) 2899 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2900 if (ResQT.isNull()) { 2901 if (New->isCXXClassMember() && New->isOutOfLine()) 2902 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2903 << New << New->getReturnTypeSourceRange(); 2904 else 2905 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2906 << New->getReturnTypeSourceRange(); 2907 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2908 << Old->getReturnTypeSourceRange(); 2909 return true; 2910 } 2911 else 2912 NewQType = ResQT; 2913 } 2914 2915 QualType OldReturnType = OldType->getReturnType(); 2916 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2917 if (OldReturnType != NewReturnType) { 2918 // If this function has a deduced return type and has already been 2919 // defined, copy the deduced value from the old declaration. 2920 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2921 if (OldAT && OldAT->isDeduced()) { 2922 New->setType( 2923 SubstAutoType(New->getType(), 2924 OldAT->isDependentType() ? Context.DependentTy 2925 : OldAT->getDeducedType())); 2926 NewQType = Context.getCanonicalType( 2927 SubstAutoType(NewQType, 2928 OldAT->isDependentType() ? Context.DependentTy 2929 : OldAT->getDeducedType())); 2930 } 2931 } 2932 2933 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2934 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2935 if (OldMethod && NewMethod) { 2936 // Preserve triviality. 2937 NewMethod->setTrivial(OldMethod->isTrivial()); 2938 2939 // MSVC allows explicit template specialization at class scope: 2940 // 2 CXXMethodDecls referring to the same function will be injected. 2941 // We don't want a redeclaration error. 2942 bool IsClassScopeExplicitSpecialization = 2943 OldMethod->isFunctionTemplateSpecialization() && 2944 NewMethod->isFunctionTemplateSpecialization(); 2945 bool isFriend = NewMethod->getFriendObjectKind(); 2946 2947 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2948 !IsClassScopeExplicitSpecialization) { 2949 // -- Member function declarations with the same name and the 2950 // same parameter types cannot be overloaded if any of them 2951 // is a static member function declaration. 2952 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2953 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2954 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2955 return true; 2956 } 2957 2958 // C++ [class.mem]p1: 2959 // [...] A member shall not be declared twice in the 2960 // member-specification, except that a nested class or member 2961 // class template can be declared and then later defined. 2962 if (ActiveTemplateInstantiations.empty()) { 2963 unsigned NewDiag; 2964 if (isa<CXXConstructorDecl>(OldMethod)) 2965 NewDiag = diag::err_constructor_redeclared; 2966 else if (isa<CXXDestructorDecl>(NewMethod)) 2967 NewDiag = diag::err_destructor_redeclared; 2968 else if (isa<CXXConversionDecl>(NewMethod)) 2969 NewDiag = diag::err_conv_function_redeclared; 2970 else 2971 NewDiag = diag::err_member_redeclared; 2972 2973 Diag(New->getLocation(), NewDiag); 2974 } else { 2975 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2976 << New << New->getType(); 2977 } 2978 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2979 return true; 2980 2981 // Complain if this is an explicit declaration of a special 2982 // member that was initially declared implicitly. 2983 // 2984 // As an exception, it's okay to befriend such methods in order 2985 // to permit the implicit constructor/destructor/operator calls. 2986 } else if (OldMethod->isImplicit()) { 2987 if (isFriend) { 2988 NewMethod->setImplicit(); 2989 } else { 2990 Diag(NewMethod->getLocation(), 2991 diag::err_definition_of_implicitly_declared_member) 2992 << New << getSpecialMember(OldMethod); 2993 return true; 2994 } 2995 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2996 Diag(NewMethod->getLocation(), 2997 diag::err_definition_of_explicitly_defaulted_member) 2998 << getSpecialMember(OldMethod); 2999 return true; 3000 } 3001 } 3002 3003 // C++11 [dcl.attr.noreturn]p1: 3004 // The first declaration of a function shall specify the noreturn 3005 // attribute if any declaration of that function specifies the noreturn 3006 // attribute. 3007 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3008 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3009 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3010 Diag(Old->getFirstDecl()->getLocation(), 3011 diag::note_noreturn_missing_first_decl); 3012 } 3013 3014 // C++11 [dcl.attr.depend]p2: 3015 // The first declaration of a function shall specify the 3016 // carries_dependency attribute for its declarator-id if any declaration 3017 // of the function specifies the carries_dependency attribute. 3018 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3019 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3020 Diag(CDA->getLocation(), 3021 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3022 Diag(Old->getFirstDecl()->getLocation(), 3023 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3024 } 3025 3026 // (C++98 8.3.5p3): 3027 // All declarations for a function shall agree exactly in both the 3028 // return type and the parameter-type-list. 3029 // We also want to respect all the extended bits except noreturn. 3030 3031 // noreturn should now match unless the old type info didn't have it. 3032 QualType OldQTypeForComparison = OldQType; 3033 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3034 assert(OldQType == QualType(OldType, 0)); 3035 const FunctionType *OldTypeForComparison 3036 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3037 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3038 assert(OldQTypeForComparison.isCanonical()); 3039 } 3040 3041 if (haveIncompatibleLanguageLinkages(Old, New)) { 3042 // As a special case, retain the language linkage from previous 3043 // declarations of a friend function as an extension. 3044 // 3045 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3046 // and is useful because there's otherwise no way to specify language 3047 // linkage within class scope. 3048 // 3049 // Check cautiously as the friend object kind isn't yet complete. 3050 if (New->getFriendObjectKind() != Decl::FOK_None) { 3051 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3052 Diag(OldLocation, PrevDiag); 3053 } else { 3054 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3055 Diag(OldLocation, PrevDiag); 3056 return true; 3057 } 3058 } 3059 3060 if (OldQTypeForComparison == NewQType) 3061 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3062 3063 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3064 New->isLocalExternDecl()) { 3065 // It's OK if we couldn't merge types for a local function declaraton 3066 // if either the old or new type is dependent. We'll merge the types 3067 // when we instantiate the function. 3068 return false; 3069 } 3070 3071 // Fall through for conflicting redeclarations and redefinitions. 3072 } 3073 3074 // C: Function types need to be compatible, not identical. This handles 3075 // duplicate function decls like "void f(int); void f(enum X);" properly. 3076 if (!getLangOpts().CPlusPlus && 3077 Context.typesAreCompatible(OldQType, NewQType)) { 3078 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3079 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3080 const FunctionProtoType *OldProto = nullptr; 3081 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3082 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3083 // The old declaration provided a function prototype, but the 3084 // new declaration does not. Merge in the prototype. 3085 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3086 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3087 NewQType = 3088 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3089 OldProto->getExtProtoInfo()); 3090 New->setType(NewQType); 3091 New->setHasInheritedPrototype(); 3092 3093 // Synthesize parameters with the same types. 3094 SmallVector<ParmVarDecl*, 16> Params; 3095 for (const auto &ParamType : OldProto->param_types()) { 3096 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3097 SourceLocation(), nullptr, 3098 ParamType, /*TInfo=*/nullptr, 3099 SC_None, nullptr); 3100 Param->setScopeInfo(0, Params.size()); 3101 Param->setImplicit(); 3102 Params.push_back(Param); 3103 } 3104 3105 New->setParams(Params); 3106 } 3107 3108 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3109 } 3110 3111 // GNU C permits a K&R definition to follow a prototype declaration 3112 // if the declared types of the parameters in the K&R definition 3113 // match the types in the prototype declaration, even when the 3114 // promoted types of the parameters from the K&R definition differ 3115 // from the types in the prototype. GCC then keeps the types from 3116 // the prototype. 3117 // 3118 // If a variadic prototype is followed by a non-variadic K&R definition, 3119 // the K&R definition becomes variadic. This is sort of an edge case, but 3120 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3121 // C99 6.9.1p8. 3122 if (!getLangOpts().CPlusPlus && 3123 Old->hasPrototype() && !New->hasPrototype() && 3124 New->getType()->getAs<FunctionProtoType>() && 3125 Old->getNumParams() == New->getNumParams()) { 3126 SmallVector<QualType, 16> ArgTypes; 3127 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3128 const FunctionProtoType *OldProto 3129 = Old->getType()->getAs<FunctionProtoType>(); 3130 const FunctionProtoType *NewProto 3131 = New->getType()->getAs<FunctionProtoType>(); 3132 3133 // Determine whether this is the GNU C extension. 3134 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3135 NewProto->getReturnType()); 3136 bool LooseCompatible = !MergedReturn.isNull(); 3137 for (unsigned Idx = 0, End = Old->getNumParams(); 3138 LooseCompatible && Idx != End; ++Idx) { 3139 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3140 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3141 if (Context.typesAreCompatible(OldParm->getType(), 3142 NewProto->getParamType(Idx))) { 3143 ArgTypes.push_back(NewParm->getType()); 3144 } else if (Context.typesAreCompatible(OldParm->getType(), 3145 NewParm->getType(), 3146 /*CompareUnqualified=*/true)) { 3147 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3148 NewProto->getParamType(Idx) }; 3149 Warnings.push_back(Warn); 3150 ArgTypes.push_back(NewParm->getType()); 3151 } else 3152 LooseCompatible = false; 3153 } 3154 3155 if (LooseCompatible) { 3156 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3157 Diag(Warnings[Warn].NewParm->getLocation(), 3158 diag::ext_param_promoted_not_compatible_with_prototype) 3159 << Warnings[Warn].PromotedType 3160 << Warnings[Warn].OldParm->getType(); 3161 if (Warnings[Warn].OldParm->getLocation().isValid()) 3162 Diag(Warnings[Warn].OldParm->getLocation(), 3163 diag::note_previous_declaration); 3164 } 3165 3166 if (MergeTypeWithOld) 3167 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3168 OldProto->getExtProtoInfo())); 3169 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3170 } 3171 3172 // Fall through to diagnose conflicting types. 3173 } 3174 3175 // A function that has already been declared has been redeclared or 3176 // defined with a different type; show an appropriate diagnostic. 3177 3178 // If the previous declaration was an implicitly-generated builtin 3179 // declaration, then at the very least we should use a specialized note. 3180 unsigned BuiltinID; 3181 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3182 // If it's actually a library-defined builtin function like 'malloc' 3183 // or 'printf', just warn about the incompatible redeclaration. 3184 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3185 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3186 Diag(OldLocation, diag::note_previous_builtin_declaration) 3187 << Old << Old->getType(); 3188 3189 // If this is a global redeclaration, just forget hereafter 3190 // about the "builtin-ness" of the function. 3191 // 3192 // Doing this for local extern declarations is problematic. If 3193 // the builtin declaration remains visible, a second invalid 3194 // local declaration will produce a hard error; if it doesn't 3195 // remain visible, a single bogus local redeclaration (which is 3196 // actually only a warning) could break all the downstream code. 3197 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3198 New->getIdentifier()->revertBuiltin(); 3199 3200 return false; 3201 } 3202 3203 PrevDiag = diag::note_previous_builtin_declaration; 3204 } 3205 3206 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3207 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3208 return true; 3209 } 3210 3211 /// \brief Completes the merge of two function declarations that are 3212 /// known to be compatible. 3213 /// 3214 /// This routine handles the merging of attributes and other 3215 /// properties of function declarations from the old declaration to 3216 /// the new declaration, once we know that New is in fact a 3217 /// redeclaration of Old. 3218 /// 3219 /// \returns false 3220 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3221 Scope *S, bool MergeTypeWithOld) { 3222 // Merge the attributes 3223 mergeDeclAttributes(New, Old); 3224 3225 // Merge "pure" flag. 3226 if (Old->isPure()) 3227 New->setPure(); 3228 3229 // Merge "used" flag. 3230 if (Old->getMostRecentDecl()->isUsed(false)) 3231 New->setIsUsed(); 3232 3233 // Merge attributes from the parameters. These can mismatch with K&R 3234 // declarations. 3235 if (New->getNumParams() == Old->getNumParams()) 3236 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3237 ParmVarDecl *NewParam = New->getParamDecl(i); 3238 ParmVarDecl *OldParam = Old->getParamDecl(i); 3239 mergeParamDeclAttributes(NewParam, OldParam, *this); 3240 mergeParamDeclTypes(NewParam, OldParam, *this); 3241 } 3242 3243 if (getLangOpts().CPlusPlus) 3244 return MergeCXXFunctionDecl(New, Old, S); 3245 3246 // Merge the function types so the we get the composite types for the return 3247 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3248 // was visible. 3249 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3250 if (!Merged.isNull() && MergeTypeWithOld) 3251 New->setType(Merged); 3252 3253 return false; 3254 } 3255 3256 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3257 ObjCMethodDecl *oldMethod) { 3258 // Merge the attributes, including deprecated/unavailable 3259 AvailabilityMergeKind MergeKind = 3260 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3261 ? AMK_ProtocolImplementation 3262 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3263 : AMK_Override; 3264 3265 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3266 3267 // Merge attributes from the parameters. 3268 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3269 oe = oldMethod->param_end(); 3270 for (ObjCMethodDecl::param_iterator 3271 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3272 ni != ne && oi != oe; ++ni, ++oi) 3273 mergeParamDeclAttributes(*ni, *oi, *this); 3274 3275 CheckObjCMethodOverride(newMethod, oldMethod); 3276 } 3277 3278 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3279 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3280 3281 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3282 ? diag::err_redefinition_different_type 3283 : diag::err_redeclaration_different_type) 3284 << New->getDeclName() << New->getType() << Old->getType(); 3285 3286 diag::kind PrevDiag; 3287 SourceLocation OldLocation; 3288 std::tie(PrevDiag, OldLocation) 3289 = getNoteDiagForInvalidRedeclaration(Old, New); 3290 S.Diag(OldLocation, PrevDiag); 3291 New->setInvalidDecl(); 3292 } 3293 3294 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3295 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3296 /// emitting diagnostics as appropriate. 3297 /// 3298 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3299 /// to here in AddInitializerToDecl. We can't check them before the initializer 3300 /// is attached. 3301 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3302 bool MergeTypeWithOld) { 3303 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3304 return; 3305 3306 QualType MergedT; 3307 if (getLangOpts().CPlusPlus) { 3308 if (New->getType()->isUndeducedType()) { 3309 // We don't know what the new type is until the initializer is attached. 3310 return; 3311 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3312 // These could still be something that needs exception specs checked. 3313 return MergeVarDeclExceptionSpecs(New, Old); 3314 } 3315 // C++ [basic.link]p10: 3316 // [...] the types specified by all declarations referring to a given 3317 // object or function shall be identical, except that declarations for an 3318 // array object can specify array types that differ by the presence or 3319 // absence of a major array bound (8.3.4). 3320 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3321 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3322 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3323 3324 // We are merging a variable declaration New into Old. If it has an array 3325 // bound, and that bound differs from Old's bound, we should diagnose the 3326 // mismatch. 3327 if (!NewArray->isIncompleteArrayType()) { 3328 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3329 PrevVD = PrevVD->getPreviousDecl()) { 3330 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3331 if (PrevVDTy->isIncompleteArrayType()) 3332 continue; 3333 3334 if (!Context.hasSameType(NewArray, PrevVDTy)) 3335 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3336 } 3337 } 3338 3339 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3340 if (Context.hasSameType(OldArray->getElementType(), 3341 NewArray->getElementType())) 3342 MergedT = New->getType(); 3343 } 3344 // FIXME: Check visibility. New is hidden but has a complete type. If New 3345 // has no array bound, it should not inherit one from Old, if Old is not 3346 // visible. 3347 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3348 if (Context.hasSameType(OldArray->getElementType(), 3349 NewArray->getElementType())) 3350 MergedT = Old->getType(); 3351 } 3352 } 3353 else if (New->getType()->isObjCObjectPointerType() && 3354 Old->getType()->isObjCObjectPointerType()) { 3355 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3356 Old->getType()); 3357 } 3358 } else { 3359 // C 6.2.7p2: 3360 // All declarations that refer to the same object or function shall have 3361 // compatible type. 3362 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3363 } 3364 if (MergedT.isNull()) { 3365 // It's OK if we couldn't merge types if either type is dependent, for a 3366 // block-scope variable. In other cases (static data members of class 3367 // templates, variable templates, ...), we require the types to be 3368 // equivalent. 3369 // FIXME: The C++ standard doesn't say anything about this. 3370 if ((New->getType()->isDependentType() || 3371 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3372 // If the old type was dependent, we can't merge with it, so the new type 3373 // becomes dependent for now. We'll reproduce the original type when we 3374 // instantiate the TypeSourceInfo for the variable. 3375 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3376 New->setType(Context.DependentTy); 3377 return; 3378 } 3379 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3380 } 3381 3382 // Don't actually update the type on the new declaration if the old 3383 // declaration was an extern declaration in a different scope. 3384 if (MergeTypeWithOld) 3385 New->setType(MergedT); 3386 } 3387 3388 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3389 LookupResult &Previous) { 3390 // C11 6.2.7p4: 3391 // For an identifier with internal or external linkage declared 3392 // in a scope in which a prior declaration of that identifier is 3393 // visible, if the prior declaration specifies internal or 3394 // external linkage, the type of the identifier at the later 3395 // declaration becomes the composite type. 3396 // 3397 // If the variable isn't visible, we do not merge with its type. 3398 if (Previous.isShadowed()) 3399 return false; 3400 3401 if (S.getLangOpts().CPlusPlus) { 3402 // C++11 [dcl.array]p3: 3403 // If there is a preceding declaration of the entity in the same 3404 // scope in which the bound was specified, an omitted array bound 3405 // is taken to be the same as in that earlier declaration. 3406 return NewVD->isPreviousDeclInSameBlockScope() || 3407 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3408 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3409 } else { 3410 // If the old declaration was function-local, don't merge with its 3411 // type unless we're in the same function. 3412 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3413 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3414 } 3415 } 3416 3417 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3418 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3419 /// situation, merging decls or emitting diagnostics as appropriate. 3420 /// 3421 /// Tentative definition rules (C99 6.9.2p2) are checked by 3422 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3423 /// definitions here, since the initializer hasn't been attached. 3424 /// 3425 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3426 // If the new decl is already invalid, don't do any other checking. 3427 if (New->isInvalidDecl()) 3428 return; 3429 3430 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3431 return; 3432 3433 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3434 3435 // Verify the old decl was also a variable or variable template. 3436 VarDecl *Old = nullptr; 3437 VarTemplateDecl *OldTemplate = nullptr; 3438 if (Previous.isSingleResult()) { 3439 if (NewTemplate) { 3440 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3441 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3442 3443 if (auto *Shadow = 3444 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3445 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3446 return New->setInvalidDecl(); 3447 } else { 3448 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3449 3450 if (auto *Shadow = 3451 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3452 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3453 return New->setInvalidDecl(); 3454 } 3455 } 3456 if (!Old) { 3457 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3458 << New->getDeclName(); 3459 Diag(Previous.getRepresentativeDecl()->getLocation(), 3460 diag::note_previous_definition); 3461 return New->setInvalidDecl(); 3462 } 3463 3464 // Ensure the template parameters are compatible. 3465 if (NewTemplate && 3466 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3467 OldTemplate->getTemplateParameters(), 3468 /*Complain=*/true, TPL_TemplateMatch)) 3469 return New->setInvalidDecl(); 3470 3471 // C++ [class.mem]p1: 3472 // A member shall not be declared twice in the member-specification [...] 3473 // 3474 // Here, we need only consider static data members. 3475 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3476 Diag(New->getLocation(), diag::err_duplicate_member) 3477 << New->getIdentifier(); 3478 Diag(Old->getLocation(), diag::note_previous_declaration); 3479 New->setInvalidDecl(); 3480 } 3481 3482 mergeDeclAttributes(New, Old); 3483 // Warn if an already-declared variable is made a weak_import in a subsequent 3484 // declaration 3485 if (New->hasAttr<WeakImportAttr>() && 3486 Old->getStorageClass() == SC_None && 3487 !Old->hasAttr<WeakImportAttr>()) { 3488 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3489 Diag(Old->getLocation(), diag::note_previous_definition); 3490 // Remove weak_import attribute on new declaration. 3491 New->dropAttr<WeakImportAttr>(); 3492 } 3493 3494 if (New->hasAttr<InternalLinkageAttr>() && 3495 !Old->hasAttr<InternalLinkageAttr>()) { 3496 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3497 << New->getDeclName(); 3498 Diag(Old->getLocation(), diag::note_previous_definition); 3499 New->dropAttr<InternalLinkageAttr>(); 3500 } 3501 3502 // Merge the types. 3503 VarDecl *MostRecent = Old->getMostRecentDecl(); 3504 if (MostRecent != Old) { 3505 MergeVarDeclTypes(New, MostRecent, 3506 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3507 if (New->isInvalidDecl()) 3508 return; 3509 } 3510 3511 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3512 if (New->isInvalidDecl()) 3513 return; 3514 3515 diag::kind PrevDiag; 3516 SourceLocation OldLocation; 3517 std::tie(PrevDiag, OldLocation) = 3518 getNoteDiagForInvalidRedeclaration(Old, New); 3519 3520 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3521 if (New->getStorageClass() == SC_Static && 3522 !New->isStaticDataMember() && 3523 Old->hasExternalFormalLinkage()) { 3524 if (getLangOpts().MicrosoftExt) { 3525 Diag(New->getLocation(), diag::ext_static_non_static) 3526 << New->getDeclName(); 3527 Diag(OldLocation, PrevDiag); 3528 } else { 3529 Diag(New->getLocation(), diag::err_static_non_static) 3530 << New->getDeclName(); 3531 Diag(OldLocation, PrevDiag); 3532 return New->setInvalidDecl(); 3533 } 3534 } 3535 // C99 6.2.2p4: 3536 // For an identifier declared with the storage-class specifier 3537 // extern in a scope in which a prior declaration of that 3538 // identifier is visible,23) if the prior declaration specifies 3539 // internal or external linkage, the linkage of the identifier at 3540 // the later declaration is the same as the linkage specified at 3541 // the prior declaration. If no prior declaration is visible, or 3542 // if the prior declaration specifies no linkage, then the 3543 // identifier has external linkage. 3544 if (New->hasExternalStorage() && Old->hasLinkage()) 3545 /* Okay */; 3546 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3547 !New->isStaticDataMember() && 3548 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3549 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3550 Diag(OldLocation, PrevDiag); 3551 return New->setInvalidDecl(); 3552 } 3553 3554 // Check if extern is followed by non-extern and vice-versa. 3555 if (New->hasExternalStorage() && 3556 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3557 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3558 Diag(OldLocation, PrevDiag); 3559 return New->setInvalidDecl(); 3560 } 3561 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3562 !New->hasExternalStorage()) { 3563 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3564 Diag(OldLocation, PrevDiag); 3565 return New->setInvalidDecl(); 3566 } 3567 3568 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3569 3570 // FIXME: The test for external storage here seems wrong? We still 3571 // need to check for mismatches. 3572 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3573 // Don't complain about out-of-line definitions of static members. 3574 !(Old->getLexicalDeclContext()->isRecord() && 3575 !New->getLexicalDeclContext()->isRecord())) { 3576 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3577 Diag(OldLocation, PrevDiag); 3578 return New->setInvalidDecl(); 3579 } 3580 3581 if (New->getTLSKind() != Old->getTLSKind()) { 3582 if (!Old->getTLSKind()) { 3583 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3584 Diag(OldLocation, PrevDiag); 3585 } else if (!New->getTLSKind()) { 3586 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3587 Diag(OldLocation, PrevDiag); 3588 } else { 3589 // Do not allow redeclaration to change the variable between requiring 3590 // static and dynamic initialization. 3591 // FIXME: GCC allows this, but uses the TLS keyword on the first 3592 // declaration to determine the kind. Do we need to be compatible here? 3593 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3594 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3595 Diag(OldLocation, PrevDiag); 3596 } 3597 } 3598 3599 // C++ doesn't have tentative definitions, so go right ahead and check here. 3600 VarDecl *Def; 3601 if (getLangOpts().CPlusPlus && 3602 New->isThisDeclarationADefinition() == VarDecl::Definition && 3603 (Def = Old->getDefinition())) { 3604 NamedDecl *Hidden = nullptr; 3605 if (!hasVisibleDefinition(Def, &Hidden) && 3606 (New->getFormalLinkage() == InternalLinkage || 3607 New->getDescribedVarTemplate() || 3608 New->getNumTemplateParameterLists() || 3609 New->getDeclContext()->isDependentContext())) { 3610 // The previous definition is hidden, and multiple definitions are 3611 // permitted (in separate TUs). Form another definition of it. 3612 } else { 3613 Diag(New->getLocation(), diag::err_redefinition) << New; 3614 Diag(Def->getLocation(), diag::note_previous_definition); 3615 New->setInvalidDecl(); 3616 return; 3617 } 3618 } 3619 3620 if (haveIncompatibleLanguageLinkages(Old, New)) { 3621 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3622 Diag(OldLocation, PrevDiag); 3623 New->setInvalidDecl(); 3624 return; 3625 } 3626 3627 // Merge "used" flag. 3628 if (Old->getMostRecentDecl()->isUsed(false)) 3629 New->setIsUsed(); 3630 3631 // Keep a chain of previous declarations. 3632 New->setPreviousDecl(Old); 3633 if (NewTemplate) 3634 NewTemplate->setPreviousDecl(OldTemplate); 3635 3636 // Inherit access appropriately. 3637 New->setAccess(Old->getAccess()); 3638 if (NewTemplate) 3639 NewTemplate->setAccess(New->getAccess()); 3640 } 3641 3642 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3643 /// no declarator (e.g. "struct foo;") is parsed. 3644 Decl * 3645 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3646 RecordDecl *&AnonRecord) { 3647 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3648 AnonRecord); 3649 } 3650 3651 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3652 // disambiguate entities defined in different scopes. 3653 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3654 // compatibility. 3655 // We will pick our mangling number depending on which version of MSVC is being 3656 // targeted. 3657 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3658 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3659 ? S->getMSCurManglingNumber() 3660 : S->getMSLastManglingNumber(); 3661 } 3662 3663 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3664 if (!Context.getLangOpts().CPlusPlus) 3665 return; 3666 3667 if (isa<CXXRecordDecl>(Tag->getParent())) { 3668 // If this tag is the direct child of a class, number it if 3669 // it is anonymous. 3670 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3671 return; 3672 MangleNumberingContext &MCtx = 3673 Context.getManglingNumberContext(Tag->getParent()); 3674 Context.setManglingNumber( 3675 Tag, MCtx.getManglingNumber( 3676 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3677 return; 3678 } 3679 3680 // If this tag isn't a direct child of a class, number it if it is local. 3681 Decl *ManglingContextDecl; 3682 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3683 Tag->getDeclContext(), ManglingContextDecl)) { 3684 Context.setManglingNumber( 3685 Tag, MCtx->getManglingNumber( 3686 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3687 } 3688 } 3689 3690 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3691 TypedefNameDecl *NewTD) { 3692 if (TagFromDeclSpec->isInvalidDecl()) 3693 return; 3694 3695 // Do nothing if the tag already has a name for linkage purposes. 3696 if (TagFromDeclSpec->hasNameForLinkage()) 3697 return; 3698 3699 // A well-formed anonymous tag must always be a TUK_Definition. 3700 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3701 3702 // The type must match the tag exactly; no qualifiers allowed. 3703 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3704 Context.getTagDeclType(TagFromDeclSpec))) { 3705 if (getLangOpts().CPlusPlus) 3706 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3707 return; 3708 } 3709 3710 // If we've already computed linkage for the anonymous tag, then 3711 // adding a typedef name for the anonymous decl can change that 3712 // linkage, which might be a serious problem. Diagnose this as 3713 // unsupported and ignore the typedef name. TODO: we should 3714 // pursue this as a language defect and establish a formal rule 3715 // for how to handle it. 3716 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3717 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3718 3719 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3720 tagLoc = getLocForEndOfToken(tagLoc); 3721 3722 llvm::SmallString<40> textToInsert; 3723 textToInsert += ' '; 3724 textToInsert += NewTD->getIdentifier()->getName(); 3725 Diag(tagLoc, diag::note_typedef_changes_linkage) 3726 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3727 return; 3728 } 3729 3730 // Otherwise, set this is the anon-decl typedef for the tag. 3731 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3732 } 3733 3734 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3735 switch (T) { 3736 case DeclSpec::TST_class: 3737 return 0; 3738 case DeclSpec::TST_struct: 3739 return 1; 3740 case DeclSpec::TST_interface: 3741 return 2; 3742 case DeclSpec::TST_union: 3743 return 3; 3744 case DeclSpec::TST_enum: 3745 return 4; 3746 default: 3747 llvm_unreachable("unexpected type specifier"); 3748 } 3749 } 3750 3751 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3752 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3753 /// parameters to cope with template friend declarations. 3754 Decl * 3755 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3756 MultiTemplateParamsArg TemplateParams, 3757 bool IsExplicitInstantiation, 3758 RecordDecl *&AnonRecord) { 3759 Decl *TagD = nullptr; 3760 TagDecl *Tag = nullptr; 3761 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3762 DS.getTypeSpecType() == DeclSpec::TST_struct || 3763 DS.getTypeSpecType() == DeclSpec::TST_interface || 3764 DS.getTypeSpecType() == DeclSpec::TST_union || 3765 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3766 TagD = DS.getRepAsDecl(); 3767 3768 if (!TagD) // We probably had an error 3769 return nullptr; 3770 3771 // Note that the above type specs guarantee that the 3772 // type rep is a Decl, whereas in many of the others 3773 // it's a Type. 3774 if (isa<TagDecl>(TagD)) 3775 Tag = cast<TagDecl>(TagD); 3776 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3777 Tag = CTD->getTemplatedDecl(); 3778 } 3779 3780 if (Tag) { 3781 handleTagNumbering(Tag, S); 3782 Tag->setFreeStanding(); 3783 if (Tag->isInvalidDecl()) 3784 return Tag; 3785 } 3786 3787 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3788 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3789 // or incomplete types shall not be restrict-qualified." 3790 if (TypeQuals & DeclSpec::TQ_restrict) 3791 Diag(DS.getRestrictSpecLoc(), 3792 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3793 << DS.getSourceRange(); 3794 } 3795 3796 if (DS.isConstexprSpecified()) { 3797 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3798 // and definitions of functions and variables. 3799 if (Tag) 3800 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3801 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3802 else 3803 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3804 // Don't emit warnings after this error. 3805 return TagD; 3806 } 3807 3808 if (DS.isConceptSpecified()) { 3809 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3810 // either a function concept and its definition or a variable concept and 3811 // its initializer. 3812 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3813 return TagD; 3814 } 3815 3816 DiagnoseFunctionSpecifiers(DS); 3817 3818 if (DS.isFriendSpecified()) { 3819 // If we're dealing with a decl but not a TagDecl, assume that 3820 // whatever routines created it handled the friendship aspect. 3821 if (TagD && !Tag) 3822 return nullptr; 3823 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3824 } 3825 3826 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3827 bool IsExplicitSpecialization = 3828 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3829 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3830 !IsExplicitInstantiation && !IsExplicitSpecialization && 3831 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 3832 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3833 // nested-name-specifier unless it is an explicit instantiation 3834 // or an explicit specialization. 3835 // 3836 // FIXME: We allow class template partial specializations here too, per the 3837 // obvious intent of DR1819. 3838 // 3839 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3840 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3841 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 3842 return nullptr; 3843 } 3844 3845 // Track whether this decl-specifier declares anything. 3846 bool DeclaresAnything = true; 3847 3848 // Handle anonymous struct definitions. 3849 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3850 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3851 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3852 if (getLangOpts().CPlusPlus || 3853 Record->getDeclContext()->isRecord()) { 3854 // If CurContext is a DeclContext that can contain statements, 3855 // RecursiveASTVisitor won't visit the decls that 3856 // BuildAnonymousStructOrUnion() will put into CurContext. 3857 // Also store them here so that they can be part of the 3858 // DeclStmt that gets created in this case. 3859 // FIXME: Also return the IndirectFieldDecls created by 3860 // BuildAnonymousStructOr union, for the same reason? 3861 if (CurContext->isFunctionOrMethod()) 3862 AnonRecord = Record; 3863 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3864 Context.getPrintingPolicy()); 3865 } 3866 3867 DeclaresAnything = false; 3868 } 3869 } 3870 3871 // C11 6.7.2.1p2: 3872 // A struct-declaration that does not declare an anonymous structure or 3873 // anonymous union shall contain a struct-declarator-list. 3874 // 3875 // This rule also existed in C89 and C99; the grammar for struct-declaration 3876 // did not permit a struct-declaration without a struct-declarator-list. 3877 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3878 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3879 // Check for Microsoft C extension: anonymous struct/union member. 3880 // Handle 2 kinds of anonymous struct/union: 3881 // struct STRUCT; 3882 // union UNION; 3883 // and 3884 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3885 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3886 if ((Tag && Tag->getDeclName()) || 3887 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3888 RecordDecl *Record = nullptr; 3889 if (Tag) 3890 Record = dyn_cast<RecordDecl>(Tag); 3891 else if (const RecordType *RT = 3892 DS.getRepAsType().get()->getAsStructureType()) 3893 Record = RT->getDecl(); 3894 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3895 Record = UT->getDecl(); 3896 3897 if (Record && getLangOpts().MicrosoftExt) { 3898 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3899 << Record->isUnion() << DS.getSourceRange(); 3900 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3901 } 3902 3903 DeclaresAnything = false; 3904 } 3905 } 3906 3907 // Skip all the checks below if we have a type error. 3908 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3909 (TagD && TagD->isInvalidDecl())) 3910 return TagD; 3911 3912 if (getLangOpts().CPlusPlus && 3913 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3914 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3915 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3916 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3917 DeclaresAnything = false; 3918 3919 if (!DS.isMissingDeclaratorOk()) { 3920 // Customize diagnostic for a typedef missing a name. 3921 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3922 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3923 << DS.getSourceRange(); 3924 else 3925 DeclaresAnything = false; 3926 } 3927 3928 if (DS.isModulePrivateSpecified() && 3929 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3930 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3931 << Tag->getTagKind() 3932 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3933 3934 ActOnDocumentableDecl(TagD); 3935 3936 // C 6.7/2: 3937 // A declaration [...] shall declare at least a declarator [...], a tag, 3938 // or the members of an enumeration. 3939 // C++ [dcl.dcl]p3: 3940 // [If there are no declarators], and except for the declaration of an 3941 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3942 // names into the program, or shall redeclare a name introduced by a 3943 // previous declaration. 3944 if (!DeclaresAnything) { 3945 // In C, we allow this as a (popular) extension / bug. Don't bother 3946 // producing further diagnostics for redundant qualifiers after this. 3947 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3948 return TagD; 3949 } 3950 3951 // C++ [dcl.stc]p1: 3952 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3953 // init-declarator-list of the declaration shall not be empty. 3954 // C++ [dcl.fct.spec]p1: 3955 // If a cv-qualifier appears in a decl-specifier-seq, the 3956 // init-declarator-list of the declaration shall not be empty. 3957 // 3958 // Spurious qualifiers here appear to be valid in C. 3959 unsigned DiagID = diag::warn_standalone_specifier; 3960 if (getLangOpts().CPlusPlus) 3961 DiagID = diag::ext_standalone_specifier; 3962 3963 // Note that a linkage-specification sets a storage class, but 3964 // 'extern "C" struct foo;' is actually valid and not theoretically 3965 // useless. 3966 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3967 if (SCS == DeclSpec::SCS_mutable) 3968 // Since mutable is not a viable storage class specifier in C, there is 3969 // no reason to treat it as an extension. Instead, diagnose as an error. 3970 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3971 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3972 Diag(DS.getStorageClassSpecLoc(), DiagID) 3973 << DeclSpec::getSpecifierName(SCS); 3974 } 3975 3976 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3977 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3978 << DeclSpec::getSpecifierName(TSCS); 3979 if (DS.getTypeQualifiers()) { 3980 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3981 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3982 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3983 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3984 // Restrict is covered above. 3985 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3986 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3987 } 3988 3989 // Warn about ignored type attributes, for example: 3990 // __attribute__((aligned)) struct A; 3991 // Attributes should be placed after tag to apply to type declaration. 3992 if (!DS.getAttributes().empty()) { 3993 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3994 if (TypeSpecType == DeclSpec::TST_class || 3995 TypeSpecType == DeclSpec::TST_struct || 3996 TypeSpecType == DeclSpec::TST_interface || 3997 TypeSpecType == DeclSpec::TST_union || 3998 TypeSpecType == DeclSpec::TST_enum) { 3999 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4000 attrs = attrs->getNext()) 4001 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4002 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4003 } 4004 } 4005 4006 return TagD; 4007 } 4008 4009 /// We are trying to inject an anonymous member into the given scope; 4010 /// check if there's an existing declaration that can't be overloaded. 4011 /// 4012 /// \return true if this is a forbidden redeclaration 4013 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4014 Scope *S, 4015 DeclContext *Owner, 4016 DeclarationName Name, 4017 SourceLocation NameLoc, 4018 bool IsUnion) { 4019 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4020 Sema::ForRedeclaration); 4021 if (!SemaRef.LookupName(R, S)) return false; 4022 4023 // Pick a representative declaration. 4024 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4025 assert(PrevDecl && "Expected a non-null Decl"); 4026 4027 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4028 return false; 4029 4030 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4031 << IsUnion << Name; 4032 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4033 4034 return true; 4035 } 4036 4037 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4038 /// anonymous struct or union AnonRecord into the owning context Owner 4039 /// and scope S. This routine will be invoked just after we realize 4040 /// that an unnamed union or struct is actually an anonymous union or 4041 /// struct, e.g., 4042 /// 4043 /// @code 4044 /// union { 4045 /// int i; 4046 /// float f; 4047 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4048 /// // f into the surrounding scope.x 4049 /// @endcode 4050 /// 4051 /// This routine is recursive, injecting the names of nested anonymous 4052 /// structs/unions into the owning context and scope as well. 4053 static bool 4054 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4055 RecordDecl *AnonRecord, AccessSpecifier AS, 4056 SmallVectorImpl<NamedDecl *> &Chaining) { 4057 bool Invalid = false; 4058 4059 // Look every FieldDecl and IndirectFieldDecl with a name. 4060 for (auto *D : AnonRecord->decls()) { 4061 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4062 cast<NamedDecl>(D)->getDeclName()) { 4063 ValueDecl *VD = cast<ValueDecl>(D); 4064 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4065 VD->getLocation(), 4066 AnonRecord->isUnion())) { 4067 // C++ [class.union]p2: 4068 // The names of the members of an anonymous union shall be 4069 // distinct from the names of any other entity in the 4070 // scope in which the anonymous union is declared. 4071 Invalid = true; 4072 } else { 4073 // C++ [class.union]p2: 4074 // For the purpose of name lookup, after the anonymous union 4075 // definition, the members of the anonymous union are 4076 // considered to have been defined in the scope in which the 4077 // anonymous union is declared. 4078 unsigned OldChainingSize = Chaining.size(); 4079 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4080 Chaining.append(IF->chain_begin(), IF->chain_end()); 4081 else 4082 Chaining.push_back(VD); 4083 4084 assert(Chaining.size() >= 2); 4085 NamedDecl **NamedChain = 4086 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4087 for (unsigned i = 0; i < Chaining.size(); i++) 4088 NamedChain[i] = Chaining[i]; 4089 4090 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4091 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4092 VD->getType(), NamedChain, Chaining.size()); 4093 4094 for (const auto *Attr : VD->attrs()) 4095 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4096 4097 IndirectField->setAccess(AS); 4098 IndirectField->setImplicit(); 4099 SemaRef.PushOnScopeChains(IndirectField, S); 4100 4101 // That includes picking up the appropriate access specifier. 4102 if (AS != AS_none) IndirectField->setAccess(AS); 4103 4104 Chaining.resize(OldChainingSize); 4105 } 4106 } 4107 } 4108 4109 return Invalid; 4110 } 4111 4112 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4113 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4114 /// illegal input values are mapped to SC_None. 4115 static StorageClass 4116 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4117 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4118 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4119 "Parser allowed 'typedef' as storage class VarDecl."); 4120 switch (StorageClassSpec) { 4121 case DeclSpec::SCS_unspecified: return SC_None; 4122 case DeclSpec::SCS_extern: 4123 if (DS.isExternInLinkageSpec()) 4124 return SC_None; 4125 return SC_Extern; 4126 case DeclSpec::SCS_static: return SC_Static; 4127 case DeclSpec::SCS_auto: return SC_Auto; 4128 case DeclSpec::SCS_register: return SC_Register; 4129 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4130 // Illegal SCSs map to None: error reporting is up to the caller. 4131 case DeclSpec::SCS_mutable: // Fall through. 4132 case DeclSpec::SCS_typedef: return SC_None; 4133 } 4134 llvm_unreachable("unknown storage class specifier"); 4135 } 4136 4137 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4138 assert(Record->hasInClassInitializer()); 4139 4140 for (const auto *I : Record->decls()) { 4141 const auto *FD = dyn_cast<FieldDecl>(I); 4142 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4143 FD = IFD->getAnonField(); 4144 if (FD && FD->hasInClassInitializer()) 4145 return FD->getLocation(); 4146 } 4147 4148 llvm_unreachable("couldn't find in-class initializer"); 4149 } 4150 4151 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4152 SourceLocation DefaultInitLoc) { 4153 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4154 return; 4155 4156 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4157 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4158 } 4159 4160 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4161 CXXRecordDecl *AnonUnion) { 4162 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4163 return; 4164 4165 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4166 } 4167 4168 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4169 /// anonymous structure or union. Anonymous unions are a C++ feature 4170 /// (C++ [class.union]) and a C11 feature; anonymous structures 4171 /// are a C11 feature and GNU C++ extension. 4172 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4173 AccessSpecifier AS, 4174 RecordDecl *Record, 4175 const PrintingPolicy &Policy) { 4176 DeclContext *Owner = Record->getDeclContext(); 4177 4178 // Diagnose whether this anonymous struct/union is an extension. 4179 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4180 Diag(Record->getLocation(), diag::ext_anonymous_union); 4181 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4182 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4183 else if (!Record->isUnion() && !getLangOpts().C11) 4184 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4185 4186 // C and C++ require different kinds of checks for anonymous 4187 // structs/unions. 4188 bool Invalid = false; 4189 if (getLangOpts().CPlusPlus) { 4190 const char *PrevSpec = nullptr; 4191 unsigned DiagID; 4192 if (Record->isUnion()) { 4193 // C++ [class.union]p6: 4194 // Anonymous unions declared in a named namespace or in the 4195 // global namespace shall be declared static. 4196 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4197 (isa<TranslationUnitDecl>(Owner) || 4198 (isa<NamespaceDecl>(Owner) && 4199 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4200 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4201 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4202 4203 // Recover by adding 'static'. 4204 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4205 PrevSpec, DiagID, Policy); 4206 } 4207 // C++ [class.union]p6: 4208 // A storage class is not allowed in a declaration of an 4209 // anonymous union in a class scope. 4210 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4211 isa<RecordDecl>(Owner)) { 4212 Diag(DS.getStorageClassSpecLoc(), 4213 diag::err_anonymous_union_with_storage_spec) 4214 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4215 4216 // Recover by removing the storage specifier. 4217 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4218 SourceLocation(), 4219 PrevSpec, DiagID, Context.getPrintingPolicy()); 4220 } 4221 } 4222 4223 // Ignore const/volatile/restrict qualifiers. 4224 if (DS.getTypeQualifiers()) { 4225 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4226 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4227 << Record->isUnion() << "const" 4228 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4229 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4230 Diag(DS.getVolatileSpecLoc(), 4231 diag::ext_anonymous_struct_union_qualified) 4232 << Record->isUnion() << "volatile" 4233 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4234 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4235 Diag(DS.getRestrictSpecLoc(), 4236 diag::ext_anonymous_struct_union_qualified) 4237 << Record->isUnion() << "restrict" 4238 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4239 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4240 Diag(DS.getAtomicSpecLoc(), 4241 diag::ext_anonymous_struct_union_qualified) 4242 << Record->isUnion() << "_Atomic" 4243 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4244 4245 DS.ClearTypeQualifiers(); 4246 } 4247 4248 // C++ [class.union]p2: 4249 // The member-specification of an anonymous union shall only 4250 // define non-static data members. [Note: nested types and 4251 // functions cannot be declared within an anonymous union. ] 4252 for (auto *Mem : Record->decls()) { 4253 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4254 // C++ [class.union]p3: 4255 // An anonymous union shall not have private or protected 4256 // members (clause 11). 4257 assert(FD->getAccess() != AS_none); 4258 if (FD->getAccess() != AS_public) { 4259 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4260 << Record->isUnion() << (FD->getAccess() == AS_protected); 4261 Invalid = true; 4262 } 4263 4264 // C++ [class.union]p1 4265 // An object of a class with a non-trivial constructor, a non-trivial 4266 // copy constructor, a non-trivial destructor, or a non-trivial copy 4267 // assignment operator cannot be a member of a union, nor can an 4268 // array of such objects. 4269 if (CheckNontrivialField(FD)) 4270 Invalid = true; 4271 } else if (Mem->isImplicit()) { 4272 // Any implicit members are fine. 4273 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4274 // This is a type that showed up in an 4275 // elaborated-type-specifier inside the anonymous struct or 4276 // union, but which actually declares a type outside of the 4277 // anonymous struct or union. It's okay. 4278 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4279 if (!MemRecord->isAnonymousStructOrUnion() && 4280 MemRecord->getDeclName()) { 4281 // Visual C++ allows type definition in anonymous struct or union. 4282 if (getLangOpts().MicrosoftExt) 4283 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4284 << Record->isUnion(); 4285 else { 4286 // This is a nested type declaration. 4287 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4288 << Record->isUnion(); 4289 Invalid = true; 4290 } 4291 } else { 4292 // This is an anonymous type definition within another anonymous type. 4293 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4294 // not part of standard C++. 4295 Diag(MemRecord->getLocation(), 4296 diag::ext_anonymous_record_with_anonymous_type) 4297 << Record->isUnion(); 4298 } 4299 } else if (isa<AccessSpecDecl>(Mem)) { 4300 // Any access specifier is fine. 4301 } else if (isa<StaticAssertDecl>(Mem)) { 4302 // In C++1z, static_assert declarations are also fine. 4303 } else { 4304 // We have something that isn't a non-static data 4305 // member. Complain about it. 4306 unsigned DK = diag::err_anonymous_record_bad_member; 4307 if (isa<TypeDecl>(Mem)) 4308 DK = diag::err_anonymous_record_with_type; 4309 else if (isa<FunctionDecl>(Mem)) 4310 DK = diag::err_anonymous_record_with_function; 4311 else if (isa<VarDecl>(Mem)) 4312 DK = diag::err_anonymous_record_with_static; 4313 4314 // Visual C++ allows type definition in anonymous struct or union. 4315 if (getLangOpts().MicrosoftExt && 4316 DK == diag::err_anonymous_record_with_type) 4317 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4318 << Record->isUnion(); 4319 else { 4320 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4321 Invalid = true; 4322 } 4323 } 4324 } 4325 4326 // C++11 [class.union]p8 (DR1460): 4327 // At most one variant member of a union may have a 4328 // brace-or-equal-initializer. 4329 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4330 Owner->isRecord()) 4331 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4332 cast<CXXRecordDecl>(Record)); 4333 } 4334 4335 if (!Record->isUnion() && !Owner->isRecord()) { 4336 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4337 << getLangOpts().CPlusPlus; 4338 Invalid = true; 4339 } 4340 4341 // Mock up a declarator. 4342 Declarator Dc(DS, Declarator::MemberContext); 4343 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4344 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4345 4346 // Create a declaration for this anonymous struct/union. 4347 NamedDecl *Anon = nullptr; 4348 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4349 Anon = FieldDecl::Create(Context, OwningClass, 4350 DS.getLocStart(), 4351 Record->getLocation(), 4352 /*IdentifierInfo=*/nullptr, 4353 Context.getTypeDeclType(Record), 4354 TInfo, 4355 /*BitWidth=*/nullptr, /*Mutable=*/false, 4356 /*InitStyle=*/ICIS_NoInit); 4357 Anon->setAccess(AS); 4358 if (getLangOpts().CPlusPlus) 4359 FieldCollector->Add(cast<FieldDecl>(Anon)); 4360 } else { 4361 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4362 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4363 if (SCSpec == DeclSpec::SCS_mutable) { 4364 // mutable can only appear on non-static class members, so it's always 4365 // an error here 4366 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4367 Invalid = true; 4368 SC = SC_None; 4369 } 4370 4371 Anon = VarDecl::Create(Context, Owner, 4372 DS.getLocStart(), 4373 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4374 Context.getTypeDeclType(Record), 4375 TInfo, SC); 4376 4377 // Default-initialize the implicit variable. This initialization will be 4378 // trivial in almost all cases, except if a union member has an in-class 4379 // initializer: 4380 // union { int n = 0; }; 4381 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4382 } 4383 Anon->setImplicit(); 4384 4385 // Mark this as an anonymous struct/union type. 4386 Record->setAnonymousStructOrUnion(true); 4387 4388 // Add the anonymous struct/union object to the current 4389 // context. We'll be referencing this object when we refer to one of 4390 // its members. 4391 Owner->addDecl(Anon); 4392 4393 // Inject the members of the anonymous struct/union into the owning 4394 // context and into the identifier resolver chain for name lookup 4395 // purposes. 4396 SmallVector<NamedDecl*, 2> Chain; 4397 Chain.push_back(Anon); 4398 4399 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4400 Invalid = true; 4401 4402 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4403 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4404 Decl *ManglingContextDecl; 4405 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4406 NewVD->getDeclContext(), ManglingContextDecl)) { 4407 Context.setManglingNumber( 4408 NewVD, MCtx->getManglingNumber( 4409 NewVD, getMSManglingNumber(getLangOpts(), S))); 4410 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4411 } 4412 } 4413 } 4414 4415 if (Invalid) 4416 Anon->setInvalidDecl(); 4417 4418 return Anon; 4419 } 4420 4421 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4422 /// Microsoft C anonymous structure. 4423 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4424 /// Example: 4425 /// 4426 /// struct A { int a; }; 4427 /// struct B { struct A; int b; }; 4428 /// 4429 /// void foo() { 4430 /// B var; 4431 /// var.a = 3; 4432 /// } 4433 /// 4434 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4435 RecordDecl *Record) { 4436 assert(Record && "expected a record!"); 4437 4438 // Mock up a declarator. 4439 Declarator Dc(DS, Declarator::TypeNameContext); 4440 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4441 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4442 4443 auto *ParentDecl = cast<RecordDecl>(CurContext); 4444 QualType RecTy = Context.getTypeDeclType(Record); 4445 4446 // Create a declaration for this anonymous struct. 4447 NamedDecl *Anon = FieldDecl::Create(Context, 4448 ParentDecl, 4449 DS.getLocStart(), 4450 DS.getLocStart(), 4451 /*IdentifierInfo=*/nullptr, 4452 RecTy, 4453 TInfo, 4454 /*BitWidth=*/nullptr, /*Mutable=*/false, 4455 /*InitStyle=*/ICIS_NoInit); 4456 Anon->setImplicit(); 4457 4458 // Add the anonymous struct object to the current context. 4459 CurContext->addDecl(Anon); 4460 4461 // Inject the members of the anonymous struct into the current 4462 // context and into the identifier resolver chain for name lookup 4463 // purposes. 4464 SmallVector<NamedDecl*, 2> Chain; 4465 Chain.push_back(Anon); 4466 4467 RecordDecl *RecordDef = Record->getDefinition(); 4468 if (RequireCompleteType(Anon->getLocation(), RecTy, 4469 diag::err_field_incomplete) || 4470 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4471 AS_none, Chain)) { 4472 Anon->setInvalidDecl(); 4473 ParentDecl->setInvalidDecl(); 4474 } 4475 4476 return Anon; 4477 } 4478 4479 /// GetNameForDeclarator - Determine the full declaration name for the 4480 /// given Declarator. 4481 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4482 return GetNameFromUnqualifiedId(D.getName()); 4483 } 4484 4485 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4486 DeclarationNameInfo 4487 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4488 DeclarationNameInfo NameInfo; 4489 NameInfo.setLoc(Name.StartLocation); 4490 4491 switch (Name.getKind()) { 4492 4493 case UnqualifiedId::IK_ImplicitSelfParam: 4494 case UnqualifiedId::IK_Identifier: 4495 NameInfo.setName(Name.Identifier); 4496 NameInfo.setLoc(Name.StartLocation); 4497 return NameInfo; 4498 4499 case UnqualifiedId::IK_OperatorFunctionId: 4500 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4501 Name.OperatorFunctionId.Operator)); 4502 NameInfo.setLoc(Name.StartLocation); 4503 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4504 = Name.OperatorFunctionId.SymbolLocations[0]; 4505 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4506 = Name.EndLocation.getRawEncoding(); 4507 return NameInfo; 4508 4509 case UnqualifiedId::IK_LiteralOperatorId: 4510 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4511 Name.Identifier)); 4512 NameInfo.setLoc(Name.StartLocation); 4513 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4514 return NameInfo; 4515 4516 case UnqualifiedId::IK_ConversionFunctionId: { 4517 TypeSourceInfo *TInfo; 4518 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4519 if (Ty.isNull()) 4520 return DeclarationNameInfo(); 4521 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4522 Context.getCanonicalType(Ty))); 4523 NameInfo.setLoc(Name.StartLocation); 4524 NameInfo.setNamedTypeInfo(TInfo); 4525 return NameInfo; 4526 } 4527 4528 case UnqualifiedId::IK_ConstructorName: { 4529 TypeSourceInfo *TInfo; 4530 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4531 if (Ty.isNull()) 4532 return DeclarationNameInfo(); 4533 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4534 Context.getCanonicalType(Ty))); 4535 NameInfo.setLoc(Name.StartLocation); 4536 NameInfo.setNamedTypeInfo(TInfo); 4537 return NameInfo; 4538 } 4539 4540 case UnqualifiedId::IK_ConstructorTemplateId: { 4541 // In well-formed code, we can only have a constructor 4542 // template-id that refers to the current context, so go there 4543 // to find the actual type being constructed. 4544 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4545 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4546 return DeclarationNameInfo(); 4547 4548 // Determine the type of the class being constructed. 4549 QualType CurClassType = Context.getTypeDeclType(CurClass); 4550 4551 // FIXME: Check two things: that the template-id names the same type as 4552 // CurClassType, and that the template-id does not occur when the name 4553 // was qualified. 4554 4555 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4556 Context.getCanonicalType(CurClassType))); 4557 NameInfo.setLoc(Name.StartLocation); 4558 // FIXME: should we retrieve TypeSourceInfo? 4559 NameInfo.setNamedTypeInfo(nullptr); 4560 return NameInfo; 4561 } 4562 4563 case UnqualifiedId::IK_DestructorName: { 4564 TypeSourceInfo *TInfo; 4565 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4566 if (Ty.isNull()) 4567 return DeclarationNameInfo(); 4568 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4569 Context.getCanonicalType(Ty))); 4570 NameInfo.setLoc(Name.StartLocation); 4571 NameInfo.setNamedTypeInfo(TInfo); 4572 return NameInfo; 4573 } 4574 4575 case UnqualifiedId::IK_TemplateId: { 4576 TemplateName TName = Name.TemplateId->Template.get(); 4577 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4578 return Context.getNameForTemplate(TName, TNameLoc); 4579 } 4580 4581 } // switch (Name.getKind()) 4582 4583 llvm_unreachable("Unknown name kind"); 4584 } 4585 4586 static QualType getCoreType(QualType Ty) { 4587 do { 4588 if (Ty->isPointerType() || Ty->isReferenceType()) 4589 Ty = Ty->getPointeeType(); 4590 else if (Ty->isArrayType()) 4591 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4592 else 4593 return Ty.withoutLocalFastQualifiers(); 4594 } while (true); 4595 } 4596 4597 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4598 /// and Definition have "nearly" matching parameters. This heuristic is 4599 /// used to improve diagnostics in the case where an out-of-line function 4600 /// definition doesn't match any declaration within the class or namespace. 4601 /// Also sets Params to the list of indices to the parameters that differ 4602 /// between the declaration and the definition. If hasSimilarParameters 4603 /// returns true and Params is empty, then all of the parameters match. 4604 static bool hasSimilarParameters(ASTContext &Context, 4605 FunctionDecl *Declaration, 4606 FunctionDecl *Definition, 4607 SmallVectorImpl<unsigned> &Params) { 4608 Params.clear(); 4609 if (Declaration->param_size() != Definition->param_size()) 4610 return false; 4611 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4612 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4613 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4614 4615 // The parameter types are identical 4616 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4617 continue; 4618 4619 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4620 QualType DefParamBaseTy = getCoreType(DefParamTy); 4621 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4622 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4623 4624 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4625 (DeclTyName && DeclTyName == DefTyName)) 4626 Params.push_back(Idx); 4627 else // The two parameters aren't even close 4628 return false; 4629 } 4630 4631 return true; 4632 } 4633 4634 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4635 /// declarator needs to be rebuilt in the current instantiation. 4636 /// Any bits of declarator which appear before the name are valid for 4637 /// consideration here. That's specifically the type in the decl spec 4638 /// and the base type in any member-pointer chunks. 4639 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4640 DeclarationName Name) { 4641 // The types we specifically need to rebuild are: 4642 // - typenames, typeofs, and decltypes 4643 // - types which will become injected class names 4644 // Of course, we also need to rebuild any type referencing such a 4645 // type. It's safest to just say "dependent", but we call out a 4646 // few cases here. 4647 4648 DeclSpec &DS = D.getMutableDeclSpec(); 4649 switch (DS.getTypeSpecType()) { 4650 case DeclSpec::TST_typename: 4651 case DeclSpec::TST_typeofType: 4652 case DeclSpec::TST_underlyingType: 4653 case DeclSpec::TST_atomic: { 4654 // Grab the type from the parser. 4655 TypeSourceInfo *TSI = nullptr; 4656 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4657 if (T.isNull() || !T->isDependentType()) break; 4658 4659 // Make sure there's a type source info. This isn't really much 4660 // of a waste; most dependent types should have type source info 4661 // attached already. 4662 if (!TSI) 4663 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4664 4665 // Rebuild the type in the current instantiation. 4666 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4667 if (!TSI) return true; 4668 4669 // Store the new type back in the decl spec. 4670 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4671 DS.UpdateTypeRep(LocType); 4672 break; 4673 } 4674 4675 case DeclSpec::TST_decltype: 4676 case DeclSpec::TST_typeofExpr: { 4677 Expr *E = DS.getRepAsExpr(); 4678 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4679 if (Result.isInvalid()) return true; 4680 DS.UpdateExprRep(Result.get()); 4681 break; 4682 } 4683 4684 default: 4685 // Nothing to do for these decl specs. 4686 break; 4687 } 4688 4689 // It doesn't matter what order we do this in. 4690 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4691 DeclaratorChunk &Chunk = D.getTypeObject(I); 4692 4693 // The only type information in the declarator which can come 4694 // before the declaration name is the base type of a member 4695 // pointer. 4696 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4697 continue; 4698 4699 // Rebuild the scope specifier in-place. 4700 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4701 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4702 return true; 4703 } 4704 4705 return false; 4706 } 4707 4708 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4709 D.setFunctionDefinitionKind(FDK_Declaration); 4710 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4711 4712 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4713 Dcl && Dcl->getDeclContext()->isFileContext()) 4714 Dcl->setTopLevelDeclInObjCContainer(); 4715 4716 return Dcl; 4717 } 4718 4719 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4720 /// If T is the name of a class, then each of the following shall have a 4721 /// name different from T: 4722 /// - every static data member of class T; 4723 /// - every member function of class T 4724 /// - every member of class T that is itself a type; 4725 /// \returns true if the declaration name violates these rules. 4726 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4727 DeclarationNameInfo NameInfo) { 4728 DeclarationName Name = NameInfo.getName(); 4729 4730 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4731 while (Record && Record->isAnonymousStructOrUnion()) 4732 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4733 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4734 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4735 return true; 4736 } 4737 4738 return false; 4739 } 4740 4741 /// \brief Diagnose a declaration whose declarator-id has the given 4742 /// nested-name-specifier. 4743 /// 4744 /// \param SS The nested-name-specifier of the declarator-id. 4745 /// 4746 /// \param DC The declaration context to which the nested-name-specifier 4747 /// resolves. 4748 /// 4749 /// \param Name The name of the entity being declared. 4750 /// 4751 /// \param Loc The location of the name of the entity being declared. 4752 /// 4753 /// \returns true if we cannot safely recover from this error, false otherwise. 4754 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4755 DeclarationName Name, 4756 SourceLocation Loc) { 4757 DeclContext *Cur = CurContext; 4758 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4759 Cur = Cur->getParent(); 4760 4761 // If the user provided a superfluous scope specifier that refers back to the 4762 // class in which the entity is already declared, diagnose and ignore it. 4763 // 4764 // class X { 4765 // void X::f(); 4766 // }; 4767 // 4768 // Note, it was once ill-formed to give redundant qualification in all 4769 // contexts, but that rule was removed by DR482. 4770 if (Cur->Equals(DC)) { 4771 if (Cur->isRecord()) { 4772 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4773 : diag::err_member_extra_qualification) 4774 << Name << FixItHint::CreateRemoval(SS.getRange()); 4775 SS.clear(); 4776 } else { 4777 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4778 } 4779 return false; 4780 } 4781 4782 // Check whether the qualifying scope encloses the scope of the original 4783 // declaration. 4784 if (!Cur->Encloses(DC)) { 4785 if (Cur->isRecord()) 4786 Diag(Loc, diag::err_member_qualification) 4787 << Name << SS.getRange(); 4788 else if (isa<TranslationUnitDecl>(DC)) 4789 Diag(Loc, diag::err_invalid_declarator_global_scope) 4790 << Name << SS.getRange(); 4791 else if (isa<FunctionDecl>(Cur)) 4792 Diag(Loc, diag::err_invalid_declarator_in_function) 4793 << Name << SS.getRange(); 4794 else if (isa<BlockDecl>(Cur)) 4795 Diag(Loc, diag::err_invalid_declarator_in_block) 4796 << Name << SS.getRange(); 4797 else 4798 Diag(Loc, diag::err_invalid_declarator_scope) 4799 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4800 4801 return true; 4802 } 4803 4804 if (Cur->isRecord()) { 4805 // Cannot qualify members within a class. 4806 Diag(Loc, diag::err_member_qualification) 4807 << Name << SS.getRange(); 4808 SS.clear(); 4809 4810 // C++ constructors and destructors with incorrect scopes can break 4811 // our AST invariants by having the wrong underlying types. If 4812 // that's the case, then drop this declaration entirely. 4813 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4814 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4815 !Context.hasSameType(Name.getCXXNameType(), 4816 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4817 return true; 4818 4819 return false; 4820 } 4821 4822 // C++11 [dcl.meaning]p1: 4823 // [...] "The nested-name-specifier of the qualified declarator-id shall 4824 // not begin with a decltype-specifer" 4825 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4826 while (SpecLoc.getPrefix()) 4827 SpecLoc = SpecLoc.getPrefix(); 4828 if (dyn_cast_or_null<DecltypeType>( 4829 SpecLoc.getNestedNameSpecifier()->getAsType())) 4830 Diag(Loc, diag::err_decltype_in_declarator) 4831 << SpecLoc.getTypeLoc().getSourceRange(); 4832 4833 return false; 4834 } 4835 4836 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4837 MultiTemplateParamsArg TemplateParamLists) { 4838 // TODO: consider using NameInfo for diagnostic. 4839 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4840 DeclarationName Name = NameInfo.getName(); 4841 4842 // All of these full declarators require an identifier. If it doesn't have 4843 // one, the ParsedFreeStandingDeclSpec action should be used. 4844 if (!Name) { 4845 if (!D.isInvalidType()) // Reject this if we think it is valid. 4846 Diag(D.getDeclSpec().getLocStart(), 4847 diag::err_declarator_need_ident) 4848 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4849 return nullptr; 4850 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4851 return nullptr; 4852 4853 // The scope passed in may not be a decl scope. Zip up the scope tree until 4854 // we find one that is. 4855 while ((S->getFlags() & Scope::DeclScope) == 0 || 4856 (S->getFlags() & Scope::TemplateParamScope) != 0) 4857 S = S->getParent(); 4858 4859 DeclContext *DC = CurContext; 4860 if (D.getCXXScopeSpec().isInvalid()) 4861 D.setInvalidType(); 4862 else if (D.getCXXScopeSpec().isSet()) { 4863 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4864 UPPC_DeclarationQualifier)) 4865 return nullptr; 4866 4867 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4868 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4869 if (!DC || isa<EnumDecl>(DC)) { 4870 // If we could not compute the declaration context, it's because the 4871 // declaration context is dependent but does not refer to a class, 4872 // class template, or class template partial specialization. Complain 4873 // and return early, to avoid the coming semantic disaster. 4874 Diag(D.getIdentifierLoc(), 4875 diag::err_template_qualified_declarator_no_match) 4876 << D.getCXXScopeSpec().getScopeRep() 4877 << D.getCXXScopeSpec().getRange(); 4878 return nullptr; 4879 } 4880 bool IsDependentContext = DC->isDependentContext(); 4881 4882 if (!IsDependentContext && 4883 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4884 return nullptr; 4885 4886 // If a class is incomplete, do not parse entities inside it. 4887 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4888 Diag(D.getIdentifierLoc(), 4889 diag::err_member_def_undefined_record) 4890 << Name << DC << D.getCXXScopeSpec().getRange(); 4891 return nullptr; 4892 } 4893 if (!D.getDeclSpec().isFriendSpecified()) { 4894 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4895 Name, D.getIdentifierLoc())) { 4896 if (DC->isRecord()) 4897 return nullptr; 4898 4899 D.setInvalidType(); 4900 } 4901 } 4902 4903 // Check whether we need to rebuild the type of the given 4904 // declaration in the current instantiation. 4905 if (EnteringContext && IsDependentContext && 4906 TemplateParamLists.size() != 0) { 4907 ContextRAII SavedContext(*this, DC); 4908 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4909 D.setInvalidType(); 4910 } 4911 } 4912 4913 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4914 QualType R = TInfo->getType(); 4915 4916 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 4917 // If this is a typedef, we'll end up spewing multiple diagnostics. 4918 // Just return early; it's safer. If this is a function, let the 4919 // "constructor cannot have a return type" diagnostic handle it. 4920 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4921 return nullptr; 4922 4923 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4924 UPPC_DeclarationType)) 4925 D.setInvalidType(); 4926 4927 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4928 ForRedeclaration); 4929 4930 // See if this is a redefinition of a variable in the same scope. 4931 if (!D.getCXXScopeSpec().isSet()) { 4932 bool IsLinkageLookup = false; 4933 bool CreateBuiltins = false; 4934 4935 // If the declaration we're planning to build will be a function 4936 // or object with linkage, then look for another declaration with 4937 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4938 // 4939 // If the declaration we're planning to build will be declared with 4940 // external linkage in the translation unit, create any builtin with 4941 // the same name. 4942 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4943 /* Do nothing*/; 4944 else if (CurContext->isFunctionOrMethod() && 4945 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4946 R->isFunctionType())) { 4947 IsLinkageLookup = true; 4948 CreateBuiltins = 4949 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4950 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4951 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4952 CreateBuiltins = true; 4953 4954 if (IsLinkageLookup) 4955 Previous.clear(LookupRedeclarationWithLinkage); 4956 4957 LookupName(Previous, S, CreateBuiltins); 4958 } else { // Something like "int foo::x;" 4959 LookupQualifiedName(Previous, DC); 4960 4961 // C++ [dcl.meaning]p1: 4962 // When the declarator-id is qualified, the declaration shall refer to a 4963 // previously declared member of the class or namespace to which the 4964 // qualifier refers (or, in the case of a namespace, of an element of the 4965 // inline namespace set of that namespace (7.3.1)) or to a specialization 4966 // thereof; [...] 4967 // 4968 // Note that we already checked the context above, and that we do not have 4969 // enough information to make sure that Previous contains the declaration 4970 // we want to match. For example, given: 4971 // 4972 // class X { 4973 // void f(); 4974 // void f(float); 4975 // }; 4976 // 4977 // void X::f(int) { } // ill-formed 4978 // 4979 // In this case, Previous will point to the overload set 4980 // containing the two f's declared in X, but neither of them 4981 // matches. 4982 4983 // C++ [dcl.meaning]p1: 4984 // [...] the member shall not merely have been introduced by a 4985 // using-declaration in the scope of the class or namespace nominated by 4986 // the nested-name-specifier of the declarator-id. 4987 RemoveUsingDecls(Previous); 4988 } 4989 4990 if (Previous.isSingleResult() && 4991 Previous.getFoundDecl()->isTemplateParameter()) { 4992 // Maybe we will complain about the shadowed template parameter. 4993 if (!D.isInvalidType()) 4994 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4995 Previous.getFoundDecl()); 4996 4997 // Just pretend that we didn't see the previous declaration. 4998 Previous.clear(); 4999 } 5000 5001 // In C++, the previous declaration we find might be a tag type 5002 // (class or enum). In this case, the new declaration will hide the 5003 // tag type. Note that this does does not apply if we're declaring a 5004 // typedef (C++ [dcl.typedef]p4). 5005 if (Previous.isSingleTagDecl() && 5006 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5007 Previous.clear(); 5008 5009 // Check that there are no default arguments other than in the parameters 5010 // of a function declaration (C++ only). 5011 if (getLangOpts().CPlusPlus) 5012 CheckExtraCXXDefaultArguments(D); 5013 5014 if (D.getDeclSpec().isConceptSpecified()) { 5015 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5016 // applied only to the definition of a function template or variable 5017 // template, declared in namespace scope 5018 if (!TemplateParamLists.size()) { 5019 Diag(D.getDeclSpec().getConceptSpecLoc(), 5020 diag:: err_concept_wrong_decl_kind); 5021 return nullptr; 5022 } 5023 5024 if (!DC->getRedeclContext()->isFileContext()) { 5025 Diag(D.getIdentifierLoc(), 5026 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5027 return nullptr; 5028 } 5029 } 5030 5031 NamedDecl *New; 5032 5033 bool AddToScope = true; 5034 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5035 if (TemplateParamLists.size()) { 5036 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5037 return nullptr; 5038 } 5039 5040 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5041 } else if (R->isFunctionType()) { 5042 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5043 TemplateParamLists, 5044 AddToScope); 5045 } else { 5046 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5047 AddToScope); 5048 } 5049 5050 if (!New) 5051 return nullptr; 5052 5053 // If this has an identifier and is not an invalid redeclaration or 5054 // function template specialization, add it to the scope stack. 5055 if (New->getDeclName() && AddToScope && 5056 !(D.isRedeclaration() && New->isInvalidDecl())) { 5057 // Only make a locally-scoped extern declaration visible if it is the first 5058 // declaration of this entity. Qualified lookup for such an entity should 5059 // only find this declaration if there is no visible declaration of it. 5060 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5061 PushOnScopeChains(New, S, AddToContext); 5062 if (!AddToContext) 5063 CurContext->addHiddenDecl(New); 5064 } 5065 5066 if (isInOpenMPDeclareTargetContext()) 5067 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5068 5069 return New; 5070 } 5071 5072 /// Helper method to turn variable array types into constant array 5073 /// types in certain situations which would otherwise be errors (for 5074 /// GCC compatibility). 5075 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5076 ASTContext &Context, 5077 bool &SizeIsNegative, 5078 llvm::APSInt &Oversized) { 5079 // This method tries to turn a variable array into a constant 5080 // array even when the size isn't an ICE. This is necessary 5081 // for compatibility with code that depends on gcc's buggy 5082 // constant expression folding, like struct {char x[(int)(char*)2];} 5083 SizeIsNegative = false; 5084 Oversized = 0; 5085 5086 if (T->isDependentType()) 5087 return QualType(); 5088 5089 QualifierCollector Qs; 5090 const Type *Ty = Qs.strip(T); 5091 5092 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5093 QualType Pointee = PTy->getPointeeType(); 5094 QualType FixedType = 5095 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5096 Oversized); 5097 if (FixedType.isNull()) return FixedType; 5098 FixedType = Context.getPointerType(FixedType); 5099 return Qs.apply(Context, FixedType); 5100 } 5101 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5102 QualType Inner = PTy->getInnerType(); 5103 QualType FixedType = 5104 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5105 Oversized); 5106 if (FixedType.isNull()) return FixedType; 5107 FixedType = Context.getParenType(FixedType); 5108 return Qs.apply(Context, FixedType); 5109 } 5110 5111 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5112 if (!VLATy) 5113 return QualType(); 5114 // FIXME: We should probably handle this case 5115 if (VLATy->getElementType()->isVariablyModifiedType()) 5116 return QualType(); 5117 5118 llvm::APSInt Res; 5119 if (!VLATy->getSizeExpr() || 5120 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5121 return QualType(); 5122 5123 // Check whether the array size is negative. 5124 if (Res.isSigned() && Res.isNegative()) { 5125 SizeIsNegative = true; 5126 return QualType(); 5127 } 5128 5129 // Check whether the array is too large to be addressed. 5130 unsigned ActiveSizeBits 5131 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5132 Res); 5133 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5134 Oversized = Res; 5135 return QualType(); 5136 } 5137 5138 return Context.getConstantArrayType(VLATy->getElementType(), 5139 Res, ArrayType::Normal, 0); 5140 } 5141 5142 static void 5143 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5144 SrcTL = SrcTL.getUnqualifiedLoc(); 5145 DstTL = DstTL.getUnqualifiedLoc(); 5146 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5147 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5148 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5149 DstPTL.getPointeeLoc()); 5150 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5151 return; 5152 } 5153 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5154 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5155 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5156 DstPTL.getInnerLoc()); 5157 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5158 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5159 return; 5160 } 5161 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5162 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5163 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5164 TypeLoc DstElemTL = DstATL.getElementLoc(); 5165 DstElemTL.initializeFullCopy(SrcElemTL); 5166 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5167 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5168 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5169 } 5170 5171 /// Helper method to turn variable array types into constant array 5172 /// types in certain situations which would otherwise be errors (for 5173 /// GCC compatibility). 5174 static TypeSourceInfo* 5175 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5176 ASTContext &Context, 5177 bool &SizeIsNegative, 5178 llvm::APSInt &Oversized) { 5179 QualType FixedTy 5180 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5181 SizeIsNegative, Oversized); 5182 if (FixedTy.isNull()) 5183 return nullptr; 5184 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5185 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5186 FixedTInfo->getTypeLoc()); 5187 return FixedTInfo; 5188 } 5189 5190 /// \brief Register the given locally-scoped extern "C" declaration so 5191 /// that it can be found later for redeclarations. We include any extern "C" 5192 /// declaration that is not visible in the translation unit here, not just 5193 /// function-scope declarations. 5194 void 5195 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5196 if (!getLangOpts().CPlusPlus && 5197 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5198 // Don't need to track declarations in the TU in C. 5199 return; 5200 5201 // Note that we have a locally-scoped external with this name. 5202 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5203 } 5204 5205 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5206 // FIXME: We can have multiple results via __attribute__((overloadable)). 5207 auto Result = Context.getExternCContextDecl()->lookup(Name); 5208 return Result.empty() ? nullptr : *Result.begin(); 5209 } 5210 5211 /// \brief Diagnose function specifiers on a declaration of an identifier that 5212 /// does not identify a function. 5213 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5214 // FIXME: We should probably indicate the identifier in question to avoid 5215 // confusion for constructs like "inline int a(), b;" 5216 if (DS.isInlineSpecified()) 5217 Diag(DS.getInlineSpecLoc(), 5218 diag::err_inline_non_function); 5219 5220 if (DS.isVirtualSpecified()) 5221 Diag(DS.getVirtualSpecLoc(), 5222 diag::err_virtual_non_function); 5223 5224 if (DS.isExplicitSpecified()) 5225 Diag(DS.getExplicitSpecLoc(), 5226 diag::err_explicit_non_function); 5227 5228 if (DS.isNoreturnSpecified()) 5229 Diag(DS.getNoreturnSpecLoc(), 5230 diag::err_noreturn_non_function); 5231 } 5232 5233 NamedDecl* 5234 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5235 TypeSourceInfo *TInfo, LookupResult &Previous) { 5236 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5237 if (D.getCXXScopeSpec().isSet()) { 5238 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5239 << D.getCXXScopeSpec().getRange(); 5240 D.setInvalidType(); 5241 // Pretend we didn't see the scope specifier. 5242 DC = CurContext; 5243 Previous.clear(); 5244 } 5245 5246 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5247 5248 if (D.getDeclSpec().isConstexprSpecified()) 5249 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5250 << 1; 5251 if (D.getDeclSpec().isConceptSpecified()) 5252 Diag(D.getDeclSpec().getConceptSpecLoc(), 5253 diag::err_concept_wrong_decl_kind); 5254 5255 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5256 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5257 << D.getName().getSourceRange(); 5258 return nullptr; 5259 } 5260 5261 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5262 if (!NewTD) return nullptr; 5263 5264 // Handle attributes prior to checking for duplicates in MergeVarDecl 5265 ProcessDeclAttributes(S, NewTD, D); 5266 5267 CheckTypedefForVariablyModifiedType(S, NewTD); 5268 5269 bool Redeclaration = D.isRedeclaration(); 5270 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5271 D.setRedeclaration(Redeclaration); 5272 return ND; 5273 } 5274 5275 void 5276 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5277 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5278 // then it shall have block scope. 5279 // Note that variably modified types must be fixed before merging the decl so 5280 // that redeclarations will match. 5281 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5282 QualType T = TInfo->getType(); 5283 if (T->isVariablyModifiedType()) { 5284 getCurFunction()->setHasBranchProtectedScope(); 5285 5286 if (S->getFnParent() == nullptr) { 5287 bool SizeIsNegative; 5288 llvm::APSInt Oversized; 5289 TypeSourceInfo *FixedTInfo = 5290 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5291 SizeIsNegative, 5292 Oversized); 5293 if (FixedTInfo) { 5294 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5295 NewTD->setTypeSourceInfo(FixedTInfo); 5296 } else { 5297 if (SizeIsNegative) 5298 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5299 else if (T->isVariableArrayType()) 5300 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5301 else if (Oversized.getBoolValue()) 5302 Diag(NewTD->getLocation(), diag::err_array_too_large) 5303 << Oversized.toString(10); 5304 else 5305 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5306 NewTD->setInvalidDecl(); 5307 } 5308 } 5309 } 5310 } 5311 5312 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5313 /// declares a typedef-name, either using the 'typedef' type specifier or via 5314 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5315 NamedDecl* 5316 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5317 LookupResult &Previous, bool &Redeclaration) { 5318 // Merge the decl with the existing one if appropriate. If the decl is 5319 // in an outer scope, it isn't the same thing. 5320 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5321 /*AllowInlineNamespace*/false); 5322 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5323 if (!Previous.empty()) { 5324 Redeclaration = true; 5325 MergeTypedefNameDecl(S, NewTD, Previous); 5326 } 5327 5328 // If this is the C FILE type, notify the AST context. 5329 if (IdentifierInfo *II = NewTD->getIdentifier()) 5330 if (!NewTD->isInvalidDecl() && 5331 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5332 if (II->isStr("FILE")) 5333 Context.setFILEDecl(NewTD); 5334 else if (II->isStr("jmp_buf")) 5335 Context.setjmp_bufDecl(NewTD); 5336 else if (II->isStr("sigjmp_buf")) 5337 Context.setsigjmp_bufDecl(NewTD); 5338 else if (II->isStr("ucontext_t")) 5339 Context.setucontext_tDecl(NewTD); 5340 } 5341 5342 return NewTD; 5343 } 5344 5345 /// \brief Determines whether the given declaration is an out-of-scope 5346 /// previous declaration. 5347 /// 5348 /// This routine should be invoked when name lookup has found a 5349 /// previous declaration (PrevDecl) that is not in the scope where a 5350 /// new declaration by the same name is being introduced. If the new 5351 /// declaration occurs in a local scope, previous declarations with 5352 /// linkage may still be considered previous declarations (C99 5353 /// 6.2.2p4-5, C++ [basic.link]p6). 5354 /// 5355 /// \param PrevDecl the previous declaration found by name 5356 /// lookup 5357 /// 5358 /// \param DC the context in which the new declaration is being 5359 /// declared. 5360 /// 5361 /// \returns true if PrevDecl is an out-of-scope previous declaration 5362 /// for a new delcaration with the same name. 5363 static bool 5364 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5365 ASTContext &Context) { 5366 if (!PrevDecl) 5367 return false; 5368 5369 if (!PrevDecl->hasLinkage()) 5370 return false; 5371 5372 if (Context.getLangOpts().CPlusPlus) { 5373 // C++ [basic.link]p6: 5374 // If there is a visible declaration of an entity with linkage 5375 // having the same name and type, ignoring entities declared 5376 // outside the innermost enclosing namespace scope, the block 5377 // scope declaration declares that same entity and receives the 5378 // linkage of the previous declaration. 5379 DeclContext *OuterContext = DC->getRedeclContext(); 5380 if (!OuterContext->isFunctionOrMethod()) 5381 // This rule only applies to block-scope declarations. 5382 return false; 5383 5384 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5385 if (PrevOuterContext->isRecord()) 5386 // We found a member function: ignore it. 5387 return false; 5388 5389 // Find the innermost enclosing namespace for the new and 5390 // previous declarations. 5391 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5392 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5393 5394 // The previous declaration is in a different namespace, so it 5395 // isn't the same function. 5396 if (!OuterContext->Equals(PrevOuterContext)) 5397 return false; 5398 } 5399 5400 return true; 5401 } 5402 5403 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5404 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5405 if (!SS.isSet()) return; 5406 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5407 } 5408 5409 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5410 QualType type = decl->getType(); 5411 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5412 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5413 // Various kinds of declaration aren't allowed to be __autoreleasing. 5414 unsigned kind = -1U; 5415 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5416 if (var->hasAttr<BlocksAttr>()) 5417 kind = 0; // __block 5418 else if (!var->hasLocalStorage()) 5419 kind = 1; // global 5420 } else if (isa<ObjCIvarDecl>(decl)) { 5421 kind = 3; // ivar 5422 } else if (isa<FieldDecl>(decl)) { 5423 kind = 2; // field 5424 } 5425 5426 if (kind != -1U) { 5427 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5428 << kind; 5429 } 5430 } else if (lifetime == Qualifiers::OCL_None) { 5431 // Try to infer lifetime. 5432 if (!type->isObjCLifetimeType()) 5433 return false; 5434 5435 lifetime = type->getObjCARCImplicitLifetime(); 5436 type = Context.getLifetimeQualifiedType(type, lifetime); 5437 decl->setType(type); 5438 } 5439 5440 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5441 // Thread-local variables cannot have lifetime. 5442 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5443 var->getTLSKind()) { 5444 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5445 << var->getType(); 5446 return true; 5447 } 5448 } 5449 5450 return false; 5451 } 5452 5453 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5454 // Ensure that an auto decl is deduced otherwise the checks below might cache 5455 // the wrong linkage. 5456 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5457 5458 // 'weak' only applies to declarations with external linkage. 5459 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5460 if (!ND.isExternallyVisible()) { 5461 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5462 ND.dropAttr<WeakAttr>(); 5463 } 5464 } 5465 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5466 if (ND.isExternallyVisible()) { 5467 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5468 ND.dropAttr<WeakRefAttr>(); 5469 ND.dropAttr<AliasAttr>(); 5470 } 5471 } 5472 5473 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5474 if (VD->hasInit()) { 5475 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5476 assert(VD->isThisDeclarationADefinition() && 5477 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5478 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5479 VD->dropAttr<AliasAttr>(); 5480 } 5481 } 5482 } 5483 5484 // 'selectany' only applies to externally visible variable declarations. 5485 // It does not apply to functions. 5486 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5487 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5488 S.Diag(Attr->getLocation(), 5489 diag::err_attribute_selectany_non_extern_data); 5490 ND.dropAttr<SelectAnyAttr>(); 5491 } 5492 } 5493 5494 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5495 // dll attributes require external linkage. Static locals may have external 5496 // linkage but still cannot be explicitly imported or exported. 5497 auto *VD = dyn_cast<VarDecl>(&ND); 5498 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5499 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5500 << &ND << Attr; 5501 ND.setInvalidDecl(); 5502 } 5503 } 5504 5505 // Virtual functions cannot be marked as 'notail'. 5506 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5507 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5508 if (MD->isVirtual()) { 5509 S.Diag(ND.getLocation(), 5510 diag::err_invalid_attribute_on_virtual_function) 5511 << Attr; 5512 ND.dropAttr<NotTailCalledAttr>(); 5513 } 5514 } 5515 5516 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5517 NamedDecl *NewDecl, 5518 bool IsSpecialization) { 5519 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5520 OldDecl = OldTD->getTemplatedDecl(); 5521 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5522 NewDecl = NewTD->getTemplatedDecl(); 5523 5524 if (!OldDecl || !NewDecl) 5525 return; 5526 5527 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5528 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5529 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5530 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5531 5532 // dllimport and dllexport are inheritable attributes so we have to exclude 5533 // inherited attribute instances. 5534 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5535 (NewExportAttr && !NewExportAttr->isInherited()); 5536 5537 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5538 // the only exception being explicit specializations. 5539 // Implicitly generated declarations are also excluded for now because there 5540 // is no other way to switch these to use dllimport or dllexport. 5541 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5542 5543 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5544 // Allow with a warning for free functions and global variables. 5545 bool JustWarn = false; 5546 if (!OldDecl->isCXXClassMember()) { 5547 auto *VD = dyn_cast<VarDecl>(OldDecl); 5548 if (VD && !VD->getDescribedVarTemplate()) 5549 JustWarn = true; 5550 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5551 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5552 JustWarn = true; 5553 } 5554 5555 // We cannot change a declaration that's been used because IR has already 5556 // been emitted. Dllimported functions will still work though (modulo 5557 // address equality) as they can use the thunk. 5558 if (OldDecl->isUsed()) 5559 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5560 JustWarn = false; 5561 5562 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5563 : diag::err_attribute_dll_redeclaration; 5564 S.Diag(NewDecl->getLocation(), DiagID) 5565 << NewDecl 5566 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5567 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5568 if (!JustWarn) { 5569 NewDecl->setInvalidDecl(); 5570 return; 5571 } 5572 } 5573 5574 // A redeclaration is not allowed to drop a dllimport attribute, the only 5575 // exceptions being inline function definitions, local extern declarations, 5576 // and qualified friend declarations. 5577 // NB: MSVC converts such a declaration to dllexport. 5578 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5579 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5580 // Ignore static data because out-of-line definitions are diagnosed 5581 // separately. 5582 IsStaticDataMember = VD->isStaticDataMember(); 5583 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5584 IsInline = FD->isInlined(); 5585 IsQualifiedFriend = FD->getQualifier() && 5586 FD->getFriendObjectKind() == Decl::FOK_Declared; 5587 } 5588 5589 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5590 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5591 S.Diag(NewDecl->getLocation(), 5592 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5593 << NewDecl << OldImportAttr; 5594 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5595 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5596 OldDecl->dropAttr<DLLImportAttr>(); 5597 NewDecl->dropAttr<DLLImportAttr>(); 5598 } else if (IsInline && OldImportAttr && 5599 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5600 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5601 OldDecl->dropAttr<DLLImportAttr>(); 5602 NewDecl->dropAttr<DLLImportAttr>(); 5603 S.Diag(NewDecl->getLocation(), 5604 diag::warn_dllimport_dropped_from_inline_function) 5605 << NewDecl << OldImportAttr; 5606 } 5607 } 5608 5609 /// Given that we are within the definition of the given function, 5610 /// will that definition behave like C99's 'inline', where the 5611 /// definition is discarded except for optimization purposes? 5612 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5613 // Try to avoid calling GetGVALinkageForFunction. 5614 5615 // All cases of this require the 'inline' keyword. 5616 if (!FD->isInlined()) return false; 5617 5618 // This is only possible in C++ with the gnu_inline attribute. 5619 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5620 return false; 5621 5622 // Okay, go ahead and call the relatively-more-expensive function. 5623 5624 #ifndef NDEBUG 5625 // AST quite reasonably asserts that it's working on a function 5626 // definition. We don't really have a way to tell it that we're 5627 // currently defining the function, so just lie to it in +Asserts 5628 // builds. This is an awful hack. 5629 FD->setLazyBody(1); 5630 #endif 5631 5632 bool isC99Inline = 5633 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5634 5635 #ifndef NDEBUG 5636 FD->setLazyBody(0); 5637 #endif 5638 5639 return isC99Inline; 5640 } 5641 5642 /// Determine whether a variable is extern "C" prior to attaching 5643 /// an initializer. We can't just call isExternC() here, because that 5644 /// will also compute and cache whether the declaration is externally 5645 /// visible, which might change when we attach the initializer. 5646 /// 5647 /// This can only be used if the declaration is known to not be a 5648 /// redeclaration of an internal linkage declaration. 5649 /// 5650 /// For instance: 5651 /// 5652 /// auto x = []{}; 5653 /// 5654 /// Attaching the initializer here makes this declaration not externally 5655 /// visible, because its type has internal linkage. 5656 /// 5657 /// FIXME: This is a hack. 5658 template<typename T> 5659 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5660 if (S.getLangOpts().CPlusPlus) { 5661 // In C++, the overloadable attribute negates the effects of extern "C". 5662 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5663 return false; 5664 5665 // So do CUDA's host/device attributes. 5666 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 5667 D->template hasAttr<CUDAHostAttr>())) 5668 return false; 5669 } 5670 return D->isExternC(); 5671 } 5672 5673 static bool shouldConsiderLinkage(const VarDecl *VD) { 5674 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5675 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 5676 return VD->hasExternalStorage(); 5677 if (DC->isFileContext()) 5678 return true; 5679 if (DC->isRecord()) 5680 return false; 5681 llvm_unreachable("Unexpected context"); 5682 } 5683 5684 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5685 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5686 if (DC->isFileContext() || DC->isFunctionOrMethod() || 5687 isa<OMPDeclareReductionDecl>(DC)) 5688 return true; 5689 if (DC->isRecord()) 5690 return false; 5691 llvm_unreachable("Unexpected context"); 5692 } 5693 5694 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5695 AttributeList::Kind Kind) { 5696 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5697 if (L->getKind() == Kind) 5698 return true; 5699 return false; 5700 } 5701 5702 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5703 AttributeList::Kind Kind) { 5704 // Check decl attributes on the DeclSpec. 5705 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5706 return true; 5707 5708 // Walk the declarator structure, checking decl attributes that were in a type 5709 // position to the decl itself. 5710 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5711 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5712 return true; 5713 } 5714 5715 // Finally, check attributes on the decl itself. 5716 return hasParsedAttr(S, PD.getAttributes(), Kind); 5717 } 5718 5719 /// Adjust the \c DeclContext for a function or variable that might be a 5720 /// function-local external declaration. 5721 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5722 if (!DC->isFunctionOrMethod()) 5723 return false; 5724 5725 // If this is a local extern function or variable declared within a function 5726 // template, don't add it into the enclosing namespace scope until it is 5727 // instantiated; it might have a dependent type right now. 5728 if (DC->isDependentContext()) 5729 return true; 5730 5731 // C++11 [basic.link]p7: 5732 // When a block scope declaration of an entity with linkage is not found to 5733 // refer to some other declaration, then that entity is a member of the 5734 // innermost enclosing namespace. 5735 // 5736 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5737 // semantically-enclosing namespace, not a lexically-enclosing one. 5738 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5739 DC = DC->getParent(); 5740 return true; 5741 } 5742 5743 /// \brief Returns true if given declaration has external C language linkage. 5744 static bool isDeclExternC(const Decl *D) { 5745 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5746 return FD->isExternC(); 5747 if (const auto *VD = dyn_cast<VarDecl>(D)) 5748 return VD->isExternC(); 5749 5750 llvm_unreachable("Unknown type of decl!"); 5751 } 5752 5753 NamedDecl * 5754 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5755 TypeSourceInfo *TInfo, LookupResult &Previous, 5756 MultiTemplateParamsArg TemplateParamLists, 5757 bool &AddToScope) { 5758 QualType R = TInfo->getType(); 5759 DeclarationName Name = GetNameForDeclarator(D).getName(); 5760 5761 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 5762 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 5763 // argument. 5764 if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) { 5765 Diag(D.getIdentifierLoc(), 5766 diag::err_opencl_type_can_only_be_used_as_function_parameter) 5767 << R; 5768 D.setInvalidType(); 5769 return nullptr; 5770 } 5771 5772 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5773 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5774 5775 // dllimport globals without explicit storage class are treated as extern. We 5776 // have to change the storage class this early to get the right DeclContext. 5777 if (SC == SC_None && !DC->isRecord() && 5778 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5779 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5780 SC = SC_Extern; 5781 5782 DeclContext *OriginalDC = DC; 5783 bool IsLocalExternDecl = SC == SC_Extern && 5784 adjustContextForLocalExternDecl(DC); 5785 5786 if (getLangOpts().OpenCL) { 5787 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5788 QualType NR = R; 5789 while (NR->isPointerType()) { 5790 if (NR->isFunctionPointerType()) { 5791 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5792 D.setInvalidType(); 5793 break; 5794 } 5795 NR = NR->getPointeeType(); 5796 } 5797 5798 if (!getOpenCLOptions().cl_khr_fp16) { 5799 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5800 // half array type (unless the cl_khr_fp16 extension is enabled). 5801 if (Context.getBaseElementType(R)->isHalfType()) { 5802 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5803 D.setInvalidType(); 5804 } 5805 } 5806 } 5807 5808 if (SCSpec == DeclSpec::SCS_mutable) { 5809 // mutable can only appear on non-static class members, so it's always 5810 // an error here 5811 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5812 D.setInvalidType(); 5813 SC = SC_None; 5814 } 5815 5816 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5817 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5818 D.getDeclSpec().getStorageClassSpecLoc())) { 5819 // In C++11, the 'register' storage class specifier is deprecated. 5820 // Suppress the warning in system macros, it's used in macros in some 5821 // popular C system headers, such as in glibc's htonl() macro. 5822 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5823 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 5824 : diag::warn_deprecated_register) 5825 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5826 } 5827 5828 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5829 if (!II) { 5830 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5831 << Name; 5832 return nullptr; 5833 } 5834 5835 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5836 5837 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5838 // C99 6.9p2: The storage-class specifiers auto and register shall not 5839 // appear in the declaration specifiers in an external declaration. 5840 // Global Register+Asm is a GNU extension we support. 5841 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5842 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5843 D.setInvalidType(); 5844 } 5845 } 5846 5847 if (getLangOpts().OpenCL) { 5848 // OpenCL v1.2 s6.9.b p4: 5849 // The sampler type cannot be used with the __local and __global address 5850 // space qualifiers. 5851 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5852 R.getAddressSpace() == LangAS::opencl_global)) { 5853 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5854 } 5855 5856 // OpenCL 1.2 spec, p6.9 r: 5857 // The event type cannot be used to declare a program scope variable. 5858 // The event type cannot be used with the __local, __constant and __global 5859 // address space qualifiers. 5860 if (R->isEventT()) { 5861 if (S->getParent() == nullptr) { 5862 Diag(D.getLocStart(), diag::err_event_t_global_var); 5863 D.setInvalidType(); 5864 } 5865 5866 if (R.getAddressSpace()) { 5867 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5868 D.setInvalidType(); 5869 } 5870 } 5871 } 5872 5873 bool IsExplicitSpecialization = false; 5874 bool IsVariableTemplateSpecialization = false; 5875 bool IsPartialSpecialization = false; 5876 bool IsVariableTemplate = false; 5877 VarDecl *NewVD = nullptr; 5878 VarTemplateDecl *NewTemplate = nullptr; 5879 TemplateParameterList *TemplateParams = nullptr; 5880 if (!getLangOpts().CPlusPlus) { 5881 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5882 D.getIdentifierLoc(), II, 5883 R, TInfo, SC); 5884 5885 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5886 ParsingInitForAutoVars.insert(NewVD); 5887 5888 if (D.isInvalidType()) 5889 NewVD->setInvalidDecl(); 5890 } else { 5891 bool Invalid = false; 5892 5893 if (DC->isRecord() && !CurContext->isRecord()) { 5894 // This is an out-of-line definition of a static data member. 5895 switch (SC) { 5896 case SC_None: 5897 break; 5898 case SC_Static: 5899 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5900 diag::err_static_out_of_line) 5901 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5902 break; 5903 case SC_Auto: 5904 case SC_Register: 5905 case SC_Extern: 5906 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5907 // to names of variables declared in a block or to function parameters. 5908 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5909 // of class members 5910 5911 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5912 diag::err_storage_class_for_static_member) 5913 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5914 break; 5915 case SC_PrivateExtern: 5916 llvm_unreachable("C storage class in c++!"); 5917 } 5918 } 5919 5920 if (SC == SC_Static && CurContext->isRecord()) { 5921 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5922 if (RD->isLocalClass()) 5923 Diag(D.getIdentifierLoc(), 5924 diag::err_static_data_member_not_allowed_in_local_class) 5925 << Name << RD->getDeclName(); 5926 5927 // C++98 [class.union]p1: If a union contains a static data member, 5928 // the program is ill-formed. C++11 drops this restriction. 5929 if (RD->isUnion()) 5930 Diag(D.getIdentifierLoc(), 5931 getLangOpts().CPlusPlus11 5932 ? diag::warn_cxx98_compat_static_data_member_in_union 5933 : diag::ext_static_data_member_in_union) << Name; 5934 // We conservatively disallow static data members in anonymous structs. 5935 else if (!RD->getDeclName()) 5936 Diag(D.getIdentifierLoc(), 5937 diag::err_static_data_member_not_allowed_in_anon_struct) 5938 << Name << RD->isUnion(); 5939 } 5940 } 5941 5942 // Match up the template parameter lists with the scope specifier, then 5943 // determine whether we have a template or a template specialization. 5944 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5945 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5946 D.getCXXScopeSpec(), 5947 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5948 ? D.getName().TemplateId 5949 : nullptr, 5950 TemplateParamLists, 5951 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5952 5953 if (TemplateParams) { 5954 if (!TemplateParams->size() && 5955 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5956 // There is an extraneous 'template<>' for this variable. Complain 5957 // about it, but allow the declaration of the variable. 5958 Diag(TemplateParams->getTemplateLoc(), 5959 diag::err_template_variable_noparams) 5960 << II 5961 << SourceRange(TemplateParams->getTemplateLoc(), 5962 TemplateParams->getRAngleLoc()); 5963 TemplateParams = nullptr; 5964 } else { 5965 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5966 // This is an explicit specialization or a partial specialization. 5967 // FIXME: Check that we can declare a specialization here. 5968 IsVariableTemplateSpecialization = true; 5969 IsPartialSpecialization = TemplateParams->size() > 0; 5970 } else { // if (TemplateParams->size() > 0) 5971 // This is a template declaration. 5972 IsVariableTemplate = true; 5973 5974 // Check that we can declare a template here. 5975 if (CheckTemplateDeclScope(S, TemplateParams)) 5976 return nullptr; 5977 5978 // Only C++1y supports variable templates (N3651). 5979 Diag(D.getIdentifierLoc(), 5980 getLangOpts().CPlusPlus14 5981 ? diag::warn_cxx11_compat_variable_template 5982 : diag::ext_variable_template); 5983 } 5984 } 5985 } else { 5986 assert( 5987 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 5988 "should have a 'template<>' for this decl"); 5989 } 5990 5991 if (IsVariableTemplateSpecialization) { 5992 SourceLocation TemplateKWLoc = 5993 TemplateParamLists.size() > 0 5994 ? TemplateParamLists[0]->getTemplateLoc() 5995 : SourceLocation(); 5996 DeclResult Res = ActOnVarTemplateSpecialization( 5997 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5998 IsPartialSpecialization); 5999 if (Res.isInvalid()) 6000 return nullptr; 6001 NewVD = cast<VarDecl>(Res.get()); 6002 AddToScope = false; 6003 } else 6004 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6005 D.getIdentifierLoc(), II, R, TInfo, SC); 6006 6007 // If this is supposed to be a variable template, create it as such. 6008 if (IsVariableTemplate) { 6009 NewTemplate = 6010 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6011 TemplateParams, NewVD); 6012 NewVD->setDescribedVarTemplate(NewTemplate); 6013 } 6014 6015 // If this decl has an auto type in need of deduction, make a note of the 6016 // Decl so we can diagnose uses of it in its own initializer. 6017 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6018 ParsingInitForAutoVars.insert(NewVD); 6019 6020 if (D.isInvalidType() || Invalid) { 6021 NewVD->setInvalidDecl(); 6022 if (NewTemplate) 6023 NewTemplate->setInvalidDecl(); 6024 } 6025 6026 SetNestedNameSpecifier(NewVD, D); 6027 6028 // If we have any template parameter lists that don't directly belong to 6029 // the variable (matching the scope specifier), store them. 6030 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6031 if (TemplateParamLists.size() > VDTemplateParamLists) 6032 NewVD->setTemplateParameterListsInfo( 6033 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6034 6035 if (D.getDeclSpec().isConstexprSpecified()) 6036 NewVD->setConstexpr(true); 6037 6038 if (D.getDeclSpec().isConceptSpecified()) { 6039 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6040 VTD->setConcept(); 6041 6042 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6043 // be declared with the thread_local, inline, friend, or constexpr 6044 // specifiers, [...] 6045 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6046 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6047 diag::err_concept_decl_invalid_specifiers) 6048 << 0 << 0; 6049 NewVD->setInvalidDecl(true); 6050 } 6051 6052 if (D.getDeclSpec().isConstexprSpecified()) { 6053 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6054 diag::err_concept_decl_invalid_specifiers) 6055 << 0 << 3; 6056 NewVD->setInvalidDecl(true); 6057 } 6058 6059 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6060 // applied only to the definition of a function template or variable 6061 // template, declared in namespace scope. 6062 if (IsVariableTemplateSpecialization) { 6063 Diag(D.getDeclSpec().getConceptSpecLoc(), 6064 diag::err_concept_specified_specialization) 6065 << (IsPartialSpecialization ? 2 : 1); 6066 } 6067 6068 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6069 // following restrictions: 6070 // - The declared type shall have the type bool. 6071 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6072 !NewVD->isInvalidDecl()) { 6073 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6074 NewVD->setInvalidDecl(true); 6075 } 6076 } 6077 } 6078 6079 // Set the lexical context. If the declarator has a C++ scope specifier, the 6080 // lexical context will be different from the semantic context. 6081 NewVD->setLexicalDeclContext(CurContext); 6082 if (NewTemplate) 6083 NewTemplate->setLexicalDeclContext(CurContext); 6084 6085 if (IsLocalExternDecl) 6086 NewVD->setLocalExternDecl(); 6087 6088 bool EmitTLSUnsupportedError = false; 6089 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6090 // C++11 [dcl.stc]p4: 6091 // When thread_local is applied to a variable of block scope the 6092 // storage-class-specifier static is implied if it does not appear 6093 // explicitly. 6094 // Core issue: 'static' is not implied if the variable is declared 6095 // 'extern'. 6096 if (NewVD->hasLocalStorage() && 6097 (SCSpec != DeclSpec::SCS_unspecified || 6098 TSCS != DeclSpec::TSCS_thread_local || 6099 !DC->isFunctionOrMethod())) 6100 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6101 diag::err_thread_non_global) 6102 << DeclSpec::getSpecifierName(TSCS); 6103 else if (!Context.getTargetInfo().isTLSSupported()) { 6104 if (getLangOpts().CUDA) { 6105 // Postpone error emission until we've collected attributes required to 6106 // figure out whether it's a host or device variable and whether the 6107 // error should be ignored. 6108 EmitTLSUnsupportedError = true; 6109 // We still need to mark the variable as TLS so it shows up in AST with 6110 // proper storage class for other tools to use even if we're not going 6111 // to emit any code for it. 6112 NewVD->setTSCSpec(TSCS); 6113 } else 6114 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6115 diag::err_thread_unsupported); 6116 } else 6117 NewVD->setTSCSpec(TSCS); 6118 } 6119 6120 // C99 6.7.4p3 6121 // An inline definition of a function with external linkage shall 6122 // not contain a definition of a modifiable object with static or 6123 // thread storage duration... 6124 // We only apply this when the function is required to be defined 6125 // elsewhere, i.e. when the function is not 'extern inline'. Note 6126 // that a local variable with thread storage duration still has to 6127 // be marked 'static'. Also note that it's possible to get these 6128 // semantics in C++ using __attribute__((gnu_inline)). 6129 if (SC == SC_Static && S->getFnParent() != nullptr && 6130 !NewVD->getType().isConstQualified()) { 6131 FunctionDecl *CurFD = getCurFunctionDecl(); 6132 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6133 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6134 diag::warn_static_local_in_extern_inline); 6135 MaybeSuggestAddingStaticToDecl(CurFD); 6136 } 6137 } 6138 6139 if (D.getDeclSpec().isModulePrivateSpecified()) { 6140 if (IsVariableTemplateSpecialization) 6141 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6142 << (IsPartialSpecialization ? 1 : 0) 6143 << FixItHint::CreateRemoval( 6144 D.getDeclSpec().getModulePrivateSpecLoc()); 6145 else if (IsExplicitSpecialization) 6146 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6147 << 2 6148 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6149 else if (NewVD->hasLocalStorage()) 6150 Diag(NewVD->getLocation(), diag::err_module_private_local) 6151 << 0 << NewVD->getDeclName() 6152 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6153 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6154 else { 6155 NewVD->setModulePrivate(); 6156 if (NewTemplate) 6157 NewTemplate->setModulePrivate(); 6158 } 6159 } 6160 6161 // Handle attributes prior to checking for duplicates in MergeVarDecl 6162 ProcessDeclAttributes(S, NewVD, D); 6163 6164 if (getLangOpts().CUDA) { 6165 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6166 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6167 diag::err_thread_unsupported); 6168 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6169 // storage [duration]." 6170 if (SC == SC_None && S->getFnParent() != nullptr && 6171 (NewVD->hasAttr<CUDASharedAttr>() || 6172 NewVD->hasAttr<CUDAConstantAttr>())) { 6173 NewVD->setStorageClass(SC_Static); 6174 } 6175 } 6176 6177 // Ensure that dllimport globals without explicit storage class are treated as 6178 // extern. The storage class is set above using parsed attributes. Now we can 6179 // check the VarDecl itself. 6180 assert(!NewVD->hasAttr<DLLImportAttr>() || 6181 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6182 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6183 6184 // In auto-retain/release, infer strong retension for variables of 6185 // retainable type. 6186 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6187 NewVD->setInvalidDecl(); 6188 6189 // Handle GNU asm-label extension (encoded as an attribute). 6190 if (Expr *E = (Expr*)D.getAsmLabel()) { 6191 // The parser guarantees this is a string. 6192 StringLiteral *SE = cast<StringLiteral>(E); 6193 StringRef Label = SE->getString(); 6194 if (S->getFnParent() != nullptr) { 6195 switch (SC) { 6196 case SC_None: 6197 case SC_Auto: 6198 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6199 break; 6200 case SC_Register: 6201 // Local Named register 6202 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6203 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6204 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6205 break; 6206 case SC_Static: 6207 case SC_Extern: 6208 case SC_PrivateExtern: 6209 break; 6210 } 6211 } else if (SC == SC_Register) { 6212 // Global Named register 6213 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6214 const auto &TI = Context.getTargetInfo(); 6215 bool HasSizeMismatch; 6216 6217 if (!TI.isValidGCCRegisterName(Label)) 6218 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6219 else if (!TI.validateGlobalRegisterVariable(Label, 6220 Context.getTypeSize(R), 6221 HasSizeMismatch)) 6222 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6223 else if (HasSizeMismatch) 6224 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6225 } 6226 6227 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6228 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6229 NewVD->setInvalidDecl(true); 6230 } 6231 } 6232 6233 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6234 Context, Label, 0)); 6235 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6236 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6237 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6238 if (I != ExtnameUndeclaredIdentifiers.end()) { 6239 if (isDeclExternC(NewVD)) { 6240 NewVD->addAttr(I->second); 6241 ExtnameUndeclaredIdentifiers.erase(I); 6242 } else 6243 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6244 << /*Variable*/1 << NewVD; 6245 } 6246 } 6247 6248 // Diagnose shadowed variables before filtering for scope. 6249 if (D.getCXXScopeSpec().isEmpty()) 6250 CheckShadow(S, NewVD, Previous); 6251 6252 // Don't consider existing declarations that are in a different 6253 // scope and are out-of-semantic-context declarations (if the new 6254 // declaration has linkage). 6255 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6256 D.getCXXScopeSpec().isNotEmpty() || 6257 IsExplicitSpecialization || 6258 IsVariableTemplateSpecialization); 6259 6260 // Check whether the previous declaration is in the same block scope. This 6261 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6262 if (getLangOpts().CPlusPlus && 6263 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6264 NewVD->setPreviousDeclInSameBlockScope( 6265 Previous.isSingleResult() && !Previous.isShadowed() && 6266 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6267 6268 if (!getLangOpts().CPlusPlus) { 6269 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6270 } else { 6271 // If this is an explicit specialization of a static data member, check it. 6272 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6273 CheckMemberSpecialization(NewVD, Previous)) 6274 NewVD->setInvalidDecl(); 6275 6276 // Merge the decl with the existing one if appropriate. 6277 if (!Previous.empty()) { 6278 if (Previous.isSingleResult() && 6279 isa<FieldDecl>(Previous.getFoundDecl()) && 6280 D.getCXXScopeSpec().isSet()) { 6281 // The user tried to define a non-static data member 6282 // out-of-line (C++ [dcl.meaning]p1). 6283 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6284 << D.getCXXScopeSpec().getRange(); 6285 Previous.clear(); 6286 NewVD->setInvalidDecl(); 6287 } 6288 } else if (D.getCXXScopeSpec().isSet()) { 6289 // No previous declaration in the qualifying scope. 6290 Diag(D.getIdentifierLoc(), diag::err_no_member) 6291 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6292 << D.getCXXScopeSpec().getRange(); 6293 NewVD->setInvalidDecl(); 6294 } 6295 6296 if (!IsVariableTemplateSpecialization) 6297 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6298 6299 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6300 // an explicit specialization (14.8.3) or a partial specialization of a 6301 // concept definition. 6302 if (IsVariableTemplateSpecialization && 6303 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6304 Previous.isSingleResult()) { 6305 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6306 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6307 if (VarTmpl->isConcept()) { 6308 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6309 << 1 /*variable*/ 6310 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6311 : 1 /*explicitly specialized*/); 6312 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6313 NewVD->setInvalidDecl(); 6314 } 6315 } 6316 } 6317 6318 if (NewTemplate) { 6319 VarTemplateDecl *PrevVarTemplate = 6320 NewVD->getPreviousDecl() 6321 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6322 : nullptr; 6323 6324 // Check the template parameter list of this declaration, possibly 6325 // merging in the template parameter list from the previous variable 6326 // template declaration. 6327 if (CheckTemplateParameterList( 6328 TemplateParams, 6329 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6330 : nullptr, 6331 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6332 DC->isDependentContext()) 6333 ? TPC_ClassTemplateMember 6334 : TPC_VarTemplate)) 6335 NewVD->setInvalidDecl(); 6336 6337 // If we are providing an explicit specialization of a static variable 6338 // template, make a note of that. 6339 if (PrevVarTemplate && 6340 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6341 PrevVarTemplate->setMemberSpecialization(); 6342 } 6343 } 6344 6345 ProcessPragmaWeak(S, NewVD); 6346 6347 // If this is the first declaration of an extern C variable, update 6348 // the map of such variables. 6349 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6350 isIncompleteDeclExternC(*this, NewVD)) 6351 RegisterLocallyScopedExternCDecl(NewVD, S); 6352 6353 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6354 Decl *ManglingContextDecl; 6355 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6356 NewVD->getDeclContext(), ManglingContextDecl)) { 6357 Context.setManglingNumber( 6358 NewVD, MCtx->getManglingNumber( 6359 NewVD, getMSManglingNumber(getLangOpts(), S))); 6360 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6361 } 6362 } 6363 6364 // Special handling of variable named 'main'. 6365 if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") && 6366 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6367 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6368 6369 // C++ [basic.start.main]p3 6370 // A program that declares a variable main at global scope is ill-formed. 6371 if (getLangOpts().CPlusPlus) 6372 Diag(D.getLocStart(), diag::err_main_global_variable); 6373 6374 // In C, and external-linkage variable named main results in undefined 6375 // behavior. 6376 else if (NewVD->hasExternalFormalLinkage()) 6377 Diag(D.getLocStart(), diag::warn_main_redefined); 6378 } 6379 6380 if (D.isRedeclaration() && !Previous.empty()) { 6381 checkDLLAttributeRedeclaration( 6382 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6383 IsExplicitSpecialization); 6384 } 6385 6386 if (NewTemplate) { 6387 if (NewVD->isInvalidDecl()) 6388 NewTemplate->setInvalidDecl(); 6389 ActOnDocumentableDecl(NewTemplate); 6390 return NewTemplate; 6391 } 6392 6393 return NewVD; 6394 } 6395 6396 /// Enum describing the %select options in diag::warn_decl_shadow. 6397 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field }; 6398 6399 /// Determine what kind of declaration we're shadowing. 6400 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6401 const DeclContext *OldDC) { 6402 if (isa<RecordDecl>(OldDC)) 6403 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6404 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6405 } 6406 6407 /// \brief Diagnose variable or built-in function shadowing. Implements 6408 /// -Wshadow. 6409 /// 6410 /// This method is called whenever a VarDecl is added to a "useful" 6411 /// scope. 6412 /// 6413 /// \param S the scope in which the shadowing name is being declared 6414 /// \param R the lookup of the name 6415 /// 6416 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6417 // Return if warning is ignored. 6418 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6419 return; 6420 6421 // Don't diagnose declarations at file scope. 6422 if (D->hasGlobalStorage()) 6423 return; 6424 6425 DeclContext *NewDC = D->getDeclContext(); 6426 6427 // Only diagnose if we're shadowing an unambiguous field or variable. 6428 if (R.getResultKind() != LookupResult::Found) 6429 return; 6430 6431 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6432 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6433 return; 6434 6435 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6436 // Fields are not shadowed by variables in C++ static methods. 6437 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6438 if (MD->isStatic()) 6439 return; 6440 6441 // Fields shadowed by constructor parameters are a special case. Usually 6442 // the constructor initializes the field with the parameter. 6443 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) { 6444 // Remember that this was shadowed so we can either warn about its 6445 // modification or its existence depending on warning settings. 6446 D = D->getCanonicalDecl(); 6447 ShadowingDecls.insert({D, FD}); 6448 return; 6449 } 6450 } 6451 6452 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6453 if (shadowedVar->isExternC()) { 6454 // For shadowing external vars, make sure that we point to the global 6455 // declaration, not a locally scoped extern declaration. 6456 for (auto I : shadowedVar->redecls()) 6457 if (I->isFileVarDecl()) { 6458 ShadowedDecl = I; 6459 break; 6460 } 6461 } 6462 6463 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6464 6465 // Only warn about certain kinds of shadowing for class members. 6466 if (NewDC && NewDC->isRecord()) { 6467 // In particular, don't warn about shadowing non-class members. 6468 if (!OldDC->isRecord()) 6469 return; 6470 6471 // TODO: should we warn about static data members shadowing 6472 // static data members from base classes? 6473 6474 // TODO: don't diagnose for inaccessible shadowed members. 6475 // This is hard to do perfectly because we might friend the 6476 // shadowing context, but that's just a false negative. 6477 } 6478 6479 6480 DeclarationName Name = R.getLookupName(); 6481 6482 // Emit warning and note. 6483 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6484 return; 6485 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6486 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6487 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6488 } 6489 6490 /// \brief Check -Wshadow without the advantage of a previous lookup. 6491 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6492 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6493 return; 6494 6495 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6496 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6497 LookupName(R, S); 6498 CheckShadow(S, D, R); 6499 } 6500 6501 /// Check if 'E', which is an expression that is about to be modified, refers 6502 /// to a constructor parameter that shadows a field. 6503 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 6504 // Quickly ignore expressions that can't be shadowing ctor parameters. 6505 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 6506 return; 6507 E = E->IgnoreParenImpCasts(); 6508 auto *DRE = dyn_cast<DeclRefExpr>(E); 6509 if (!DRE) 6510 return; 6511 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 6512 auto I = ShadowingDecls.find(D); 6513 if (I == ShadowingDecls.end()) 6514 return; 6515 const NamedDecl *ShadowedDecl = I->second; 6516 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6517 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 6518 Diag(D->getLocation(), diag::note_var_declared_here) << D; 6519 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6520 6521 // Avoid issuing multiple warnings about the same decl. 6522 ShadowingDecls.erase(I); 6523 } 6524 6525 /// Check for conflict between this global or extern "C" declaration and 6526 /// previous global or extern "C" declarations. This is only used in C++. 6527 template<typename T> 6528 static bool checkGlobalOrExternCConflict( 6529 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6530 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6531 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6532 6533 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6534 // The common case: this global doesn't conflict with any extern "C" 6535 // declaration. 6536 return false; 6537 } 6538 6539 if (Prev) { 6540 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6541 // Both the old and new declarations have C language linkage. This is a 6542 // redeclaration. 6543 Previous.clear(); 6544 Previous.addDecl(Prev); 6545 return true; 6546 } 6547 6548 // This is a global, non-extern "C" declaration, and there is a previous 6549 // non-global extern "C" declaration. Diagnose if this is a variable 6550 // declaration. 6551 if (!isa<VarDecl>(ND)) 6552 return false; 6553 } else { 6554 // The declaration is extern "C". Check for any declaration in the 6555 // translation unit which might conflict. 6556 if (IsGlobal) { 6557 // We have already performed the lookup into the translation unit. 6558 IsGlobal = false; 6559 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6560 I != E; ++I) { 6561 if (isa<VarDecl>(*I)) { 6562 Prev = *I; 6563 break; 6564 } 6565 } 6566 } else { 6567 DeclContext::lookup_result R = 6568 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6569 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6570 I != E; ++I) { 6571 if (isa<VarDecl>(*I)) { 6572 Prev = *I; 6573 break; 6574 } 6575 // FIXME: If we have any other entity with this name in global scope, 6576 // the declaration is ill-formed, but that is a defect: it breaks the 6577 // 'stat' hack, for instance. Only variables can have mangled name 6578 // clashes with extern "C" declarations, so only they deserve a 6579 // diagnostic. 6580 } 6581 } 6582 6583 if (!Prev) 6584 return false; 6585 } 6586 6587 // Use the first declaration's location to ensure we point at something which 6588 // is lexically inside an extern "C" linkage-spec. 6589 assert(Prev && "should have found a previous declaration to diagnose"); 6590 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6591 Prev = FD->getFirstDecl(); 6592 else 6593 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6594 6595 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6596 << IsGlobal << ND; 6597 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6598 << IsGlobal; 6599 return false; 6600 } 6601 6602 /// Apply special rules for handling extern "C" declarations. Returns \c true 6603 /// if we have found that this is a redeclaration of some prior entity. 6604 /// 6605 /// Per C++ [dcl.link]p6: 6606 /// Two declarations [for a function or variable] with C language linkage 6607 /// with the same name that appear in different scopes refer to the same 6608 /// [entity]. An entity with C language linkage shall not be declared with 6609 /// the same name as an entity in global scope. 6610 template<typename T> 6611 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6612 LookupResult &Previous) { 6613 if (!S.getLangOpts().CPlusPlus) { 6614 // In C, when declaring a global variable, look for a corresponding 'extern' 6615 // variable declared in function scope. We don't need this in C++, because 6616 // we find local extern decls in the surrounding file-scope DeclContext. 6617 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6618 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6619 Previous.clear(); 6620 Previous.addDecl(Prev); 6621 return true; 6622 } 6623 } 6624 return false; 6625 } 6626 6627 // A declaration in the translation unit can conflict with an extern "C" 6628 // declaration. 6629 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6630 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6631 6632 // An extern "C" declaration can conflict with a declaration in the 6633 // translation unit or can be a redeclaration of an extern "C" declaration 6634 // in another scope. 6635 if (isIncompleteDeclExternC(S,ND)) 6636 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6637 6638 // Neither global nor extern "C": nothing to do. 6639 return false; 6640 } 6641 6642 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6643 // If the decl is already known invalid, don't check it. 6644 if (NewVD->isInvalidDecl()) 6645 return; 6646 6647 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6648 QualType T = TInfo->getType(); 6649 6650 // Defer checking an 'auto' type until its initializer is attached. 6651 if (T->isUndeducedType()) 6652 return; 6653 6654 if (NewVD->hasAttrs()) 6655 CheckAlignasUnderalignment(NewVD); 6656 6657 if (T->isObjCObjectType()) { 6658 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6659 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6660 T = Context.getObjCObjectPointerType(T); 6661 NewVD->setType(T); 6662 } 6663 6664 // Emit an error if an address space was applied to decl with local storage. 6665 // This includes arrays of objects with address space qualifiers, but not 6666 // automatic variables that point to other address spaces. 6667 // ISO/IEC TR 18037 S5.1.2 6668 if (!getLangOpts().OpenCL 6669 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6670 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6671 NewVD->setInvalidDecl(); 6672 return; 6673 } 6674 6675 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 6676 // scope. 6677 if (getLangOpts().OpenCLVersion == 120 && 6678 !getOpenCLOptions().cl_clang_storage_class_specifiers && 6679 NewVD->isStaticLocal()) { 6680 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6681 NewVD->setInvalidDecl(); 6682 return; 6683 } 6684 6685 if (getLangOpts().OpenCL) { 6686 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 6687 if (NewVD->hasAttr<BlocksAttr>()) { 6688 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 6689 return; 6690 } 6691 6692 if (T->isBlockPointerType()) { 6693 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 6694 // can't use 'extern' storage class. 6695 if (!T.isConstQualified()) { 6696 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 6697 << 0 /*const*/; 6698 NewVD->setInvalidDecl(); 6699 return; 6700 } 6701 if (NewVD->hasExternalStorage()) { 6702 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 6703 NewVD->setInvalidDecl(); 6704 return; 6705 } 6706 // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported. 6707 // TODO: this check is not enough as it doesn't diagnose the typedef 6708 const BlockPointerType *BlkTy = T->getAs<BlockPointerType>(); 6709 const FunctionProtoType *FTy = 6710 BlkTy->getPointeeType()->getAs<FunctionProtoType>(); 6711 if (FTy && FTy->isVariadic()) { 6712 Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic) 6713 << T << NewVD->getSourceRange(); 6714 NewVD->setInvalidDecl(); 6715 return; 6716 } 6717 } 6718 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6719 // __constant address space. 6720 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6721 // variables inside a function can also be declared in the global 6722 // address space. 6723 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 6724 NewVD->hasExternalStorage()) { 6725 if (!T->isSamplerT() && 6726 !(T.getAddressSpace() == LangAS::opencl_constant || 6727 (T.getAddressSpace() == LangAS::opencl_global && 6728 getLangOpts().OpenCLVersion == 200))) { 6729 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 6730 if (getLangOpts().OpenCLVersion == 200) 6731 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6732 << Scope << "global or constant"; 6733 else 6734 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6735 << Scope << "constant"; 6736 NewVD->setInvalidDecl(); 6737 return; 6738 } 6739 } else { 6740 if (T.getAddressSpace() == LangAS::opencl_global) { 6741 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6742 << 1 /*is any function*/ << "global"; 6743 NewVD->setInvalidDecl(); 6744 return; 6745 } 6746 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 6747 // in functions. 6748 if (T.getAddressSpace() == LangAS::opencl_constant || 6749 T.getAddressSpace() == LangAS::opencl_local) { 6750 FunctionDecl *FD = getCurFunctionDecl(); 6751 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 6752 if (T.getAddressSpace() == LangAS::opencl_constant) 6753 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6754 << 0 /*non-kernel only*/ << "constant"; 6755 else 6756 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6757 << 0 /*non-kernel only*/ << "local"; 6758 NewVD->setInvalidDecl(); 6759 return; 6760 } 6761 } 6762 } 6763 } 6764 6765 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6766 && !NewVD->hasAttr<BlocksAttr>()) { 6767 if (getLangOpts().getGC() != LangOptions::NonGC) 6768 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6769 else { 6770 assert(!getLangOpts().ObjCAutoRefCount); 6771 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6772 } 6773 } 6774 6775 bool isVM = T->isVariablyModifiedType(); 6776 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6777 NewVD->hasAttr<BlocksAttr>()) 6778 getCurFunction()->setHasBranchProtectedScope(); 6779 6780 if ((isVM && NewVD->hasLinkage()) || 6781 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6782 bool SizeIsNegative; 6783 llvm::APSInt Oversized; 6784 TypeSourceInfo *FixedTInfo = 6785 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6786 SizeIsNegative, Oversized); 6787 if (!FixedTInfo && T->isVariableArrayType()) { 6788 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6789 // FIXME: This won't give the correct result for 6790 // int a[10][n]; 6791 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6792 6793 if (NewVD->isFileVarDecl()) 6794 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6795 << SizeRange; 6796 else if (NewVD->isStaticLocal()) 6797 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6798 << SizeRange; 6799 else 6800 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6801 << SizeRange; 6802 NewVD->setInvalidDecl(); 6803 return; 6804 } 6805 6806 if (!FixedTInfo) { 6807 if (NewVD->isFileVarDecl()) 6808 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6809 else 6810 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6811 NewVD->setInvalidDecl(); 6812 return; 6813 } 6814 6815 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6816 NewVD->setType(FixedTInfo->getType()); 6817 NewVD->setTypeSourceInfo(FixedTInfo); 6818 } 6819 6820 if (T->isVoidType()) { 6821 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6822 // of objects and functions. 6823 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6824 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6825 << T; 6826 NewVD->setInvalidDecl(); 6827 return; 6828 } 6829 } 6830 6831 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6832 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6833 NewVD->setInvalidDecl(); 6834 return; 6835 } 6836 6837 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6838 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6839 NewVD->setInvalidDecl(); 6840 return; 6841 } 6842 6843 if (NewVD->isConstexpr() && !T->isDependentType() && 6844 RequireLiteralType(NewVD->getLocation(), T, 6845 diag::err_constexpr_var_non_literal)) { 6846 NewVD->setInvalidDecl(); 6847 return; 6848 } 6849 } 6850 6851 /// \brief Perform semantic checking on a newly-created variable 6852 /// declaration. 6853 /// 6854 /// This routine performs all of the type-checking required for a 6855 /// variable declaration once it has been built. It is used both to 6856 /// check variables after they have been parsed and their declarators 6857 /// have been translated into a declaration, and to check variables 6858 /// that have been instantiated from a template. 6859 /// 6860 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6861 /// 6862 /// Returns true if the variable declaration is a redeclaration. 6863 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6864 CheckVariableDeclarationType(NewVD); 6865 6866 // If the decl is already known invalid, don't check it. 6867 if (NewVD->isInvalidDecl()) 6868 return false; 6869 6870 // If we did not find anything by this name, look for a non-visible 6871 // extern "C" declaration with the same name. 6872 if (Previous.empty() && 6873 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6874 Previous.setShadowed(); 6875 6876 if (!Previous.empty()) { 6877 MergeVarDecl(NewVD, Previous); 6878 return true; 6879 } 6880 return false; 6881 } 6882 6883 namespace { 6884 struct FindOverriddenMethod { 6885 Sema *S; 6886 CXXMethodDecl *Method; 6887 6888 /// Member lookup function that determines whether a given C++ 6889 /// method overrides a method in a base class, to be used with 6890 /// CXXRecordDecl::lookupInBases(). 6891 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 6892 RecordDecl *BaseRecord = 6893 Specifier->getType()->getAs<RecordType>()->getDecl(); 6894 6895 DeclarationName Name = Method->getDeclName(); 6896 6897 // FIXME: Do we care about other names here too? 6898 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6899 // We really want to find the base class destructor here. 6900 QualType T = S->Context.getTypeDeclType(BaseRecord); 6901 CanQualType CT = S->Context.getCanonicalType(T); 6902 6903 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 6904 } 6905 6906 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 6907 Path.Decls = Path.Decls.slice(1)) { 6908 NamedDecl *D = Path.Decls.front(); 6909 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6910 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 6911 return true; 6912 } 6913 } 6914 6915 return false; 6916 } 6917 }; 6918 6919 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6920 } // end anonymous namespace 6921 6922 /// \brief Report an error regarding overriding, along with any relevant 6923 /// overriden methods. 6924 /// 6925 /// \param DiagID the primary error to report. 6926 /// \param MD the overriding method. 6927 /// \param OEK which overrides to include as notes. 6928 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6929 OverrideErrorKind OEK = OEK_All) { 6930 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6931 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6932 E = MD->end_overridden_methods(); 6933 I != E; ++I) { 6934 // This check (& the OEK parameter) could be replaced by a predicate, but 6935 // without lambdas that would be overkill. This is still nicer than writing 6936 // out the diag loop 3 times. 6937 if ((OEK == OEK_All) || 6938 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6939 (OEK == OEK_Deleted && (*I)->isDeleted())) 6940 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6941 } 6942 } 6943 6944 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6945 /// and if so, check that it's a valid override and remember it. 6946 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6947 // Look for methods in base classes that this method might override. 6948 CXXBasePaths Paths; 6949 FindOverriddenMethod FOM; 6950 FOM.Method = MD; 6951 FOM.S = this; 6952 bool hasDeletedOverridenMethods = false; 6953 bool hasNonDeletedOverridenMethods = false; 6954 bool AddedAny = false; 6955 if (DC->lookupInBases(FOM, Paths)) { 6956 for (auto *I : Paths.found_decls()) { 6957 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6958 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6959 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6960 !CheckOverridingFunctionAttributes(MD, OldMD) && 6961 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6962 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6963 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6964 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6965 AddedAny = true; 6966 } 6967 } 6968 } 6969 } 6970 6971 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6972 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6973 } 6974 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6975 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6976 } 6977 6978 return AddedAny; 6979 } 6980 6981 namespace { 6982 // Struct for holding all of the extra arguments needed by 6983 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6984 struct ActOnFDArgs { 6985 Scope *S; 6986 Declarator &D; 6987 MultiTemplateParamsArg TemplateParamLists; 6988 bool AddToScope; 6989 }; 6990 } // end anonymous namespace 6991 6992 namespace { 6993 6994 // Callback to only accept typo corrections that have a non-zero edit distance. 6995 // Also only accept corrections that have the same parent decl. 6996 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6997 public: 6998 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6999 CXXRecordDecl *Parent) 7000 : Context(Context), OriginalFD(TypoFD), 7001 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7002 7003 bool ValidateCandidate(const TypoCorrection &candidate) override { 7004 if (candidate.getEditDistance() == 0) 7005 return false; 7006 7007 SmallVector<unsigned, 1> MismatchedParams; 7008 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7009 CDeclEnd = candidate.end(); 7010 CDecl != CDeclEnd; ++CDecl) { 7011 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7012 7013 if (FD && !FD->hasBody() && 7014 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7015 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7016 CXXRecordDecl *Parent = MD->getParent(); 7017 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7018 return true; 7019 } else if (!ExpectedParent) { 7020 return true; 7021 } 7022 } 7023 } 7024 7025 return false; 7026 } 7027 7028 private: 7029 ASTContext &Context; 7030 FunctionDecl *OriginalFD; 7031 CXXRecordDecl *ExpectedParent; 7032 }; 7033 7034 } // end anonymous namespace 7035 7036 /// \brief Generate diagnostics for an invalid function redeclaration. 7037 /// 7038 /// This routine handles generating the diagnostic messages for an invalid 7039 /// function redeclaration, including finding possible similar declarations 7040 /// or performing typo correction if there are no previous declarations with 7041 /// the same name. 7042 /// 7043 /// Returns a NamedDecl iff typo correction was performed and substituting in 7044 /// the new declaration name does not cause new errors. 7045 static NamedDecl *DiagnoseInvalidRedeclaration( 7046 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7047 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7048 DeclarationName Name = NewFD->getDeclName(); 7049 DeclContext *NewDC = NewFD->getDeclContext(); 7050 SmallVector<unsigned, 1> MismatchedParams; 7051 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7052 TypoCorrection Correction; 7053 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7054 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7055 : diag::err_member_decl_does_not_match; 7056 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7057 IsLocalFriend ? Sema::LookupLocalFriendName 7058 : Sema::LookupOrdinaryName, 7059 Sema::ForRedeclaration); 7060 7061 NewFD->setInvalidDecl(); 7062 if (IsLocalFriend) 7063 SemaRef.LookupName(Prev, S); 7064 else 7065 SemaRef.LookupQualifiedName(Prev, NewDC); 7066 assert(!Prev.isAmbiguous() && 7067 "Cannot have an ambiguity in previous-declaration lookup"); 7068 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7069 if (!Prev.empty()) { 7070 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7071 Func != FuncEnd; ++Func) { 7072 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7073 if (FD && 7074 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7075 // Add 1 to the index so that 0 can mean the mismatch didn't 7076 // involve a parameter 7077 unsigned ParamNum = 7078 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7079 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7080 } 7081 } 7082 // If the qualified name lookup yielded nothing, try typo correction 7083 } else if ((Correction = SemaRef.CorrectTypo( 7084 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7085 &ExtraArgs.D.getCXXScopeSpec(), 7086 llvm::make_unique<DifferentNameValidatorCCC>( 7087 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7088 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7089 // Set up everything for the call to ActOnFunctionDeclarator 7090 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7091 ExtraArgs.D.getIdentifierLoc()); 7092 Previous.clear(); 7093 Previous.setLookupName(Correction.getCorrection()); 7094 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7095 CDeclEnd = Correction.end(); 7096 CDecl != CDeclEnd; ++CDecl) { 7097 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7098 if (FD && !FD->hasBody() && 7099 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7100 Previous.addDecl(FD); 7101 } 7102 } 7103 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7104 7105 NamedDecl *Result; 7106 // Retry building the function declaration with the new previous 7107 // declarations, and with errors suppressed. 7108 { 7109 // Trap errors. 7110 Sema::SFINAETrap Trap(SemaRef); 7111 7112 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7113 // pieces need to verify the typo-corrected C++ declaration and hopefully 7114 // eliminate the need for the parameter pack ExtraArgs. 7115 Result = SemaRef.ActOnFunctionDeclarator( 7116 ExtraArgs.S, ExtraArgs.D, 7117 Correction.getCorrectionDecl()->getDeclContext(), 7118 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7119 ExtraArgs.AddToScope); 7120 7121 if (Trap.hasErrorOccurred()) 7122 Result = nullptr; 7123 } 7124 7125 if (Result) { 7126 // Determine which correction we picked. 7127 Decl *Canonical = Result->getCanonicalDecl(); 7128 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7129 I != E; ++I) 7130 if ((*I)->getCanonicalDecl() == Canonical) 7131 Correction.setCorrectionDecl(*I); 7132 7133 SemaRef.diagnoseTypo( 7134 Correction, 7135 SemaRef.PDiag(IsLocalFriend 7136 ? diag::err_no_matching_local_friend_suggest 7137 : diag::err_member_decl_does_not_match_suggest) 7138 << Name << NewDC << IsDefinition); 7139 return Result; 7140 } 7141 7142 // Pretend the typo correction never occurred 7143 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7144 ExtraArgs.D.getIdentifierLoc()); 7145 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7146 Previous.clear(); 7147 Previous.setLookupName(Name); 7148 } 7149 7150 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7151 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7152 7153 bool NewFDisConst = false; 7154 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7155 NewFDisConst = NewMD->isConst(); 7156 7157 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7158 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7159 NearMatch != NearMatchEnd; ++NearMatch) { 7160 FunctionDecl *FD = NearMatch->first; 7161 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7162 bool FDisConst = MD && MD->isConst(); 7163 bool IsMember = MD || !IsLocalFriend; 7164 7165 // FIXME: These notes are poorly worded for the local friend case. 7166 if (unsigned Idx = NearMatch->second) { 7167 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7168 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7169 if (Loc.isInvalid()) Loc = FD->getLocation(); 7170 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7171 : diag::note_local_decl_close_param_match) 7172 << Idx << FDParam->getType() 7173 << NewFD->getParamDecl(Idx - 1)->getType(); 7174 } else if (FDisConst != NewFDisConst) { 7175 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7176 << NewFDisConst << FD->getSourceRange().getEnd(); 7177 } else 7178 SemaRef.Diag(FD->getLocation(), 7179 IsMember ? diag::note_member_def_close_match 7180 : diag::note_local_decl_close_match); 7181 } 7182 return nullptr; 7183 } 7184 7185 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7186 switch (D.getDeclSpec().getStorageClassSpec()) { 7187 default: llvm_unreachable("Unknown storage class!"); 7188 case DeclSpec::SCS_auto: 7189 case DeclSpec::SCS_register: 7190 case DeclSpec::SCS_mutable: 7191 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7192 diag::err_typecheck_sclass_func); 7193 D.setInvalidType(); 7194 break; 7195 case DeclSpec::SCS_unspecified: break; 7196 case DeclSpec::SCS_extern: 7197 if (D.getDeclSpec().isExternInLinkageSpec()) 7198 return SC_None; 7199 return SC_Extern; 7200 case DeclSpec::SCS_static: { 7201 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7202 // C99 6.7.1p5: 7203 // The declaration of an identifier for a function that has 7204 // block scope shall have no explicit storage-class specifier 7205 // other than extern 7206 // See also (C++ [dcl.stc]p4). 7207 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7208 diag::err_static_block_func); 7209 break; 7210 } else 7211 return SC_Static; 7212 } 7213 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7214 } 7215 7216 // No explicit storage class has already been returned 7217 return SC_None; 7218 } 7219 7220 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7221 DeclContext *DC, QualType &R, 7222 TypeSourceInfo *TInfo, 7223 StorageClass SC, 7224 bool &IsVirtualOkay) { 7225 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7226 DeclarationName Name = NameInfo.getName(); 7227 7228 FunctionDecl *NewFD = nullptr; 7229 bool isInline = D.getDeclSpec().isInlineSpecified(); 7230 7231 if (!SemaRef.getLangOpts().CPlusPlus) { 7232 // Determine whether the function was written with a 7233 // prototype. This true when: 7234 // - there is a prototype in the declarator, or 7235 // - the type R of the function is some kind of typedef or other reference 7236 // to a type name (which eventually refers to a function type). 7237 bool HasPrototype = 7238 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7239 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7240 7241 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7242 D.getLocStart(), NameInfo, R, 7243 TInfo, SC, isInline, 7244 HasPrototype, false); 7245 if (D.isInvalidType()) 7246 NewFD->setInvalidDecl(); 7247 7248 return NewFD; 7249 } 7250 7251 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7252 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7253 7254 // Check that the return type is not an abstract class type. 7255 // For record types, this is done by the AbstractClassUsageDiagnoser once 7256 // the class has been completely parsed. 7257 if (!DC->isRecord() && 7258 SemaRef.RequireNonAbstractType( 7259 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7260 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7261 D.setInvalidType(); 7262 7263 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7264 // This is a C++ constructor declaration. 7265 assert(DC->isRecord() && 7266 "Constructors can only be declared in a member context"); 7267 7268 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7269 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7270 D.getLocStart(), NameInfo, 7271 R, TInfo, isExplicit, isInline, 7272 /*isImplicitlyDeclared=*/false, 7273 isConstexpr); 7274 7275 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7276 // This is a C++ destructor declaration. 7277 if (DC->isRecord()) { 7278 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7279 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7280 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7281 SemaRef.Context, Record, 7282 D.getLocStart(), 7283 NameInfo, R, TInfo, isInline, 7284 /*isImplicitlyDeclared=*/false); 7285 7286 // If the class is complete, then we now create the implicit exception 7287 // specification. If the class is incomplete or dependent, we can't do 7288 // it yet. 7289 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7290 Record->getDefinition() && !Record->isBeingDefined() && 7291 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7292 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7293 } 7294 7295 IsVirtualOkay = true; 7296 return NewDD; 7297 7298 } else { 7299 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7300 D.setInvalidType(); 7301 7302 // Create a FunctionDecl to satisfy the function definition parsing 7303 // code path. 7304 return FunctionDecl::Create(SemaRef.Context, DC, 7305 D.getLocStart(), 7306 D.getIdentifierLoc(), Name, R, TInfo, 7307 SC, isInline, 7308 /*hasPrototype=*/true, isConstexpr); 7309 } 7310 7311 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7312 if (!DC->isRecord()) { 7313 SemaRef.Diag(D.getIdentifierLoc(), 7314 diag::err_conv_function_not_member); 7315 return nullptr; 7316 } 7317 7318 SemaRef.CheckConversionDeclarator(D, R, SC); 7319 IsVirtualOkay = true; 7320 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7321 D.getLocStart(), NameInfo, 7322 R, TInfo, isInline, isExplicit, 7323 isConstexpr, SourceLocation()); 7324 7325 } else if (DC->isRecord()) { 7326 // If the name of the function is the same as the name of the record, 7327 // then this must be an invalid constructor that has a return type. 7328 // (The parser checks for a return type and makes the declarator a 7329 // constructor if it has no return type). 7330 if (Name.getAsIdentifierInfo() && 7331 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7332 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7333 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7334 << SourceRange(D.getIdentifierLoc()); 7335 return nullptr; 7336 } 7337 7338 // This is a C++ method declaration. 7339 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7340 cast<CXXRecordDecl>(DC), 7341 D.getLocStart(), NameInfo, R, 7342 TInfo, SC, isInline, 7343 isConstexpr, SourceLocation()); 7344 IsVirtualOkay = !Ret->isStatic(); 7345 return Ret; 7346 } else { 7347 bool isFriend = 7348 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7349 if (!isFriend && SemaRef.CurContext->isRecord()) 7350 return nullptr; 7351 7352 // Determine whether the function was written with a 7353 // prototype. This true when: 7354 // - we're in C++ (where every function has a prototype), 7355 return FunctionDecl::Create(SemaRef.Context, DC, 7356 D.getLocStart(), 7357 NameInfo, R, TInfo, SC, isInline, 7358 true/*HasPrototype*/, isConstexpr); 7359 } 7360 } 7361 7362 enum OpenCLParamType { 7363 ValidKernelParam, 7364 PtrPtrKernelParam, 7365 PtrKernelParam, 7366 PrivatePtrKernelParam, 7367 InvalidKernelParam, 7368 RecordKernelParam 7369 }; 7370 7371 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 7372 if (PT->isPointerType()) { 7373 QualType PointeeType = PT->getPointeeType(); 7374 if (PointeeType->isPointerType()) 7375 return PtrPtrKernelParam; 7376 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 7377 : PtrKernelParam; 7378 } 7379 7380 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7381 // be used as builtin types. 7382 7383 if (PT->isImageType()) 7384 return PtrKernelParam; 7385 7386 if (PT->isBooleanType()) 7387 return InvalidKernelParam; 7388 7389 if (PT->isEventT()) 7390 return InvalidKernelParam; 7391 7392 if (PT->isHalfType()) 7393 return InvalidKernelParam; 7394 7395 if (PT->isRecordType()) 7396 return RecordKernelParam; 7397 7398 return ValidKernelParam; 7399 } 7400 7401 static void checkIsValidOpenCLKernelParameter( 7402 Sema &S, 7403 Declarator &D, 7404 ParmVarDecl *Param, 7405 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7406 QualType PT = Param->getType(); 7407 7408 // Cache the valid types we encounter to avoid rechecking structs that are 7409 // used again 7410 if (ValidTypes.count(PT.getTypePtr())) 7411 return; 7412 7413 switch (getOpenCLKernelParameterType(PT)) { 7414 case PtrPtrKernelParam: 7415 // OpenCL v1.2 s6.9.a: 7416 // A kernel function argument cannot be declared as a 7417 // pointer to a pointer type. 7418 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7419 D.setInvalidType(); 7420 return; 7421 7422 case PrivatePtrKernelParam: 7423 // OpenCL v1.2 s6.9.a: 7424 // A kernel function argument cannot be declared as a 7425 // pointer to the private address space. 7426 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 7427 D.setInvalidType(); 7428 return; 7429 7430 // OpenCL v1.2 s6.9.k: 7431 // Arguments to kernel functions in a program cannot be declared with the 7432 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7433 // uintptr_t or a struct and/or union that contain fields declared to be 7434 // one of these built-in scalar types. 7435 7436 case InvalidKernelParam: 7437 // OpenCL v1.2 s6.8 n: 7438 // A kernel function argument cannot be declared 7439 // of event_t type. 7440 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7441 D.setInvalidType(); 7442 return; 7443 7444 case PtrKernelParam: 7445 case ValidKernelParam: 7446 ValidTypes.insert(PT.getTypePtr()); 7447 return; 7448 7449 case RecordKernelParam: 7450 break; 7451 } 7452 7453 // Track nested structs we will inspect 7454 SmallVector<const Decl *, 4> VisitStack; 7455 7456 // Track where we are in the nested structs. Items will migrate from 7457 // VisitStack to HistoryStack as we do the DFS for bad field. 7458 SmallVector<const FieldDecl *, 4> HistoryStack; 7459 HistoryStack.push_back(nullptr); 7460 7461 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7462 VisitStack.push_back(PD); 7463 7464 assert(VisitStack.back() && "First decl null?"); 7465 7466 do { 7467 const Decl *Next = VisitStack.pop_back_val(); 7468 if (!Next) { 7469 assert(!HistoryStack.empty()); 7470 // Found a marker, we have gone up a level 7471 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7472 ValidTypes.insert(Hist->getType().getTypePtr()); 7473 7474 continue; 7475 } 7476 7477 // Adds everything except the original parameter declaration (which is not a 7478 // field itself) to the history stack. 7479 const RecordDecl *RD; 7480 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7481 HistoryStack.push_back(Field); 7482 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7483 } else { 7484 RD = cast<RecordDecl>(Next); 7485 } 7486 7487 // Add a null marker so we know when we've gone back up a level 7488 VisitStack.push_back(nullptr); 7489 7490 for (const auto *FD : RD->fields()) { 7491 QualType QT = FD->getType(); 7492 7493 if (ValidTypes.count(QT.getTypePtr())) 7494 continue; 7495 7496 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 7497 if (ParamType == ValidKernelParam) 7498 continue; 7499 7500 if (ParamType == RecordKernelParam) { 7501 VisitStack.push_back(FD); 7502 continue; 7503 } 7504 7505 // OpenCL v1.2 s6.9.p: 7506 // Arguments to kernel functions that are declared to be a struct or union 7507 // do not allow OpenCL objects to be passed as elements of the struct or 7508 // union. 7509 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7510 ParamType == PrivatePtrKernelParam) { 7511 S.Diag(Param->getLocation(), 7512 diag::err_record_with_pointers_kernel_param) 7513 << PT->isUnionType() 7514 << PT; 7515 } else { 7516 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7517 } 7518 7519 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7520 << PD->getDeclName(); 7521 7522 // We have an error, now let's go back up through history and show where 7523 // the offending field came from 7524 for (ArrayRef<const FieldDecl *>::const_iterator 7525 I = HistoryStack.begin() + 1, 7526 E = HistoryStack.end(); 7527 I != E; ++I) { 7528 const FieldDecl *OuterField = *I; 7529 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7530 << OuterField->getType(); 7531 } 7532 7533 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7534 << QT->isPointerType() 7535 << QT; 7536 D.setInvalidType(); 7537 return; 7538 } 7539 } while (!VisitStack.empty()); 7540 } 7541 7542 NamedDecl* 7543 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7544 TypeSourceInfo *TInfo, LookupResult &Previous, 7545 MultiTemplateParamsArg TemplateParamLists, 7546 bool &AddToScope) { 7547 QualType R = TInfo->getType(); 7548 7549 assert(R.getTypePtr()->isFunctionType()); 7550 7551 // TODO: consider using NameInfo for diagnostic. 7552 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7553 DeclarationName Name = NameInfo.getName(); 7554 StorageClass SC = getFunctionStorageClass(*this, D); 7555 7556 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7557 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7558 diag::err_invalid_thread) 7559 << DeclSpec::getSpecifierName(TSCS); 7560 7561 if (D.isFirstDeclarationOfMember()) 7562 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7563 D.getIdentifierLoc()); 7564 7565 bool isFriend = false; 7566 FunctionTemplateDecl *FunctionTemplate = nullptr; 7567 bool isExplicitSpecialization = false; 7568 bool isFunctionTemplateSpecialization = false; 7569 7570 bool isDependentClassScopeExplicitSpecialization = false; 7571 bool HasExplicitTemplateArgs = false; 7572 TemplateArgumentListInfo TemplateArgs; 7573 7574 bool isVirtualOkay = false; 7575 7576 DeclContext *OriginalDC = DC; 7577 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7578 7579 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7580 isVirtualOkay); 7581 if (!NewFD) return nullptr; 7582 7583 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7584 NewFD->setTopLevelDeclInObjCContainer(); 7585 7586 // Set the lexical context. If this is a function-scope declaration, or has a 7587 // C++ scope specifier, or is the object of a friend declaration, the lexical 7588 // context will be different from the semantic context. 7589 NewFD->setLexicalDeclContext(CurContext); 7590 7591 if (IsLocalExternDecl) 7592 NewFD->setLocalExternDecl(); 7593 7594 if (getLangOpts().CPlusPlus) { 7595 bool isInline = D.getDeclSpec().isInlineSpecified(); 7596 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7597 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7598 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7599 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7600 isFriend = D.getDeclSpec().isFriendSpecified(); 7601 if (isFriend && !isInline && D.isFunctionDefinition()) { 7602 // C++ [class.friend]p5 7603 // A function can be defined in a friend declaration of a 7604 // class . . . . Such a function is implicitly inline. 7605 NewFD->setImplicitlyInline(); 7606 } 7607 7608 // If this is a method defined in an __interface, and is not a constructor 7609 // or an overloaded operator, then set the pure flag (isVirtual will already 7610 // return true). 7611 if (const CXXRecordDecl *Parent = 7612 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7613 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7614 NewFD->setPure(true); 7615 7616 // C++ [class.union]p2 7617 // A union can have member functions, but not virtual functions. 7618 if (isVirtual && Parent->isUnion()) 7619 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7620 } 7621 7622 SetNestedNameSpecifier(NewFD, D); 7623 isExplicitSpecialization = false; 7624 isFunctionTemplateSpecialization = false; 7625 if (D.isInvalidType()) 7626 NewFD->setInvalidDecl(); 7627 7628 // Match up the template parameter lists with the scope specifier, then 7629 // determine whether we have a template or a template specialization. 7630 bool Invalid = false; 7631 if (TemplateParameterList *TemplateParams = 7632 MatchTemplateParametersToScopeSpecifier( 7633 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7634 D.getCXXScopeSpec(), 7635 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7636 ? D.getName().TemplateId 7637 : nullptr, 7638 TemplateParamLists, isFriend, isExplicitSpecialization, 7639 Invalid)) { 7640 if (TemplateParams->size() > 0) { 7641 // This is a function template 7642 7643 // Check that we can declare a template here. 7644 if (CheckTemplateDeclScope(S, TemplateParams)) 7645 NewFD->setInvalidDecl(); 7646 7647 // A destructor cannot be a template. 7648 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7649 Diag(NewFD->getLocation(), diag::err_destructor_template); 7650 NewFD->setInvalidDecl(); 7651 } 7652 7653 // If we're adding a template to a dependent context, we may need to 7654 // rebuilding some of the types used within the template parameter list, 7655 // now that we know what the current instantiation is. 7656 if (DC->isDependentContext()) { 7657 ContextRAII SavedContext(*this, DC); 7658 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7659 Invalid = true; 7660 } 7661 7662 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7663 NewFD->getLocation(), 7664 Name, TemplateParams, 7665 NewFD); 7666 FunctionTemplate->setLexicalDeclContext(CurContext); 7667 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7668 7669 // For source fidelity, store the other template param lists. 7670 if (TemplateParamLists.size() > 1) { 7671 NewFD->setTemplateParameterListsInfo(Context, 7672 TemplateParamLists.drop_back(1)); 7673 } 7674 } else { 7675 // This is a function template specialization. 7676 isFunctionTemplateSpecialization = true; 7677 // For source fidelity, store all the template param lists. 7678 if (TemplateParamLists.size() > 0) 7679 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7680 7681 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7682 if (isFriend) { 7683 // We want to remove the "template<>", found here. 7684 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7685 7686 // If we remove the template<> and the name is not a 7687 // template-id, we're actually silently creating a problem: 7688 // the friend declaration will refer to an untemplated decl, 7689 // and clearly the user wants a template specialization. So 7690 // we need to insert '<>' after the name. 7691 SourceLocation InsertLoc; 7692 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7693 InsertLoc = D.getName().getSourceRange().getEnd(); 7694 InsertLoc = getLocForEndOfToken(InsertLoc); 7695 } 7696 7697 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7698 << Name << RemoveRange 7699 << FixItHint::CreateRemoval(RemoveRange) 7700 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7701 } 7702 } 7703 } 7704 else { 7705 // All template param lists were matched against the scope specifier: 7706 // this is NOT (an explicit specialization of) a template. 7707 if (TemplateParamLists.size() > 0) 7708 // For source fidelity, store all the template param lists. 7709 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7710 } 7711 7712 if (Invalid) { 7713 NewFD->setInvalidDecl(); 7714 if (FunctionTemplate) 7715 FunctionTemplate->setInvalidDecl(); 7716 } 7717 7718 // C++ [dcl.fct.spec]p5: 7719 // The virtual specifier shall only be used in declarations of 7720 // nonstatic class member functions that appear within a 7721 // member-specification of a class declaration; see 10.3. 7722 // 7723 if (isVirtual && !NewFD->isInvalidDecl()) { 7724 if (!isVirtualOkay) { 7725 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7726 diag::err_virtual_non_function); 7727 } else if (!CurContext->isRecord()) { 7728 // 'virtual' was specified outside of the class. 7729 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7730 diag::err_virtual_out_of_class) 7731 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7732 } else if (NewFD->getDescribedFunctionTemplate()) { 7733 // C++ [temp.mem]p3: 7734 // A member function template shall not be virtual. 7735 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7736 diag::err_virtual_member_function_template) 7737 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7738 } else { 7739 // Okay: Add virtual to the method. 7740 NewFD->setVirtualAsWritten(true); 7741 } 7742 7743 if (getLangOpts().CPlusPlus14 && 7744 NewFD->getReturnType()->isUndeducedType()) 7745 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7746 } 7747 7748 if (getLangOpts().CPlusPlus14 && 7749 (NewFD->isDependentContext() || 7750 (isFriend && CurContext->isDependentContext())) && 7751 NewFD->getReturnType()->isUndeducedType()) { 7752 // If the function template is referenced directly (for instance, as a 7753 // member of the current instantiation), pretend it has a dependent type. 7754 // This is not really justified by the standard, but is the only sane 7755 // thing to do. 7756 // FIXME: For a friend function, we have not marked the function as being 7757 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7758 const FunctionProtoType *FPT = 7759 NewFD->getType()->castAs<FunctionProtoType>(); 7760 QualType Result = 7761 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7762 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7763 FPT->getExtProtoInfo())); 7764 } 7765 7766 // C++ [dcl.fct.spec]p3: 7767 // The inline specifier shall not appear on a block scope function 7768 // declaration. 7769 if (isInline && !NewFD->isInvalidDecl()) { 7770 if (CurContext->isFunctionOrMethod()) { 7771 // 'inline' is not allowed on block scope function declaration. 7772 Diag(D.getDeclSpec().getInlineSpecLoc(), 7773 diag::err_inline_declaration_block_scope) << Name 7774 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7775 } 7776 } 7777 7778 // C++ [dcl.fct.spec]p6: 7779 // The explicit specifier shall be used only in the declaration of a 7780 // constructor or conversion function within its class definition; 7781 // see 12.3.1 and 12.3.2. 7782 if (isExplicit && !NewFD->isInvalidDecl()) { 7783 if (!CurContext->isRecord()) { 7784 // 'explicit' was specified outside of the class. 7785 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7786 diag::err_explicit_out_of_class) 7787 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7788 } else if (!isa<CXXConstructorDecl>(NewFD) && 7789 !isa<CXXConversionDecl>(NewFD)) { 7790 // 'explicit' was specified on a function that wasn't a constructor 7791 // or conversion function. 7792 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7793 diag::err_explicit_non_ctor_or_conv_function) 7794 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7795 } 7796 } 7797 7798 if (isConstexpr) { 7799 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7800 // are implicitly inline. 7801 NewFD->setImplicitlyInline(); 7802 7803 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7804 // be either constructors or to return a literal type. Therefore, 7805 // destructors cannot be declared constexpr. 7806 if (isa<CXXDestructorDecl>(NewFD)) 7807 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7808 } 7809 7810 if (isConcept) { 7811 // This is a function concept. 7812 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 7813 FTD->setConcept(); 7814 7815 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7816 // applied only to the definition of a function template [...] 7817 if (!D.isFunctionDefinition()) { 7818 Diag(D.getDeclSpec().getConceptSpecLoc(), 7819 diag::err_function_concept_not_defined); 7820 NewFD->setInvalidDecl(); 7821 } 7822 7823 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 7824 // have no exception-specification and is treated as if it were specified 7825 // with noexcept(true) (15.4). [...] 7826 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 7827 if (FPT->hasExceptionSpec()) { 7828 SourceRange Range; 7829 if (D.isFunctionDeclarator()) 7830 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 7831 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 7832 << FixItHint::CreateRemoval(Range); 7833 NewFD->setInvalidDecl(); 7834 } else { 7835 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 7836 } 7837 7838 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 7839 // following restrictions: 7840 // - The declared return type shall have the type bool. 7841 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 7842 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 7843 NewFD->setInvalidDecl(); 7844 } 7845 7846 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 7847 // following restrictions: 7848 // - The declaration's parameter list shall be equivalent to an empty 7849 // parameter list. 7850 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 7851 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 7852 } 7853 7854 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 7855 // implicity defined to be a constexpr declaration (implicitly inline) 7856 NewFD->setImplicitlyInline(); 7857 7858 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 7859 // be declared with the thread_local, inline, friend, or constexpr 7860 // specifiers, [...] 7861 if (isInline) { 7862 Diag(D.getDeclSpec().getInlineSpecLoc(), 7863 diag::err_concept_decl_invalid_specifiers) 7864 << 1 << 1; 7865 NewFD->setInvalidDecl(true); 7866 } 7867 7868 if (isFriend) { 7869 Diag(D.getDeclSpec().getFriendSpecLoc(), 7870 diag::err_concept_decl_invalid_specifiers) 7871 << 1 << 2; 7872 NewFD->setInvalidDecl(true); 7873 } 7874 7875 if (isConstexpr) { 7876 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7877 diag::err_concept_decl_invalid_specifiers) 7878 << 1 << 3; 7879 NewFD->setInvalidDecl(true); 7880 } 7881 7882 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7883 // applied only to the definition of a function template or variable 7884 // template, declared in namespace scope. 7885 if (isFunctionTemplateSpecialization) { 7886 Diag(D.getDeclSpec().getConceptSpecLoc(), 7887 diag::err_concept_specified_specialization) << 1; 7888 NewFD->setInvalidDecl(true); 7889 return NewFD; 7890 } 7891 } 7892 7893 // If __module_private__ was specified, mark the function accordingly. 7894 if (D.getDeclSpec().isModulePrivateSpecified()) { 7895 if (isFunctionTemplateSpecialization) { 7896 SourceLocation ModulePrivateLoc 7897 = D.getDeclSpec().getModulePrivateSpecLoc(); 7898 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7899 << 0 7900 << FixItHint::CreateRemoval(ModulePrivateLoc); 7901 } else { 7902 NewFD->setModulePrivate(); 7903 if (FunctionTemplate) 7904 FunctionTemplate->setModulePrivate(); 7905 } 7906 } 7907 7908 if (isFriend) { 7909 if (FunctionTemplate) { 7910 FunctionTemplate->setObjectOfFriendDecl(); 7911 FunctionTemplate->setAccess(AS_public); 7912 } 7913 NewFD->setObjectOfFriendDecl(); 7914 NewFD->setAccess(AS_public); 7915 } 7916 7917 // If a function is defined as defaulted or deleted, mark it as such now. 7918 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7919 // definition kind to FDK_Definition. 7920 switch (D.getFunctionDefinitionKind()) { 7921 case FDK_Declaration: 7922 case FDK_Definition: 7923 break; 7924 7925 case FDK_Defaulted: 7926 NewFD->setDefaulted(); 7927 break; 7928 7929 case FDK_Deleted: 7930 NewFD->setDeletedAsWritten(); 7931 break; 7932 } 7933 7934 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7935 D.isFunctionDefinition()) { 7936 // C++ [class.mfct]p2: 7937 // A member function may be defined (8.4) in its class definition, in 7938 // which case it is an inline member function (7.1.2) 7939 NewFD->setImplicitlyInline(); 7940 } 7941 7942 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7943 !CurContext->isRecord()) { 7944 // C++ [class.static]p1: 7945 // A data or function member of a class may be declared static 7946 // in a class definition, in which case it is a static member of 7947 // the class. 7948 7949 // Complain about the 'static' specifier if it's on an out-of-line 7950 // member function definition. 7951 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7952 diag::err_static_out_of_line) 7953 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7954 } 7955 7956 // C++11 [except.spec]p15: 7957 // A deallocation function with no exception-specification is treated 7958 // as if it were specified with noexcept(true). 7959 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7960 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7961 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7962 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7963 NewFD->setType(Context.getFunctionType( 7964 FPT->getReturnType(), FPT->getParamTypes(), 7965 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7966 } 7967 7968 // Filter out previous declarations that don't match the scope. 7969 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7970 D.getCXXScopeSpec().isNotEmpty() || 7971 isExplicitSpecialization || 7972 isFunctionTemplateSpecialization); 7973 7974 // Handle GNU asm-label extension (encoded as an attribute). 7975 if (Expr *E = (Expr*) D.getAsmLabel()) { 7976 // The parser guarantees this is a string. 7977 StringLiteral *SE = cast<StringLiteral>(E); 7978 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7979 SE->getString(), 0)); 7980 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7981 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7982 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7983 if (I != ExtnameUndeclaredIdentifiers.end()) { 7984 if (isDeclExternC(NewFD)) { 7985 NewFD->addAttr(I->second); 7986 ExtnameUndeclaredIdentifiers.erase(I); 7987 } else 7988 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 7989 << /*Variable*/0 << NewFD; 7990 } 7991 } 7992 7993 // Copy the parameter declarations from the declarator D to the function 7994 // declaration NewFD, if they are available. First scavenge them into Params. 7995 SmallVector<ParmVarDecl*, 16> Params; 7996 if (D.isFunctionDeclarator()) { 7997 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7998 7999 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8000 // function that takes no arguments, not a function that takes a 8001 // single void argument. 8002 // We let through "const void" here because Sema::GetTypeForDeclarator 8003 // already checks for that case. 8004 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8005 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8006 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8007 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8008 Param->setDeclContext(NewFD); 8009 Params.push_back(Param); 8010 8011 if (Param->isInvalidDecl()) 8012 NewFD->setInvalidDecl(); 8013 } 8014 } 8015 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8016 // When we're declaring a function with a typedef, typeof, etc as in the 8017 // following example, we'll need to synthesize (unnamed) 8018 // parameters for use in the declaration. 8019 // 8020 // @code 8021 // typedef void fn(int); 8022 // fn f; 8023 // @endcode 8024 8025 // Synthesize a parameter for each argument type. 8026 for (const auto &AI : FT->param_types()) { 8027 ParmVarDecl *Param = 8028 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8029 Param->setScopeInfo(0, Params.size()); 8030 Params.push_back(Param); 8031 } 8032 } else { 8033 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8034 "Should not need args for typedef of non-prototype fn"); 8035 } 8036 8037 // Finally, we know we have the right number of parameters, install them. 8038 NewFD->setParams(Params); 8039 8040 // Find all anonymous symbols defined during the declaration of this function 8041 // and add to NewFD. This lets us track decls such 'enum Y' in: 8042 // 8043 // void f(enum Y {AA} x) {} 8044 // 8045 // which would otherwise incorrectly end up in the translation unit scope. 8046 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 8047 DeclsInPrototypeScope.clear(); 8048 8049 if (D.getDeclSpec().isNoreturnSpecified()) 8050 NewFD->addAttr( 8051 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8052 Context, 0)); 8053 8054 // Functions returning a variably modified type violate C99 6.7.5.2p2 8055 // because all functions have linkage. 8056 if (!NewFD->isInvalidDecl() && 8057 NewFD->getReturnType()->isVariablyModifiedType()) { 8058 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8059 NewFD->setInvalidDecl(); 8060 } 8061 8062 // Apply an implicit SectionAttr if #pragma code_seg is active. 8063 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8064 !NewFD->hasAttr<SectionAttr>()) { 8065 NewFD->addAttr( 8066 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8067 CodeSegStack.CurrentValue->getString(), 8068 CodeSegStack.CurrentPragmaLocation)); 8069 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8070 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8071 ASTContext::PSF_Read, 8072 NewFD)) 8073 NewFD->dropAttr<SectionAttr>(); 8074 } 8075 8076 // Handle attributes. 8077 ProcessDeclAttributes(S, NewFD, D); 8078 8079 if (getLangOpts().CUDA) 8080 maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous); 8081 8082 if (getLangOpts().OpenCL) { 8083 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8084 // type declaration will generate a compilation error. 8085 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8086 if (AddressSpace == LangAS::opencl_local || 8087 AddressSpace == LangAS::opencl_global || 8088 AddressSpace == LangAS::opencl_constant) { 8089 Diag(NewFD->getLocation(), 8090 diag::err_opencl_return_value_with_address_space); 8091 NewFD->setInvalidDecl(); 8092 } 8093 } 8094 8095 if (!getLangOpts().CPlusPlus) { 8096 // Perform semantic checking on the function declaration. 8097 bool isExplicitSpecialization=false; 8098 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8099 CheckMain(NewFD, D.getDeclSpec()); 8100 8101 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8102 CheckMSVCRTEntryPoint(NewFD); 8103 8104 if (!NewFD->isInvalidDecl()) 8105 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8106 isExplicitSpecialization)); 8107 else if (!Previous.empty()) 8108 // Recover gracefully from an invalid redeclaration. 8109 D.setRedeclaration(true); 8110 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8111 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8112 "previous declaration set still overloaded"); 8113 8114 // Diagnose no-prototype function declarations with calling conventions that 8115 // don't support variadic calls. Only do this in C and do it after merging 8116 // possibly prototyped redeclarations. 8117 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8118 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8119 CallingConv CC = FT->getExtInfo().getCC(); 8120 if (!supportsVariadicCall(CC)) { 8121 // Windows system headers sometimes accidentally use stdcall without 8122 // (void) parameters, so we relax this to a warning. 8123 int DiagID = 8124 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8125 Diag(NewFD->getLocation(), DiagID) 8126 << FunctionType::getNameForCallConv(CC); 8127 } 8128 } 8129 } else { 8130 // C++11 [replacement.functions]p3: 8131 // The program's definitions shall not be specified as inline. 8132 // 8133 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8134 // 8135 // Suppress the diagnostic if the function is __attribute__((used)), since 8136 // that forces an external definition to be emitted. 8137 if (D.getDeclSpec().isInlineSpecified() && 8138 NewFD->isReplaceableGlobalAllocationFunction() && 8139 !NewFD->hasAttr<UsedAttr>()) 8140 Diag(D.getDeclSpec().getInlineSpecLoc(), 8141 diag::ext_operator_new_delete_declared_inline) 8142 << NewFD->getDeclName(); 8143 8144 // If the declarator is a template-id, translate the parser's template 8145 // argument list into our AST format. 8146 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8147 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8148 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8149 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8150 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8151 TemplateId->NumArgs); 8152 translateTemplateArguments(TemplateArgsPtr, 8153 TemplateArgs); 8154 8155 HasExplicitTemplateArgs = true; 8156 8157 if (NewFD->isInvalidDecl()) { 8158 HasExplicitTemplateArgs = false; 8159 } else if (FunctionTemplate) { 8160 // Function template with explicit template arguments. 8161 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8162 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8163 8164 HasExplicitTemplateArgs = false; 8165 } else { 8166 assert((isFunctionTemplateSpecialization || 8167 D.getDeclSpec().isFriendSpecified()) && 8168 "should have a 'template<>' for this decl"); 8169 // "friend void foo<>(int);" is an implicit specialization decl. 8170 isFunctionTemplateSpecialization = true; 8171 } 8172 } else if (isFriend && isFunctionTemplateSpecialization) { 8173 // This combination is only possible in a recovery case; the user 8174 // wrote something like: 8175 // template <> friend void foo(int); 8176 // which we're recovering from as if the user had written: 8177 // friend void foo<>(int); 8178 // Go ahead and fake up a template id. 8179 HasExplicitTemplateArgs = true; 8180 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8181 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8182 } 8183 8184 // If it's a friend (and only if it's a friend), it's possible 8185 // that either the specialized function type or the specialized 8186 // template is dependent, and therefore matching will fail. In 8187 // this case, don't check the specialization yet. 8188 bool InstantiationDependent = false; 8189 if (isFunctionTemplateSpecialization && isFriend && 8190 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8191 TemplateSpecializationType::anyDependentTemplateArguments( 8192 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 8193 InstantiationDependent))) { 8194 assert(HasExplicitTemplateArgs && 8195 "friend function specialization without template args"); 8196 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8197 Previous)) 8198 NewFD->setInvalidDecl(); 8199 } else if (isFunctionTemplateSpecialization) { 8200 if (CurContext->isDependentContext() && CurContext->isRecord() 8201 && !isFriend) { 8202 isDependentClassScopeExplicitSpecialization = true; 8203 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8204 diag::ext_function_specialization_in_class : 8205 diag::err_function_specialization_in_class) 8206 << NewFD->getDeclName(); 8207 } else if (CheckFunctionTemplateSpecialization(NewFD, 8208 (HasExplicitTemplateArgs ? &TemplateArgs 8209 : nullptr), 8210 Previous)) 8211 NewFD->setInvalidDecl(); 8212 8213 // C++ [dcl.stc]p1: 8214 // A storage-class-specifier shall not be specified in an explicit 8215 // specialization (14.7.3) 8216 FunctionTemplateSpecializationInfo *Info = 8217 NewFD->getTemplateSpecializationInfo(); 8218 if (Info && SC != SC_None) { 8219 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8220 Diag(NewFD->getLocation(), 8221 diag::err_explicit_specialization_inconsistent_storage_class) 8222 << SC 8223 << FixItHint::CreateRemoval( 8224 D.getDeclSpec().getStorageClassSpecLoc()); 8225 8226 else 8227 Diag(NewFD->getLocation(), 8228 diag::ext_explicit_specialization_storage_class) 8229 << FixItHint::CreateRemoval( 8230 D.getDeclSpec().getStorageClassSpecLoc()); 8231 } 8232 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 8233 if (CheckMemberSpecialization(NewFD, Previous)) 8234 NewFD->setInvalidDecl(); 8235 } 8236 8237 // Perform semantic checking on the function declaration. 8238 if (!isDependentClassScopeExplicitSpecialization) { 8239 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8240 CheckMain(NewFD, D.getDeclSpec()); 8241 8242 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8243 CheckMSVCRTEntryPoint(NewFD); 8244 8245 if (!NewFD->isInvalidDecl()) 8246 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8247 isExplicitSpecialization)); 8248 else if (!Previous.empty()) 8249 // Recover gracefully from an invalid redeclaration. 8250 D.setRedeclaration(true); 8251 } 8252 8253 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8254 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8255 "previous declaration set still overloaded"); 8256 8257 NamedDecl *PrincipalDecl = (FunctionTemplate 8258 ? cast<NamedDecl>(FunctionTemplate) 8259 : NewFD); 8260 8261 if (isFriend && D.isRedeclaration()) { 8262 AccessSpecifier Access = AS_public; 8263 if (!NewFD->isInvalidDecl()) 8264 Access = NewFD->getPreviousDecl()->getAccess(); 8265 8266 NewFD->setAccess(Access); 8267 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8268 } 8269 8270 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8271 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8272 PrincipalDecl->setNonMemberOperator(); 8273 8274 // If we have a function template, check the template parameter 8275 // list. This will check and merge default template arguments. 8276 if (FunctionTemplate) { 8277 FunctionTemplateDecl *PrevTemplate = 8278 FunctionTemplate->getPreviousDecl(); 8279 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8280 PrevTemplate ? PrevTemplate->getTemplateParameters() 8281 : nullptr, 8282 D.getDeclSpec().isFriendSpecified() 8283 ? (D.isFunctionDefinition() 8284 ? TPC_FriendFunctionTemplateDefinition 8285 : TPC_FriendFunctionTemplate) 8286 : (D.getCXXScopeSpec().isSet() && 8287 DC && DC->isRecord() && 8288 DC->isDependentContext()) 8289 ? TPC_ClassTemplateMember 8290 : TPC_FunctionTemplate); 8291 } 8292 8293 if (NewFD->isInvalidDecl()) { 8294 // Ignore all the rest of this. 8295 } else if (!D.isRedeclaration()) { 8296 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8297 AddToScope }; 8298 // Fake up an access specifier if it's supposed to be a class member. 8299 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8300 NewFD->setAccess(AS_public); 8301 8302 // Qualified decls generally require a previous declaration. 8303 if (D.getCXXScopeSpec().isSet()) { 8304 // ...with the major exception of templated-scope or 8305 // dependent-scope friend declarations. 8306 8307 // TODO: we currently also suppress this check in dependent 8308 // contexts because (1) the parameter depth will be off when 8309 // matching friend templates and (2) we might actually be 8310 // selecting a friend based on a dependent factor. But there 8311 // are situations where these conditions don't apply and we 8312 // can actually do this check immediately. 8313 if (isFriend && 8314 (TemplateParamLists.size() || 8315 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8316 CurContext->isDependentContext())) { 8317 // ignore these 8318 } else { 8319 // The user tried to provide an out-of-line definition for a 8320 // function that is a member of a class or namespace, but there 8321 // was no such member function declared (C++ [class.mfct]p2, 8322 // C++ [namespace.memdef]p2). For example: 8323 // 8324 // class X { 8325 // void f() const; 8326 // }; 8327 // 8328 // void X::f() { } // ill-formed 8329 // 8330 // Complain about this problem, and attempt to suggest close 8331 // matches (e.g., those that differ only in cv-qualifiers and 8332 // whether the parameter types are references). 8333 8334 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8335 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8336 AddToScope = ExtraArgs.AddToScope; 8337 return Result; 8338 } 8339 } 8340 8341 // Unqualified local friend declarations are required to resolve 8342 // to something. 8343 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8344 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8345 *this, Previous, NewFD, ExtraArgs, true, S)) { 8346 AddToScope = ExtraArgs.AddToScope; 8347 return Result; 8348 } 8349 } 8350 } else if (!D.isFunctionDefinition() && 8351 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8352 !isFriend && !isFunctionTemplateSpecialization && 8353 !isExplicitSpecialization) { 8354 // An out-of-line member function declaration must also be a 8355 // definition (C++ [class.mfct]p2). 8356 // Note that this is not the case for explicit specializations of 8357 // function templates or member functions of class templates, per 8358 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8359 // extension for compatibility with old SWIG code which likes to 8360 // generate them. 8361 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8362 << D.getCXXScopeSpec().getRange(); 8363 } 8364 } 8365 8366 ProcessPragmaWeak(S, NewFD); 8367 checkAttributesAfterMerging(*this, *NewFD); 8368 8369 AddKnownFunctionAttributes(NewFD); 8370 8371 if (NewFD->hasAttr<OverloadableAttr>() && 8372 !NewFD->getType()->getAs<FunctionProtoType>()) { 8373 Diag(NewFD->getLocation(), 8374 diag::err_attribute_overloadable_no_prototype) 8375 << NewFD; 8376 8377 // Turn this into a variadic function with no parameters. 8378 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8379 FunctionProtoType::ExtProtoInfo EPI( 8380 Context.getDefaultCallingConvention(true, false)); 8381 EPI.Variadic = true; 8382 EPI.ExtInfo = FT->getExtInfo(); 8383 8384 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8385 NewFD->setType(R); 8386 } 8387 8388 // If there's a #pragma GCC visibility in scope, and this isn't a class 8389 // member, set the visibility of this function. 8390 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8391 AddPushedVisibilityAttribute(NewFD); 8392 8393 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8394 // marking the function. 8395 AddCFAuditedAttribute(NewFD); 8396 8397 // If this is a function definition, check if we have to apply optnone due to 8398 // a pragma. 8399 if(D.isFunctionDefinition()) 8400 AddRangeBasedOptnone(NewFD); 8401 8402 // If this is the first declaration of an extern C variable, update 8403 // the map of such variables. 8404 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8405 isIncompleteDeclExternC(*this, NewFD)) 8406 RegisterLocallyScopedExternCDecl(NewFD, S); 8407 8408 // Set this FunctionDecl's range up to the right paren. 8409 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8410 8411 if (D.isRedeclaration() && !Previous.empty()) { 8412 checkDLLAttributeRedeclaration( 8413 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8414 isExplicitSpecialization || isFunctionTemplateSpecialization); 8415 } 8416 8417 if (getLangOpts().CUDA) { 8418 IdentifierInfo *II = NewFD->getIdentifier(); 8419 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8420 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8421 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8422 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8423 8424 Context.setcudaConfigureCallDecl(NewFD); 8425 } 8426 8427 // Variadic functions, other than a *declaration* of printf, are not allowed 8428 // in device-side CUDA code, unless someone passed 8429 // -fcuda-allow-variadic-functions. 8430 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8431 (NewFD->hasAttr<CUDADeviceAttr>() || 8432 NewFD->hasAttr<CUDAGlobalAttr>()) && 8433 !(II && II->isStr("printf") && NewFD->isExternC() && 8434 !D.isFunctionDefinition())) { 8435 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8436 } 8437 } 8438 8439 if (getLangOpts().CPlusPlus) { 8440 if (FunctionTemplate) { 8441 if (NewFD->isInvalidDecl()) 8442 FunctionTemplate->setInvalidDecl(); 8443 return FunctionTemplate; 8444 } 8445 } 8446 8447 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8448 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8449 if ((getLangOpts().OpenCLVersion >= 120) 8450 && (SC == SC_Static)) { 8451 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8452 D.setInvalidType(); 8453 } 8454 8455 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8456 if (!NewFD->getReturnType()->isVoidType()) { 8457 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8458 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8459 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8460 : FixItHint()); 8461 D.setInvalidType(); 8462 } 8463 8464 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8465 for (auto Param : NewFD->params()) 8466 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8467 } 8468 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 8469 PE = NewFD->param_end(); PI != PE; ++PI) { 8470 ParmVarDecl *Param = *PI; 8471 QualType PT = Param->getType(); 8472 8473 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8474 // types. 8475 if (getLangOpts().OpenCLVersion >= 200) { 8476 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8477 QualType ElemTy = PipeTy->getElementType(); 8478 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8479 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8480 D.setInvalidType(); 8481 } 8482 } 8483 } 8484 } 8485 8486 MarkUnusedFileScopedDecl(NewFD); 8487 8488 // Here we have an function template explicit specialization at class scope. 8489 // The actually specialization will be postponed to template instatiation 8490 // time via the ClassScopeFunctionSpecializationDecl node. 8491 if (isDependentClassScopeExplicitSpecialization) { 8492 ClassScopeFunctionSpecializationDecl *NewSpec = 8493 ClassScopeFunctionSpecializationDecl::Create( 8494 Context, CurContext, SourceLocation(), 8495 cast<CXXMethodDecl>(NewFD), 8496 HasExplicitTemplateArgs, TemplateArgs); 8497 CurContext->addDecl(NewSpec); 8498 AddToScope = false; 8499 } 8500 8501 return NewFD; 8502 } 8503 8504 /// \brief Perform semantic checking of a new function declaration. 8505 /// 8506 /// Performs semantic analysis of the new function declaration 8507 /// NewFD. This routine performs all semantic checking that does not 8508 /// require the actual declarator involved in the declaration, and is 8509 /// used both for the declaration of functions as they are parsed 8510 /// (called via ActOnDeclarator) and for the declaration of functions 8511 /// that have been instantiated via C++ template instantiation (called 8512 /// via InstantiateDecl). 8513 /// 8514 /// \param IsExplicitSpecialization whether this new function declaration is 8515 /// an explicit specialization of the previous declaration. 8516 /// 8517 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8518 /// 8519 /// \returns true if the function declaration is a redeclaration. 8520 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8521 LookupResult &Previous, 8522 bool IsExplicitSpecialization) { 8523 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8524 "Variably modified return types are not handled here"); 8525 8526 // Determine whether the type of this function should be merged with 8527 // a previous visible declaration. This never happens for functions in C++, 8528 // and always happens in C if the previous declaration was visible. 8529 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8530 !Previous.isShadowed(); 8531 8532 bool Redeclaration = false; 8533 NamedDecl *OldDecl = nullptr; 8534 8535 // Merge or overload the declaration with an existing declaration of 8536 // the same name, if appropriate. 8537 if (!Previous.empty()) { 8538 // Determine whether NewFD is an overload of PrevDecl or 8539 // a declaration that requires merging. If it's an overload, 8540 // there's no more work to do here; we'll just add the new 8541 // function to the scope. 8542 if (!AllowOverloadingOfFunction(Previous, Context)) { 8543 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8544 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8545 Redeclaration = true; 8546 OldDecl = Candidate; 8547 } 8548 } else { 8549 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8550 /*NewIsUsingDecl*/ false)) { 8551 case Ovl_Match: 8552 Redeclaration = true; 8553 break; 8554 8555 case Ovl_NonFunction: 8556 Redeclaration = true; 8557 break; 8558 8559 case Ovl_Overload: 8560 Redeclaration = false; 8561 break; 8562 } 8563 8564 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8565 // If a function name is overloadable in C, then every function 8566 // with that name must be marked "overloadable". 8567 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8568 << Redeclaration << NewFD; 8569 NamedDecl *OverloadedDecl = nullptr; 8570 if (Redeclaration) 8571 OverloadedDecl = OldDecl; 8572 else if (!Previous.empty()) 8573 OverloadedDecl = Previous.getRepresentativeDecl(); 8574 if (OverloadedDecl) 8575 Diag(OverloadedDecl->getLocation(), 8576 diag::note_attribute_overloadable_prev_overload); 8577 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8578 } 8579 } 8580 } 8581 8582 // Check for a previous extern "C" declaration with this name. 8583 if (!Redeclaration && 8584 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8585 if (!Previous.empty()) { 8586 // This is an extern "C" declaration with the same name as a previous 8587 // declaration, and thus redeclares that entity... 8588 Redeclaration = true; 8589 OldDecl = Previous.getFoundDecl(); 8590 MergeTypeWithPrevious = false; 8591 8592 // ... except in the presence of __attribute__((overloadable)). 8593 if (OldDecl->hasAttr<OverloadableAttr>()) { 8594 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8595 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8596 << Redeclaration << NewFD; 8597 Diag(Previous.getFoundDecl()->getLocation(), 8598 diag::note_attribute_overloadable_prev_overload); 8599 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8600 } 8601 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8602 Redeclaration = false; 8603 OldDecl = nullptr; 8604 } 8605 } 8606 } 8607 } 8608 8609 // C++11 [dcl.constexpr]p8: 8610 // A constexpr specifier for a non-static member function that is not 8611 // a constructor declares that member function to be const. 8612 // 8613 // This needs to be delayed until we know whether this is an out-of-line 8614 // definition of a static member function. 8615 // 8616 // This rule is not present in C++1y, so we produce a backwards 8617 // compatibility warning whenever it happens in C++11. 8618 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8619 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8620 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8621 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8622 CXXMethodDecl *OldMD = nullptr; 8623 if (OldDecl) 8624 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8625 if (!OldMD || !OldMD->isStatic()) { 8626 const FunctionProtoType *FPT = 8627 MD->getType()->castAs<FunctionProtoType>(); 8628 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8629 EPI.TypeQuals |= Qualifiers::Const; 8630 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8631 FPT->getParamTypes(), EPI)); 8632 8633 // Warn that we did this, if we're not performing template instantiation. 8634 // In that case, we'll have warned already when the template was defined. 8635 if (ActiveTemplateInstantiations.empty()) { 8636 SourceLocation AddConstLoc; 8637 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8638 .IgnoreParens().getAs<FunctionTypeLoc>()) 8639 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8640 8641 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8642 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8643 } 8644 } 8645 } 8646 8647 if (Redeclaration) { 8648 // NewFD and OldDecl represent declarations that need to be 8649 // merged. 8650 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8651 NewFD->setInvalidDecl(); 8652 return Redeclaration; 8653 } 8654 8655 Previous.clear(); 8656 Previous.addDecl(OldDecl); 8657 8658 if (FunctionTemplateDecl *OldTemplateDecl 8659 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8660 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8661 FunctionTemplateDecl *NewTemplateDecl 8662 = NewFD->getDescribedFunctionTemplate(); 8663 assert(NewTemplateDecl && "Template/non-template mismatch"); 8664 if (CXXMethodDecl *Method 8665 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8666 Method->setAccess(OldTemplateDecl->getAccess()); 8667 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8668 } 8669 8670 // If this is an explicit specialization of a member that is a function 8671 // template, mark it as a member specialization. 8672 if (IsExplicitSpecialization && 8673 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8674 NewTemplateDecl->setMemberSpecialization(); 8675 assert(OldTemplateDecl->isMemberSpecialization()); 8676 // Explicit specializations of a member template do not inherit deleted 8677 // status from the parent member template that they are specializing. 8678 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 8679 FunctionDecl *const OldTemplatedDecl = 8680 OldTemplateDecl->getTemplatedDecl(); 8681 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 8682 OldTemplatedDecl->setDeletedAsWritten(false); 8683 } 8684 } 8685 8686 } else { 8687 // This needs to happen first so that 'inline' propagates. 8688 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8689 8690 if (isa<CXXMethodDecl>(NewFD)) 8691 NewFD->setAccess(OldDecl->getAccess()); 8692 } 8693 } 8694 8695 // Semantic checking for this function declaration (in isolation). 8696 8697 if (getLangOpts().CPlusPlus) { 8698 // C++-specific checks. 8699 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8700 CheckConstructor(Constructor); 8701 } else if (CXXDestructorDecl *Destructor = 8702 dyn_cast<CXXDestructorDecl>(NewFD)) { 8703 CXXRecordDecl *Record = Destructor->getParent(); 8704 QualType ClassType = Context.getTypeDeclType(Record); 8705 8706 // FIXME: Shouldn't we be able to perform this check even when the class 8707 // type is dependent? Both gcc and edg can handle that. 8708 if (!ClassType->isDependentType()) { 8709 DeclarationName Name 8710 = Context.DeclarationNames.getCXXDestructorName( 8711 Context.getCanonicalType(ClassType)); 8712 if (NewFD->getDeclName() != Name) { 8713 Diag(NewFD->getLocation(), diag::err_destructor_name); 8714 NewFD->setInvalidDecl(); 8715 return Redeclaration; 8716 } 8717 } 8718 } else if (CXXConversionDecl *Conversion 8719 = dyn_cast<CXXConversionDecl>(NewFD)) { 8720 ActOnConversionDeclarator(Conversion); 8721 } 8722 8723 // Find any virtual functions that this function overrides. 8724 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8725 if (!Method->isFunctionTemplateSpecialization() && 8726 !Method->getDescribedFunctionTemplate() && 8727 Method->isCanonicalDecl()) { 8728 if (AddOverriddenMethods(Method->getParent(), Method)) { 8729 // If the function was marked as "static", we have a problem. 8730 if (NewFD->getStorageClass() == SC_Static) { 8731 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8732 } 8733 } 8734 } 8735 8736 if (Method->isStatic()) 8737 checkThisInStaticMemberFunctionType(Method); 8738 } 8739 8740 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8741 if (NewFD->isOverloadedOperator() && 8742 CheckOverloadedOperatorDeclaration(NewFD)) { 8743 NewFD->setInvalidDecl(); 8744 return Redeclaration; 8745 } 8746 8747 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8748 if (NewFD->getLiteralIdentifier() && 8749 CheckLiteralOperatorDeclaration(NewFD)) { 8750 NewFD->setInvalidDecl(); 8751 return Redeclaration; 8752 } 8753 8754 // In C++, check default arguments now that we have merged decls. Unless 8755 // the lexical context is the class, because in this case this is done 8756 // during delayed parsing anyway. 8757 if (!CurContext->isRecord()) 8758 CheckCXXDefaultArguments(NewFD); 8759 8760 // If this function declares a builtin function, check the type of this 8761 // declaration against the expected type for the builtin. 8762 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8763 ASTContext::GetBuiltinTypeError Error; 8764 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8765 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8766 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8767 // The type of this function differs from the type of the builtin, 8768 // so forget about the builtin entirely. 8769 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 8770 } 8771 } 8772 8773 // If this function is declared as being extern "C", then check to see if 8774 // the function returns a UDT (class, struct, or union type) that is not C 8775 // compatible, and if it does, warn the user. 8776 // But, issue any diagnostic on the first declaration only. 8777 if (Previous.empty() && NewFD->isExternC()) { 8778 QualType R = NewFD->getReturnType(); 8779 if (R->isIncompleteType() && !R->isVoidType()) 8780 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8781 << NewFD << R; 8782 else if (!R.isPODType(Context) && !R->isVoidType() && 8783 !R->isObjCObjectPointerType()) 8784 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8785 } 8786 } 8787 return Redeclaration; 8788 } 8789 8790 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8791 // C++11 [basic.start.main]p3: 8792 // A program that [...] declares main to be inline, static or 8793 // constexpr is ill-formed. 8794 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8795 // appear in a declaration of main. 8796 // static main is not an error under C99, but we should warn about it. 8797 // We accept _Noreturn main as an extension. 8798 if (FD->getStorageClass() == SC_Static) 8799 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8800 ? diag::err_static_main : diag::warn_static_main) 8801 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8802 if (FD->isInlineSpecified()) 8803 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8804 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8805 if (DS.isNoreturnSpecified()) { 8806 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8807 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8808 Diag(NoreturnLoc, diag::ext_noreturn_main); 8809 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8810 << FixItHint::CreateRemoval(NoreturnRange); 8811 } 8812 if (FD->isConstexpr()) { 8813 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8814 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8815 FD->setConstexpr(false); 8816 } 8817 8818 if (getLangOpts().OpenCL) { 8819 Diag(FD->getLocation(), diag::err_opencl_no_main) 8820 << FD->hasAttr<OpenCLKernelAttr>(); 8821 FD->setInvalidDecl(); 8822 return; 8823 } 8824 8825 QualType T = FD->getType(); 8826 assert(T->isFunctionType() && "function decl is not of function type"); 8827 const FunctionType* FT = T->castAs<FunctionType>(); 8828 8829 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8830 // In C with GNU extensions we allow main() to have non-integer return 8831 // type, but we should warn about the extension, and we disable the 8832 // implicit-return-zero rule. 8833 8834 // GCC in C mode accepts qualified 'int'. 8835 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8836 FD->setHasImplicitReturnZero(true); 8837 else { 8838 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8839 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8840 if (RTRange.isValid()) 8841 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8842 << FixItHint::CreateReplacement(RTRange, "int"); 8843 } 8844 } else { 8845 // In C and C++, main magically returns 0 if you fall off the end; 8846 // set the flag which tells us that. 8847 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8848 8849 // All the standards say that main() should return 'int'. 8850 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8851 FD->setHasImplicitReturnZero(true); 8852 else { 8853 // Otherwise, this is just a flat-out error. 8854 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8855 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8856 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8857 : FixItHint()); 8858 FD->setInvalidDecl(true); 8859 } 8860 } 8861 8862 // Treat protoless main() as nullary. 8863 if (isa<FunctionNoProtoType>(FT)) return; 8864 8865 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8866 unsigned nparams = FTP->getNumParams(); 8867 assert(FD->getNumParams() == nparams); 8868 8869 bool HasExtraParameters = (nparams > 3); 8870 8871 if (FTP->isVariadic()) { 8872 Diag(FD->getLocation(), diag::ext_variadic_main); 8873 // FIXME: if we had information about the location of the ellipsis, we 8874 // could add a FixIt hint to remove it as a parameter. 8875 } 8876 8877 // Darwin passes an undocumented fourth argument of type char**. If 8878 // other platforms start sprouting these, the logic below will start 8879 // getting shifty. 8880 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8881 HasExtraParameters = false; 8882 8883 if (HasExtraParameters) { 8884 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8885 FD->setInvalidDecl(true); 8886 nparams = 3; 8887 } 8888 8889 // FIXME: a lot of the following diagnostics would be improved 8890 // if we had some location information about types. 8891 8892 QualType CharPP = 8893 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8894 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8895 8896 for (unsigned i = 0; i < nparams; ++i) { 8897 QualType AT = FTP->getParamType(i); 8898 8899 bool mismatch = true; 8900 8901 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8902 mismatch = false; 8903 else if (Expected[i] == CharPP) { 8904 // As an extension, the following forms are okay: 8905 // char const ** 8906 // char const * const * 8907 // char * const * 8908 8909 QualifierCollector qs; 8910 const PointerType* PT; 8911 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8912 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8913 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8914 Context.CharTy)) { 8915 qs.removeConst(); 8916 mismatch = !qs.empty(); 8917 } 8918 } 8919 8920 if (mismatch) { 8921 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8922 // TODO: suggest replacing given type with expected type 8923 FD->setInvalidDecl(true); 8924 } 8925 } 8926 8927 if (nparams == 1 && !FD->isInvalidDecl()) { 8928 Diag(FD->getLocation(), diag::warn_main_one_arg); 8929 } 8930 8931 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8932 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8933 FD->setInvalidDecl(); 8934 } 8935 } 8936 8937 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8938 QualType T = FD->getType(); 8939 assert(T->isFunctionType() && "function decl is not of function type"); 8940 const FunctionType *FT = T->castAs<FunctionType>(); 8941 8942 // Set an implicit return of 'zero' if the function can return some integral, 8943 // enumeration, pointer or nullptr type. 8944 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8945 FT->getReturnType()->isAnyPointerType() || 8946 FT->getReturnType()->isNullPtrType()) 8947 // DllMain is exempt because a return value of zero means it failed. 8948 if (FD->getName() != "DllMain") 8949 FD->setHasImplicitReturnZero(true); 8950 8951 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8952 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8953 FD->setInvalidDecl(); 8954 } 8955 } 8956 8957 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8958 // FIXME: Need strict checking. In C89, we need to check for 8959 // any assignment, increment, decrement, function-calls, or 8960 // commas outside of a sizeof. In C99, it's the same list, 8961 // except that the aforementioned are allowed in unevaluated 8962 // expressions. Everything else falls under the 8963 // "may accept other forms of constant expressions" exception. 8964 // (We never end up here for C++, so the constant expression 8965 // rules there don't matter.) 8966 const Expr *Culprit; 8967 if (Init->isConstantInitializer(Context, false, &Culprit)) 8968 return false; 8969 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8970 << Culprit->getSourceRange(); 8971 return true; 8972 } 8973 8974 namespace { 8975 // Visits an initialization expression to see if OrigDecl is evaluated in 8976 // its own initialization and throws a warning if it does. 8977 class SelfReferenceChecker 8978 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8979 Sema &S; 8980 Decl *OrigDecl; 8981 bool isRecordType; 8982 bool isPODType; 8983 bool isReferenceType; 8984 8985 bool isInitList; 8986 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8987 8988 public: 8989 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8990 8991 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8992 S(S), OrigDecl(OrigDecl) { 8993 isPODType = false; 8994 isRecordType = false; 8995 isReferenceType = false; 8996 isInitList = false; 8997 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8998 isPODType = VD->getType().isPODType(S.Context); 8999 isRecordType = VD->getType()->isRecordType(); 9000 isReferenceType = VD->getType()->isReferenceType(); 9001 } 9002 } 9003 9004 // For most expressions, just call the visitor. For initializer lists, 9005 // track the index of the field being initialized since fields are 9006 // initialized in order allowing use of previously initialized fields. 9007 void CheckExpr(Expr *E) { 9008 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9009 if (!InitList) { 9010 Visit(E); 9011 return; 9012 } 9013 9014 // Track and increment the index here. 9015 isInitList = true; 9016 InitFieldIndex.push_back(0); 9017 for (auto Child : InitList->children()) { 9018 CheckExpr(cast<Expr>(Child)); 9019 ++InitFieldIndex.back(); 9020 } 9021 InitFieldIndex.pop_back(); 9022 } 9023 9024 // Returns true if MemberExpr is checked and no futher checking is needed. 9025 // Returns false if additional checking is required. 9026 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9027 llvm::SmallVector<FieldDecl*, 4> Fields; 9028 Expr *Base = E; 9029 bool ReferenceField = false; 9030 9031 // Get the field memebers used. 9032 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9033 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9034 if (!FD) 9035 return false; 9036 Fields.push_back(FD); 9037 if (FD->getType()->isReferenceType()) 9038 ReferenceField = true; 9039 Base = ME->getBase()->IgnoreParenImpCasts(); 9040 } 9041 9042 // Keep checking only if the base Decl is the same. 9043 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9044 if (!DRE || DRE->getDecl() != OrigDecl) 9045 return false; 9046 9047 // A reference field can be bound to an unininitialized field. 9048 if (CheckReference && !ReferenceField) 9049 return true; 9050 9051 // Convert FieldDecls to their index number. 9052 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9053 for (const FieldDecl *I : llvm::reverse(Fields)) 9054 UsedFieldIndex.push_back(I->getFieldIndex()); 9055 9056 // See if a warning is needed by checking the first difference in index 9057 // numbers. If field being used has index less than the field being 9058 // initialized, then the use is safe. 9059 for (auto UsedIter = UsedFieldIndex.begin(), 9060 UsedEnd = UsedFieldIndex.end(), 9061 OrigIter = InitFieldIndex.begin(), 9062 OrigEnd = InitFieldIndex.end(); 9063 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9064 if (*UsedIter < *OrigIter) 9065 return true; 9066 if (*UsedIter > *OrigIter) 9067 break; 9068 } 9069 9070 // TODO: Add a different warning which will print the field names. 9071 HandleDeclRefExpr(DRE); 9072 return true; 9073 } 9074 9075 // For most expressions, the cast is directly above the DeclRefExpr. 9076 // For conditional operators, the cast can be outside the conditional 9077 // operator if both expressions are DeclRefExpr's. 9078 void HandleValue(Expr *E) { 9079 E = E->IgnoreParens(); 9080 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9081 HandleDeclRefExpr(DRE); 9082 return; 9083 } 9084 9085 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9086 Visit(CO->getCond()); 9087 HandleValue(CO->getTrueExpr()); 9088 HandleValue(CO->getFalseExpr()); 9089 return; 9090 } 9091 9092 if (BinaryConditionalOperator *BCO = 9093 dyn_cast<BinaryConditionalOperator>(E)) { 9094 Visit(BCO->getCond()); 9095 HandleValue(BCO->getFalseExpr()); 9096 return; 9097 } 9098 9099 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9100 HandleValue(OVE->getSourceExpr()); 9101 return; 9102 } 9103 9104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9105 if (BO->getOpcode() == BO_Comma) { 9106 Visit(BO->getLHS()); 9107 HandleValue(BO->getRHS()); 9108 return; 9109 } 9110 } 9111 9112 if (isa<MemberExpr>(E)) { 9113 if (isInitList) { 9114 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9115 false /*CheckReference*/)) 9116 return; 9117 } 9118 9119 Expr *Base = E->IgnoreParenImpCasts(); 9120 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9121 // Check for static member variables and don't warn on them. 9122 if (!isa<FieldDecl>(ME->getMemberDecl())) 9123 return; 9124 Base = ME->getBase()->IgnoreParenImpCasts(); 9125 } 9126 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9127 HandleDeclRefExpr(DRE); 9128 return; 9129 } 9130 9131 Visit(E); 9132 } 9133 9134 // Reference types not handled in HandleValue are handled here since all 9135 // uses of references are bad, not just r-value uses. 9136 void VisitDeclRefExpr(DeclRefExpr *E) { 9137 if (isReferenceType) 9138 HandleDeclRefExpr(E); 9139 } 9140 9141 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9142 if (E->getCastKind() == CK_LValueToRValue) { 9143 HandleValue(E->getSubExpr()); 9144 return; 9145 } 9146 9147 Inherited::VisitImplicitCastExpr(E); 9148 } 9149 9150 void VisitMemberExpr(MemberExpr *E) { 9151 if (isInitList) { 9152 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9153 return; 9154 } 9155 9156 // Don't warn on arrays since they can be treated as pointers. 9157 if (E->getType()->canDecayToPointerType()) return; 9158 9159 // Warn when a non-static method call is followed by non-static member 9160 // field accesses, which is followed by a DeclRefExpr. 9161 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9162 bool Warn = (MD && !MD->isStatic()); 9163 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9164 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9165 if (!isa<FieldDecl>(ME->getMemberDecl())) 9166 Warn = false; 9167 Base = ME->getBase()->IgnoreParenImpCasts(); 9168 } 9169 9170 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9171 if (Warn) 9172 HandleDeclRefExpr(DRE); 9173 return; 9174 } 9175 9176 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9177 // Visit that expression. 9178 Visit(Base); 9179 } 9180 9181 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9182 Expr *Callee = E->getCallee(); 9183 9184 if (isa<UnresolvedLookupExpr>(Callee)) 9185 return Inherited::VisitCXXOperatorCallExpr(E); 9186 9187 Visit(Callee); 9188 for (auto Arg: E->arguments()) 9189 HandleValue(Arg->IgnoreParenImpCasts()); 9190 } 9191 9192 void VisitUnaryOperator(UnaryOperator *E) { 9193 // For POD record types, addresses of its own members are well-defined. 9194 if (E->getOpcode() == UO_AddrOf && isRecordType && 9195 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9196 if (!isPODType) 9197 HandleValue(E->getSubExpr()); 9198 return; 9199 } 9200 9201 if (E->isIncrementDecrementOp()) { 9202 HandleValue(E->getSubExpr()); 9203 return; 9204 } 9205 9206 Inherited::VisitUnaryOperator(E); 9207 } 9208 9209 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9210 9211 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9212 if (E->getConstructor()->isCopyConstructor()) { 9213 Expr *ArgExpr = E->getArg(0); 9214 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9215 if (ILE->getNumInits() == 1) 9216 ArgExpr = ILE->getInit(0); 9217 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9218 if (ICE->getCastKind() == CK_NoOp) 9219 ArgExpr = ICE->getSubExpr(); 9220 HandleValue(ArgExpr); 9221 return; 9222 } 9223 Inherited::VisitCXXConstructExpr(E); 9224 } 9225 9226 void VisitCallExpr(CallExpr *E) { 9227 // Treat std::move as a use. 9228 if (E->getNumArgs() == 1) { 9229 if (FunctionDecl *FD = E->getDirectCallee()) { 9230 if (FD->isInStdNamespace() && FD->getIdentifier() && 9231 FD->getIdentifier()->isStr("move")) { 9232 HandleValue(E->getArg(0)); 9233 return; 9234 } 9235 } 9236 } 9237 9238 Inherited::VisitCallExpr(E); 9239 } 9240 9241 void VisitBinaryOperator(BinaryOperator *E) { 9242 if (E->isCompoundAssignmentOp()) { 9243 HandleValue(E->getLHS()); 9244 Visit(E->getRHS()); 9245 return; 9246 } 9247 9248 Inherited::VisitBinaryOperator(E); 9249 } 9250 9251 // A custom visitor for BinaryConditionalOperator is needed because the 9252 // regular visitor would check the condition and true expression separately 9253 // but both point to the same place giving duplicate diagnostics. 9254 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9255 Visit(E->getCond()); 9256 Visit(E->getFalseExpr()); 9257 } 9258 9259 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9260 Decl* ReferenceDecl = DRE->getDecl(); 9261 if (OrigDecl != ReferenceDecl) return; 9262 unsigned diag; 9263 if (isReferenceType) { 9264 diag = diag::warn_uninit_self_reference_in_reference_init; 9265 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9266 diag = diag::warn_static_self_reference_in_init; 9267 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9268 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9269 DRE->getDecl()->getType()->isRecordType()) { 9270 diag = diag::warn_uninit_self_reference_in_init; 9271 } else { 9272 // Local variables will be handled by the CFG analysis. 9273 return; 9274 } 9275 9276 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9277 S.PDiag(diag) 9278 << DRE->getNameInfo().getName() 9279 << OrigDecl->getLocation() 9280 << DRE->getSourceRange()); 9281 } 9282 }; 9283 9284 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9285 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9286 bool DirectInit) { 9287 // Parameters arguments are occassionially constructed with itself, 9288 // for instance, in recursive functions. Skip them. 9289 if (isa<ParmVarDecl>(OrigDecl)) 9290 return; 9291 9292 E = E->IgnoreParens(); 9293 9294 // Skip checking T a = a where T is not a record or reference type. 9295 // Doing so is a way to silence uninitialized warnings. 9296 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9297 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9298 if (ICE->getCastKind() == CK_LValueToRValue) 9299 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9300 if (DRE->getDecl() == OrigDecl) 9301 return; 9302 9303 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9304 } 9305 } // end anonymous namespace 9306 9307 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9308 DeclarationName Name, QualType Type, 9309 TypeSourceInfo *TSI, 9310 SourceRange Range, bool DirectInit, 9311 Expr *Init) { 9312 bool IsInitCapture = !VDecl; 9313 assert((!VDecl || !VDecl->isInitCapture()) && 9314 "init captures are expected to be deduced prior to initialization"); 9315 9316 ArrayRef<Expr *> DeduceInits = Init; 9317 if (DirectInit) { 9318 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9319 DeduceInits = PL->exprs(); 9320 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9321 DeduceInits = IL->inits(); 9322 } 9323 9324 // Deduction only works if we have exactly one source expression. 9325 if (DeduceInits.empty()) { 9326 // It isn't possible to write this directly, but it is possible to 9327 // end up in this situation with "auto x(some_pack...);" 9328 Diag(Init->getLocStart(), IsInitCapture 9329 ? diag::err_init_capture_no_expression 9330 : diag::err_auto_var_init_no_expression) 9331 << Name << Type << Range; 9332 return QualType(); 9333 } 9334 9335 if (DeduceInits.size() > 1) { 9336 Diag(DeduceInits[1]->getLocStart(), 9337 IsInitCapture ? diag::err_init_capture_multiple_expressions 9338 : diag::err_auto_var_init_multiple_expressions) 9339 << Name << Type << Range; 9340 return QualType(); 9341 } 9342 9343 Expr *DeduceInit = DeduceInits[0]; 9344 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9345 Diag(Init->getLocStart(), IsInitCapture 9346 ? diag::err_init_capture_paren_braces 9347 : diag::err_auto_var_init_paren_braces) 9348 << isa<InitListExpr>(Init) << Name << Type << Range; 9349 return QualType(); 9350 } 9351 9352 // Expressions default to 'id' when we're in a debugger. 9353 bool DefaultedAnyToId = false; 9354 if (getLangOpts().DebuggerCastResultToId && 9355 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9356 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9357 if (Result.isInvalid()) { 9358 return QualType(); 9359 } 9360 Init = Result.get(); 9361 DefaultedAnyToId = true; 9362 } 9363 9364 QualType DeducedType; 9365 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9366 if (!IsInitCapture) 9367 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9368 else if (isa<InitListExpr>(Init)) 9369 Diag(Range.getBegin(), 9370 diag::err_init_capture_deduction_failure_from_init_list) 9371 << Name 9372 << (DeduceInit->getType().isNull() ? TSI->getType() 9373 : DeduceInit->getType()) 9374 << DeduceInit->getSourceRange(); 9375 else 9376 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9377 << Name << TSI->getType() 9378 << (DeduceInit->getType().isNull() ? TSI->getType() 9379 : DeduceInit->getType()) 9380 << DeduceInit->getSourceRange(); 9381 } 9382 9383 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9384 // 'id' instead of a specific object type prevents most of our usual 9385 // checks. 9386 // We only want to warn outside of template instantiations, though: 9387 // inside a template, the 'id' could have come from a parameter. 9388 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9389 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9390 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9391 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range; 9392 } 9393 9394 return DeducedType; 9395 } 9396 9397 /// AddInitializerToDecl - Adds the initializer Init to the 9398 /// declaration dcl. If DirectInit is true, this is C++ direct 9399 /// initialization rather than copy initialization. 9400 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 9401 bool DirectInit, bool TypeMayContainAuto) { 9402 // If there is no declaration, there was an error parsing it. Just ignore 9403 // the initializer. 9404 if (!RealDecl || RealDecl->isInvalidDecl()) { 9405 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9406 return; 9407 } 9408 9409 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9410 // Pure-specifiers are handled in ActOnPureSpecifier. 9411 Diag(Method->getLocation(), diag::err_member_function_initialization) 9412 << Method->getDeclName() << Init->getSourceRange(); 9413 Method->setInvalidDecl(); 9414 return; 9415 } 9416 9417 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9418 if (!VDecl) { 9419 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9420 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9421 RealDecl->setInvalidDecl(); 9422 return; 9423 } 9424 9425 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9426 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 9427 // Attempt typo correction early so that the type of the init expression can 9428 // be deduced based on the chosen correction if the original init contains a 9429 // TypoExpr. 9430 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9431 if (!Res.isUsable()) { 9432 RealDecl->setInvalidDecl(); 9433 return; 9434 } 9435 Init = Res.get(); 9436 9437 QualType DeducedType = deduceVarTypeFromInitializer( 9438 VDecl, VDecl->getDeclName(), VDecl->getType(), 9439 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9440 if (DeducedType.isNull()) { 9441 RealDecl->setInvalidDecl(); 9442 return; 9443 } 9444 9445 VDecl->setType(DeducedType); 9446 assert(VDecl->isLinkageValid()); 9447 9448 // In ARC, infer lifetime. 9449 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9450 VDecl->setInvalidDecl(); 9451 9452 // If this is a redeclaration, check that the type we just deduced matches 9453 // the previously declared type. 9454 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9455 // We never need to merge the type, because we cannot form an incomplete 9456 // array of auto, nor deduce such a type. 9457 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9458 } 9459 9460 // Check the deduced type is valid for a variable declaration. 9461 CheckVariableDeclarationType(VDecl); 9462 if (VDecl->isInvalidDecl()) 9463 return; 9464 } 9465 9466 // dllimport cannot be used on variable definitions. 9467 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9468 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9469 VDecl->setInvalidDecl(); 9470 return; 9471 } 9472 9473 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9474 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9475 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9476 VDecl->setInvalidDecl(); 9477 return; 9478 } 9479 9480 if (!VDecl->getType()->isDependentType()) { 9481 // A definition must end up with a complete type, which means it must be 9482 // complete with the restriction that an array type might be completed by 9483 // the initializer; note that later code assumes this restriction. 9484 QualType BaseDeclType = VDecl->getType(); 9485 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9486 BaseDeclType = Array->getElementType(); 9487 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9488 diag::err_typecheck_decl_incomplete_type)) { 9489 RealDecl->setInvalidDecl(); 9490 return; 9491 } 9492 9493 // The variable can not have an abstract class type. 9494 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9495 diag::err_abstract_type_in_decl, 9496 AbstractVariableType)) 9497 VDecl->setInvalidDecl(); 9498 } 9499 9500 VarDecl *Def; 9501 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 9502 NamedDecl *Hidden = nullptr; 9503 if (!hasVisibleDefinition(Def, &Hidden) && 9504 (VDecl->getFormalLinkage() == InternalLinkage || 9505 VDecl->getDescribedVarTemplate() || 9506 VDecl->getNumTemplateParameterLists() || 9507 VDecl->getDeclContext()->isDependentContext())) { 9508 // The previous definition is hidden, and multiple definitions are 9509 // permitted (in separate TUs). Form another definition of it. 9510 } else { 9511 Diag(VDecl->getLocation(), diag::err_redefinition) 9512 << VDecl->getDeclName(); 9513 Diag(Def->getLocation(), diag::note_previous_definition); 9514 VDecl->setInvalidDecl(); 9515 return; 9516 } 9517 } 9518 9519 if (getLangOpts().CPlusPlus) { 9520 // C++ [class.static.data]p4 9521 // If a static data member is of const integral or const 9522 // enumeration type, its declaration in the class definition can 9523 // specify a constant-initializer which shall be an integral 9524 // constant expression (5.19). In that case, the member can appear 9525 // in integral constant expressions. The member shall still be 9526 // defined in a namespace scope if it is used in the program and the 9527 // namespace scope definition shall not contain an initializer. 9528 // 9529 // We already performed a redefinition check above, but for static 9530 // data members we also need to check whether there was an in-class 9531 // declaration with an initializer. 9532 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9533 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9534 << VDecl->getDeclName(); 9535 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9536 diag::note_previous_initializer) 9537 << 0; 9538 return; 9539 } 9540 9541 if (VDecl->hasLocalStorage()) 9542 getCurFunction()->setHasBranchProtectedScope(); 9543 9544 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 9545 VDecl->setInvalidDecl(); 9546 return; 9547 } 9548 } 9549 9550 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 9551 // a kernel function cannot be initialized." 9552 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 9553 Diag(VDecl->getLocation(), diag::err_local_cant_init); 9554 VDecl->setInvalidDecl(); 9555 return; 9556 } 9557 9558 // Get the decls type and save a reference for later, since 9559 // CheckInitializerTypes may change it. 9560 QualType DclT = VDecl->getType(), SavT = DclT; 9561 9562 // Expressions default to 'id' when we're in a debugger 9563 // and we are assigning it to a variable of Objective-C pointer type. 9564 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 9565 Init->getType() == Context.UnknownAnyTy) { 9566 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9567 if (Result.isInvalid()) { 9568 VDecl->setInvalidDecl(); 9569 return; 9570 } 9571 Init = Result.get(); 9572 } 9573 9574 // Perform the initialization. 9575 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 9576 if (!VDecl->isInvalidDecl()) { 9577 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9578 InitializationKind Kind = 9579 DirectInit 9580 ? CXXDirectInit 9581 ? InitializationKind::CreateDirect(VDecl->getLocation(), 9582 Init->getLocStart(), 9583 Init->getLocEnd()) 9584 : InitializationKind::CreateDirectList(VDecl->getLocation()) 9585 : InitializationKind::CreateCopy(VDecl->getLocation(), 9586 Init->getLocStart()); 9587 9588 MultiExprArg Args = Init; 9589 if (CXXDirectInit) 9590 Args = MultiExprArg(CXXDirectInit->getExprs(), 9591 CXXDirectInit->getNumExprs()); 9592 9593 // Try to correct any TypoExprs in the initialization arguments. 9594 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9595 ExprResult Res = CorrectDelayedTyposInExpr( 9596 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9597 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9598 return Init.Failed() ? ExprError() : E; 9599 }); 9600 if (Res.isInvalid()) { 9601 VDecl->setInvalidDecl(); 9602 } else if (Res.get() != Args[Idx]) { 9603 Args[Idx] = Res.get(); 9604 } 9605 } 9606 if (VDecl->isInvalidDecl()) 9607 return; 9608 9609 InitializationSequence InitSeq(*this, Entity, Kind, Args, 9610 /*TopLevelOfInitList=*/false, 9611 /*TreatUnavailableAsInvalid=*/false); 9612 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9613 if (Result.isInvalid()) { 9614 VDecl->setInvalidDecl(); 9615 return; 9616 } 9617 9618 Init = Result.getAs<Expr>(); 9619 } 9620 9621 // Check for self-references within variable initializers. 9622 // Variables declared within a function/method body (except for references) 9623 // are handled by a dataflow analysis. 9624 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9625 VDecl->getType()->isReferenceType()) { 9626 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9627 } 9628 9629 // If the type changed, it means we had an incomplete type that was 9630 // completed by the initializer. For example: 9631 // int ary[] = { 1, 3, 5 }; 9632 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9633 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9634 VDecl->setType(DclT); 9635 9636 if (!VDecl->isInvalidDecl()) { 9637 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9638 9639 if (VDecl->hasAttr<BlocksAttr>()) 9640 checkRetainCycles(VDecl, Init); 9641 9642 // It is safe to assign a weak reference into a strong variable. 9643 // Although this code can still have problems: 9644 // id x = self.weakProp; 9645 // id y = self.weakProp; 9646 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9647 // paths through the function. This should be revisited if 9648 // -Wrepeated-use-of-weak is made flow-sensitive. 9649 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9650 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9651 Init->getLocStart())) 9652 getCurFunction()->markSafeWeakUse(Init); 9653 } 9654 9655 // The initialization is usually a full-expression. 9656 // 9657 // FIXME: If this is a braced initialization of an aggregate, it is not 9658 // an expression, and each individual field initializer is a separate 9659 // full-expression. For instance, in: 9660 // 9661 // struct Temp { ~Temp(); }; 9662 // struct S { S(Temp); }; 9663 // struct T { S a, b; } t = { Temp(), Temp() } 9664 // 9665 // we should destroy the first Temp before constructing the second. 9666 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9667 false, 9668 VDecl->isConstexpr()); 9669 if (Result.isInvalid()) { 9670 VDecl->setInvalidDecl(); 9671 return; 9672 } 9673 Init = Result.get(); 9674 9675 // Attach the initializer to the decl. 9676 VDecl->setInit(Init); 9677 9678 if (VDecl->isLocalVarDecl()) { 9679 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9680 // static storage duration shall be constant expressions or string literals. 9681 // C++ does not have this restriction. 9682 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9683 const Expr *Culprit; 9684 if (VDecl->getStorageClass() == SC_Static) 9685 CheckForConstantInitializer(Init, DclT); 9686 // C89 is stricter than C99 for non-static aggregate types. 9687 // C89 6.5.7p3: All the expressions [...] in an initializer list 9688 // for an object that has aggregate or union type shall be 9689 // constant expressions. 9690 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9691 isa<InitListExpr>(Init) && 9692 !Init->isConstantInitializer(Context, false, &Culprit)) 9693 Diag(Culprit->getExprLoc(), 9694 diag::ext_aggregate_init_not_constant) 9695 << Culprit->getSourceRange(); 9696 } 9697 } else if (VDecl->isStaticDataMember() && 9698 VDecl->getLexicalDeclContext()->isRecord()) { 9699 // This is an in-class initialization for a static data member, e.g., 9700 // 9701 // struct S { 9702 // static const int value = 17; 9703 // }; 9704 9705 // C++ [class.mem]p4: 9706 // A member-declarator can contain a constant-initializer only 9707 // if it declares a static member (9.4) of const integral or 9708 // const enumeration type, see 9.4.2. 9709 // 9710 // C++11 [class.static.data]p3: 9711 // If a non-volatile const static data member is of integral or 9712 // enumeration type, its declaration in the class definition can 9713 // specify a brace-or-equal-initializer in which every initalizer-clause 9714 // that is an assignment-expression is a constant expression. A static 9715 // data member of literal type can be declared in the class definition 9716 // with the constexpr specifier; if so, its declaration shall specify a 9717 // brace-or-equal-initializer in which every initializer-clause that is 9718 // an assignment-expression is a constant expression. 9719 9720 // Do nothing on dependent types. 9721 if (DclT->isDependentType()) { 9722 9723 // Allow any 'static constexpr' members, whether or not they are of literal 9724 // type. We separately check that every constexpr variable is of literal 9725 // type. 9726 } else if (VDecl->isConstexpr()) { 9727 9728 // Require constness. 9729 } else if (!DclT.isConstQualified()) { 9730 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9731 << Init->getSourceRange(); 9732 VDecl->setInvalidDecl(); 9733 9734 // We allow integer constant expressions in all cases. 9735 } else if (DclT->isIntegralOrEnumerationType()) { 9736 // Check whether the expression is a constant expression. 9737 SourceLocation Loc; 9738 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9739 // In C++11, a non-constexpr const static data member with an 9740 // in-class initializer cannot be volatile. 9741 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9742 else if (Init->isValueDependent()) 9743 ; // Nothing to check. 9744 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9745 ; // Ok, it's an ICE! 9746 else if (Init->isEvaluatable(Context)) { 9747 // If we can constant fold the initializer through heroics, accept it, 9748 // but report this as a use of an extension for -pedantic. 9749 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9750 << Init->getSourceRange(); 9751 } else { 9752 // Otherwise, this is some crazy unknown case. Report the issue at the 9753 // location provided by the isIntegerConstantExpr failed check. 9754 Diag(Loc, diag::err_in_class_initializer_non_constant) 9755 << Init->getSourceRange(); 9756 VDecl->setInvalidDecl(); 9757 } 9758 9759 // We allow foldable floating-point constants as an extension. 9760 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9761 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9762 // it anyway and provide a fixit to add the 'constexpr'. 9763 if (getLangOpts().CPlusPlus11) { 9764 Diag(VDecl->getLocation(), 9765 diag::ext_in_class_initializer_float_type_cxx11) 9766 << DclT << Init->getSourceRange(); 9767 Diag(VDecl->getLocStart(), 9768 diag::note_in_class_initializer_float_type_cxx11) 9769 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9770 } else { 9771 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9772 << DclT << Init->getSourceRange(); 9773 9774 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9775 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9776 << Init->getSourceRange(); 9777 VDecl->setInvalidDecl(); 9778 } 9779 } 9780 9781 // Suggest adding 'constexpr' in C++11 for literal types. 9782 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9783 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9784 << DclT << Init->getSourceRange() 9785 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9786 VDecl->setConstexpr(true); 9787 9788 } else { 9789 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9790 << DclT << Init->getSourceRange(); 9791 VDecl->setInvalidDecl(); 9792 } 9793 } else if (VDecl->isFileVarDecl()) { 9794 if (VDecl->getStorageClass() == SC_Extern && 9795 (!getLangOpts().CPlusPlus || 9796 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 9797 VDecl->isExternC())) && 9798 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9799 Diag(VDecl->getLocation(), diag::warn_extern_init); 9800 9801 // C99 6.7.8p4. All file scoped initializers need to be constant. 9802 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9803 CheckForConstantInitializer(Init, DclT); 9804 } 9805 9806 // We will represent direct-initialization similarly to copy-initialization: 9807 // int x(1); -as-> int x = 1; 9808 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9809 // 9810 // Clients that want to distinguish between the two forms, can check for 9811 // direct initializer using VarDecl::getInitStyle(). 9812 // A major benefit is that clients that don't particularly care about which 9813 // exactly form was it (like the CodeGen) can handle both cases without 9814 // special case code. 9815 9816 // C++ 8.5p11: 9817 // The form of initialization (using parentheses or '=') is generally 9818 // insignificant, but does matter when the entity being initialized has a 9819 // class type. 9820 if (CXXDirectInit) { 9821 assert(DirectInit && "Call-style initializer must be direct init."); 9822 VDecl->setInitStyle(VarDecl::CallInit); 9823 } else if (DirectInit) { 9824 // This must be list-initialization. No other way is direct-initialization. 9825 VDecl->setInitStyle(VarDecl::ListInit); 9826 } 9827 9828 CheckCompleteVariableDeclaration(VDecl); 9829 } 9830 9831 /// ActOnInitializerError - Given that there was an error parsing an 9832 /// initializer for the given declaration, try to return to some form 9833 /// of sanity. 9834 void Sema::ActOnInitializerError(Decl *D) { 9835 // Our main concern here is re-establishing invariants like "a 9836 // variable's type is either dependent or complete". 9837 if (!D || D->isInvalidDecl()) return; 9838 9839 VarDecl *VD = dyn_cast<VarDecl>(D); 9840 if (!VD) return; 9841 9842 // Auto types are meaningless if we can't make sense of the initializer. 9843 if (ParsingInitForAutoVars.count(D)) { 9844 D->setInvalidDecl(); 9845 return; 9846 } 9847 9848 QualType Ty = VD->getType(); 9849 if (Ty->isDependentType()) return; 9850 9851 // Require a complete type. 9852 if (RequireCompleteType(VD->getLocation(), 9853 Context.getBaseElementType(Ty), 9854 diag::err_typecheck_decl_incomplete_type)) { 9855 VD->setInvalidDecl(); 9856 return; 9857 } 9858 9859 // Require a non-abstract type. 9860 if (RequireNonAbstractType(VD->getLocation(), Ty, 9861 diag::err_abstract_type_in_decl, 9862 AbstractVariableType)) { 9863 VD->setInvalidDecl(); 9864 return; 9865 } 9866 9867 // Don't bother complaining about constructors or destructors, 9868 // though. 9869 } 9870 9871 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9872 bool TypeMayContainAuto) { 9873 // If there is no declaration, there was an error parsing it. Just ignore it. 9874 if (!RealDecl) 9875 return; 9876 9877 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9878 QualType Type = Var->getType(); 9879 9880 // C++11 [dcl.spec.auto]p3 9881 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9882 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9883 << Var->getDeclName() << Type; 9884 Var->setInvalidDecl(); 9885 return; 9886 } 9887 9888 // C++11 [class.static.data]p3: A static data member can be declared with 9889 // the constexpr specifier; if so, its declaration shall specify 9890 // a brace-or-equal-initializer. 9891 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9892 // the definition of a variable [...] or the declaration of a static data 9893 // member. 9894 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9895 if (Var->isStaticDataMember()) 9896 Diag(Var->getLocation(), 9897 diag::err_constexpr_static_mem_var_requires_init) 9898 << Var->getDeclName(); 9899 else 9900 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9901 Var->setInvalidDecl(); 9902 return; 9903 } 9904 9905 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 9906 // definition having the concept specifier is called a variable concept. A 9907 // concept definition refers to [...] a variable concept and its initializer. 9908 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 9909 if (VTD->isConcept()) { 9910 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 9911 Var->setInvalidDecl(); 9912 return; 9913 } 9914 } 9915 9916 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9917 // be initialized. 9918 if (!Var->isInvalidDecl() && 9919 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9920 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9921 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9922 Var->setInvalidDecl(); 9923 return; 9924 } 9925 9926 switch (Var->isThisDeclarationADefinition()) { 9927 case VarDecl::Definition: 9928 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9929 break; 9930 9931 // We have an out-of-line definition of a static data member 9932 // that has an in-class initializer, so we type-check this like 9933 // a declaration. 9934 // 9935 // Fall through 9936 9937 case VarDecl::DeclarationOnly: 9938 // It's only a declaration. 9939 9940 // Block scope. C99 6.7p7: If an identifier for an object is 9941 // declared with no linkage (C99 6.2.2p6), the type for the 9942 // object shall be complete. 9943 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9944 !Var->hasLinkage() && !Var->isInvalidDecl() && 9945 RequireCompleteType(Var->getLocation(), Type, 9946 diag::err_typecheck_decl_incomplete_type)) 9947 Var->setInvalidDecl(); 9948 9949 // Make sure that the type is not abstract. 9950 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9951 RequireNonAbstractType(Var->getLocation(), Type, 9952 diag::err_abstract_type_in_decl, 9953 AbstractVariableType)) 9954 Var->setInvalidDecl(); 9955 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9956 Var->getStorageClass() == SC_PrivateExtern) { 9957 Diag(Var->getLocation(), diag::warn_private_extern); 9958 Diag(Var->getLocation(), diag::note_private_extern); 9959 } 9960 9961 return; 9962 9963 case VarDecl::TentativeDefinition: 9964 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9965 // object that has file scope without an initializer, and without a 9966 // storage-class specifier or with the storage-class specifier "static", 9967 // constitutes a tentative definition. Note: A tentative definition with 9968 // external linkage is valid (C99 6.2.2p5). 9969 if (!Var->isInvalidDecl()) { 9970 if (const IncompleteArrayType *ArrayT 9971 = Context.getAsIncompleteArrayType(Type)) { 9972 if (RequireCompleteType(Var->getLocation(), 9973 ArrayT->getElementType(), 9974 diag::err_illegal_decl_array_incomplete_type)) 9975 Var->setInvalidDecl(); 9976 } else if (Var->getStorageClass() == SC_Static) { 9977 // C99 6.9.2p3: If the declaration of an identifier for an object is 9978 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9979 // declared type shall not be an incomplete type. 9980 // NOTE: code such as the following 9981 // static struct s; 9982 // struct s { int a; }; 9983 // is accepted by gcc. Hence here we issue a warning instead of 9984 // an error and we do not invalidate the static declaration. 9985 // NOTE: to avoid multiple warnings, only check the first declaration. 9986 if (Var->isFirstDecl()) 9987 RequireCompleteType(Var->getLocation(), Type, 9988 diag::ext_typecheck_decl_incomplete_type); 9989 } 9990 } 9991 9992 // Record the tentative definition; we're done. 9993 if (!Var->isInvalidDecl()) 9994 TentativeDefinitions.push_back(Var); 9995 return; 9996 } 9997 9998 // Provide a specific diagnostic for uninitialized variable 9999 // definitions with incomplete array type. 10000 if (Type->isIncompleteArrayType()) { 10001 Diag(Var->getLocation(), 10002 diag::err_typecheck_incomplete_array_needs_initializer); 10003 Var->setInvalidDecl(); 10004 return; 10005 } 10006 10007 // Provide a specific diagnostic for uninitialized variable 10008 // definitions with reference type. 10009 if (Type->isReferenceType()) { 10010 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10011 << Var->getDeclName() 10012 << SourceRange(Var->getLocation(), Var->getLocation()); 10013 Var->setInvalidDecl(); 10014 return; 10015 } 10016 10017 // Do not attempt to type-check the default initializer for a 10018 // variable with dependent type. 10019 if (Type->isDependentType()) 10020 return; 10021 10022 if (Var->isInvalidDecl()) 10023 return; 10024 10025 if (!Var->hasAttr<AliasAttr>()) { 10026 if (RequireCompleteType(Var->getLocation(), 10027 Context.getBaseElementType(Type), 10028 diag::err_typecheck_decl_incomplete_type)) { 10029 Var->setInvalidDecl(); 10030 return; 10031 } 10032 } else { 10033 return; 10034 } 10035 10036 // The variable can not have an abstract class type. 10037 if (RequireNonAbstractType(Var->getLocation(), Type, 10038 diag::err_abstract_type_in_decl, 10039 AbstractVariableType)) { 10040 Var->setInvalidDecl(); 10041 return; 10042 } 10043 10044 // Check for jumps past the implicit initializer. C++0x 10045 // clarifies that this applies to a "variable with automatic 10046 // storage duration", not a "local variable". 10047 // C++11 [stmt.dcl]p3 10048 // A program that jumps from a point where a variable with automatic 10049 // storage duration is not in scope to a point where it is in scope is 10050 // ill-formed unless the variable has scalar type, class type with a 10051 // trivial default constructor and a trivial destructor, a cv-qualified 10052 // version of one of these types, or an array of one of the preceding 10053 // types and is declared without an initializer. 10054 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10055 if (const RecordType *Record 10056 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10057 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10058 // Mark the function for further checking even if the looser rules of 10059 // C++11 do not require such checks, so that we can diagnose 10060 // incompatibilities with C++98. 10061 if (!CXXRecord->isPOD()) 10062 getCurFunction()->setHasBranchProtectedScope(); 10063 } 10064 } 10065 10066 // C++03 [dcl.init]p9: 10067 // If no initializer is specified for an object, and the 10068 // object is of (possibly cv-qualified) non-POD class type (or 10069 // array thereof), the object shall be default-initialized; if 10070 // the object is of const-qualified type, the underlying class 10071 // type shall have a user-declared default 10072 // constructor. Otherwise, if no initializer is specified for 10073 // a non- static object, the object and its subobjects, if 10074 // any, have an indeterminate initial value); if the object 10075 // or any of its subobjects are of const-qualified type, the 10076 // program is ill-formed. 10077 // C++0x [dcl.init]p11: 10078 // If no initializer is specified for an object, the object is 10079 // default-initialized; [...]. 10080 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10081 InitializationKind Kind 10082 = InitializationKind::CreateDefault(Var->getLocation()); 10083 10084 InitializationSequence InitSeq(*this, Entity, Kind, None); 10085 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10086 if (Init.isInvalid()) 10087 Var->setInvalidDecl(); 10088 else if (Init.get()) { 10089 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10090 // This is important for template substitution. 10091 Var->setInitStyle(VarDecl::CallInit); 10092 } 10093 10094 CheckCompleteVariableDeclaration(Var); 10095 } 10096 } 10097 10098 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10099 // If there is no declaration, there was an error parsing it. Ignore it. 10100 if (!D) 10101 return; 10102 10103 VarDecl *VD = dyn_cast<VarDecl>(D); 10104 if (!VD) { 10105 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10106 D->setInvalidDecl(); 10107 return; 10108 } 10109 10110 VD->setCXXForRangeDecl(true); 10111 10112 // for-range-declaration cannot be given a storage class specifier. 10113 int Error = -1; 10114 switch (VD->getStorageClass()) { 10115 case SC_None: 10116 break; 10117 case SC_Extern: 10118 Error = 0; 10119 break; 10120 case SC_Static: 10121 Error = 1; 10122 break; 10123 case SC_PrivateExtern: 10124 Error = 2; 10125 break; 10126 case SC_Auto: 10127 Error = 3; 10128 break; 10129 case SC_Register: 10130 Error = 4; 10131 break; 10132 } 10133 if (Error != -1) { 10134 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10135 << VD->getDeclName() << Error; 10136 D->setInvalidDecl(); 10137 } 10138 } 10139 10140 StmtResult 10141 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10142 IdentifierInfo *Ident, 10143 ParsedAttributes &Attrs, 10144 SourceLocation AttrEnd) { 10145 // C++1y [stmt.iter]p1: 10146 // A range-based for statement of the form 10147 // for ( for-range-identifier : for-range-initializer ) statement 10148 // is equivalent to 10149 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10150 DeclSpec DS(Attrs.getPool().getFactory()); 10151 10152 const char *PrevSpec; 10153 unsigned DiagID; 10154 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10155 getPrintingPolicy()); 10156 10157 Declarator D(DS, Declarator::ForContext); 10158 D.SetIdentifier(Ident, IdentLoc); 10159 D.takeAttributes(Attrs, AttrEnd); 10160 10161 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10162 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10163 EmptyAttrs, IdentLoc); 10164 Decl *Var = ActOnDeclarator(S, D); 10165 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10166 FinalizeDeclaration(Var); 10167 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10168 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10169 } 10170 10171 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10172 if (var->isInvalidDecl()) return; 10173 10174 if (getLangOpts().OpenCL) { 10175 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10176 // initialiser 10177 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10178 !var->hasInit()) { 10179 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10180 << 1 /*Init*/; 10181 var->setInvalidDecl(); 10182 return; 10183 } 10184 } 10185 10186 // In Objective-C, don't allow jumps past the implicit initialization of a 10187 // local retaining variable. 10188 if (getLangOpts().ObjC1 && 10189 var->hasLocalStorage()) { 10190 switch (var->getType().getObjCLifetime()) { 10191 case Qualifiers::OCL_None: 10192 case Qualifiers::OCL_ExplicitNone: 10193 case Qualifiers::OCL_Autoreleasing: 10194 break; 10195 10196 case Qualifiers::OCL_Weak: 10197 case Qualifiers::OCL_Strong: 10198 getCurFunction()->setHasBranchProtectedScope(); 10199 break; 10200 } 10201 } 10202 10203 // Warn about externally-visible variables being defined without a 10204 // prior declaration. We only want to do this for global 10205 // declarations, but we also specifically need to avoid doing it for 10206 // class members because the linkage of an anonymous class can 10207 // change if it's later given a typedef name. 10208 if (var->isThisDeclarationADefinition() && 10209 var->getDeclContext()->getRedeclContext()->isFileContext() && 10210 var->isExternallyVisible() && var->hasLinkage() && 10211 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10212 var->getLocation())) { 10213 // Find a previous declaration that's not a definition. 10214 VarDecl *prev = var->getPreviousDecl(); 10215 while (prev && prev->isThisDeclarationADefinition()) 10216 prev = prev->getPreviousDecl(); 10217 10218 if (!prev) 10219 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10220 } 10221 10222 if (var->getTLSKind() == VarDecl::TLS_Static) { 10223 const Expr *Culprit; 10224 if (var->getType().isDestructedType()) { 10225 // GNU C++98 edits for __thread, [basic.start.term]p3: 10226 // The type of an object with thread storage duration shall not 10227 // have a non-trivial destructor. 10228 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10229 if (getLangOpts().CPlusPlus11) 10230 Diag(var->getLocation(), diag::note_use_thread_local); 10231 } else if (getLangOpts().CPlusPlus && var->hasInit() && 10232 !var->getInit()->isConstantInitializer( 10233 Context, var->getType()->isReferenceType(), &Culprit)) { 10234 // GNU C++98 edits for __thread, [basic.start.init]p4: 10235 // An object of thread storage duration shall not require dynamic 10236 // initialization. 10237 // FIXME: Need strict checking here. 10238 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 10239 << Culprit->getSourceRange(); 10240 if (getLangOpts().CPlusPlus11) 10241 Diag(var->getLocation(), diag::note_use_thread_local); 10242 } 10243 } 10244 10245 // Apply section attributes and pragmas to global variables. 10246 bool GlobalStorage = var->hasGlobalStorage(); 10247 if (GlobalStorage && var->isThisDeclarationADefinition() && 10248 ActiveTemplateInstantiations.empty()) { 10249 PragmaStack<StringLiteral *> *Stack = nullptr; 10250 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10251 if (var->getType().isConstQualified()) 10252 Stack = &ConstSegStack; 10253 else if (!var->getInit()) { 10254 Stack = &BSSSegStack; 10255 SectionFlags |= ASTContext::PSF_Write; 10256 } else { 10257 Stack = &DataSegStack; 10258 SectionFlags |= ASTContext::PSF_Write; 10259 } 10260 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10261 var->addAttr(SectionAttr::CreateImplicit( 10262 Context, SectionAttr::Declspec_allocate, 10263 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10264 } 10265 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10266 if (UnifySection(SA->getName(), SectionFlags, var)) 10267 var->dropAttr<SectionAttr>(); 10268 10269 // Apply the init_seg attribute if this has an initializer. If the 10270 // initializer turns out to not be dynamic, we'll end up ignoring this 10271 // attribute. 10272 if (CurInitSeg && var->getInit()) 10273 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10274 CurInitSegLoc)); 10275 } 10276 10277 // All the following checks are C++ only. 10278 if (!getLangOpts().CPlusPlus) return; 10279 10280 QualType type = var->getType(); 10281 if (type->isDependentType()) return; 10282 10283 // __block variables might require us to capture a copy-initializer. 10284 if (var->hasAttr<BlocksAttr>()) { 10285 // It's currently invalid to ever have a __block variable with an 10286 // array type; should we diagnose that here? 10287 10288 // Regardless, we don't want to ignore array nesting when 10289 // constructing this copy. 10290 if (type->isStructureOrClassType()) { 10291 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10292 SourceLocation poi = var->getLocation(); 10293 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10294 ExprResult result 10295 = PerformMoveOrCopyInitialization( 10296 InitializedEntity::InitializeBlock(poi, type, false), 10297 var, var->getType(), varRef, /*AllowNRVO=*/true); 10298 if (!result.isInvalid()) { 10299 result = MaybeCreateExprWithCleanups(result); 10300 Expr *init = result.getAs<Expr>(); 10301 Context.setBlockVarCopyInits(var, init); 10302 } 10303 } 10304 } 10305 10306 Expr *Init = var->getInit(); 10307 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10308 QualType baseType = Context.getBaseElementType(type); 10309 10310 if (!var->getDeclContext()->isDependentContext() && 10311 Init && !Init->isValueDependent()) { 10312 if (IsGlobal && !var->isConstexpr() && 10313 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10314 var->getLocation())) { 10315 // Warn about globals which don't have a constant initializer. Don't 10316 // warn about globals with a non-trivial destructor because we already 10317 // warned about them. 10318 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10319 if (!(RD && !RD->hasTrivialDestructor()) && 10320 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 10321 Diag(var->getLocation(), diag::warn_global_constructor) 10322 << Init->getSourceRange(); 10323 } 10324 10325 if (var->isConstexpr()) { 10326 SmallVector<PartialDiagnosticAt, 8> Notes; 10327 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10328 SourceLocation DiagLoc = var->getLocation(); 10329 // If the note doesn't add any useful information other than a source 10330 // location, fold it into the primary diagnostic. 10331 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10332 diag::note_invalid_subexpr_in_const_expr) { 10333 DiagLoc = Notes[0].first; 10334 Notes.clear(); 10335 } 10336 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10337 << var << Init->getSourceRange(); 10338 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10339 Diag(Notes[I].first, Notes[I].second); 10340 } 10341 } else if (var->isUsableInConstantExpressions(Context)) { 10342 // Check whether the initializer of a const variable of integral or 10343 // enumeration type is an ICE now, since we can't tell whether it was 10344 // initialized by a constant expression if we check later. 10345 var->checkInitIsICE(); 10346 } 10347 } 10348 10349 // Require the destructor. 10350 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10351 FinalizeVarWithDestructor(var, recordType); 10352 } 10353 10354 /// \brief Determines if a variable's alignment is dependent. 10355 static bool hasDependentAlignment(VarDecl *VD) { 10356 if (VD->getType()->isDependentType()) 10357 return true; 10358 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10359 if (I->isAlignmentDependent()) 10360 return true; 10361 return false; 10362 } 10363 10364 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10365 /// any semantic actions necessary after any initializer has been attached. 10366 void 10367 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10368 // Note that we are no longer parsing the initializer for this declaration. 10369 ParsingInitForAutoVars.erase(ThisDecl); 10370 10371 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10372 if (!VD) 10373 return; 10374 10375 checkAttributesAfterMerging(*this, *VD); 10376 10377 // Perform TLS alignment check here after attributes attached to the variable 10378 // which may affect the alignment have been processed. Only perform the check 10379 // if the target has a maximum TLS alignment (zero means no constraints). 10380 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10381 // Protect the check so that it's not performed on dependent types and 10382 // dependent alignments (we can't determine the alignment in that case). 10383 if (VD->getTLSKind() && !hasDependentAlignment(VD)) { 10384 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10385 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10386 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10387 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10388 << (unsigned)MaxAlignChars.getQuantity(); 10389 } 10390 } 10391 } 10392 10393 // Static locals inherit dll attributes from their function. 10394 if (VD->isStaticLocal()) { 10395 if (FunctionDecl *FD = 10396 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10397 if (Attr *A = getDLLAttr(FD)) { 10398 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10399 NewAttr->setInherited(true); 10400 VD->addAttr(NewAttr); 10401 } 10402 } 10403 } 10404 10405 // Perform check for initializers of device-side global variables. 10406 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 10407 // 7.5). CUDA also allows constant initializers for __constant__ and 10408 // __device__ variables. 10409 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 10410 const Expr *Init = VD->getInit(); 10411 const bool IsGlobal = VD->hasGlobalStorage() && !VD->isStaticLocal(); 10412 if (Init && IsGlobal && 10413 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 10414 VD->hasAttr<CUDASharedAttr>())) { 10415 bool AllowedInit = false; 10416 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 10417 AllowedInit = 10418 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 10419 // We'll allow constant initializers even if it's a non-empty 10420 // constructor according to CUDA rules. This deviates from NVCC, 10421 // but allows us to handle things like constexpr constructors. 10422 if (!AllowedInit && 10423 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 10424 AllowedInit = VD->getInit()->isConstantInitializer( 10425 Context, VD->getType()->isReferenceType()); 10426 10427 if (!AllowedInit) { 10428 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 10429 ? diag::err_shared_var_init 10430 : diag::err_dynamic_var_init) 10431 << Init->getSourceRange(); 10432 VD->setInvalidDecl(); 10433 } 10434 } 10435 } 10436 10437 // Grab the dllimport or dllexport attribute off of the VarDecl. 10438 const InheritableAttr *DLLAttr = getDLLAttr(VD); 10439 10440 // Imported static data members cannot be defined out-of-line. 10441 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 10442 if (VD->isStaticDataMember() && VD->isOutOfLine() && 10443 VD->isThisDeclarationADefinition()) { 10444 // We allow definitions of dllimport class template static data members 10445 // with a warning. 10446 CXXRecordDecl *Context = 10447 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 10448 bool IsClassTemplateMember = 10449 isa<ClassTemplatePartialSpecializationDecl>(Context) || 10450 Context->getDescribedClassTemplate(); 10451 10452 Diag(VD->getLocation(), 10453 IsClassTemplateMember 10454 ? diag::warn_attribute_dllimport_static_field_definition 10455 : diag::err_attribute_dllimport_static_field_definition); 10456 Diag(IA->getLocation(), diag::note_attribute); 10457 if (!IsClassTemplateMember) 10458 VD->setInvalidDecl(); 10459 } 10460 } 10461 10462 // dllimport/dllexport variables cannot be thread local, their TLS index 10463 // isn't exported with the variable. 10464 if (DLLAttr && VD->getTLSKind()) { 10465 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 10466 if (F && getDLLAttr(F)) { 10467 assert(VD->isStaticLocal()); 10468 // But if this is a static local in a dlimport/dllexport function, the 10469 // function will never be inlined, which means the var would never be 10470 // imported, so having it marked import/export is safe. 10471 } else { 10472 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 10473 << DLLAttr; 10474 VD->setInvalidDecl(); 10475 } 10476 } 10477 10478 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 10479 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 10480 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 10481 VD->dropAttr<UsedAttr>(); 10482 } 10483 } 10484 10485 const DeclContext *DC = VD->getDeclContext(); 10486 // If there's a #pragma GCC visibility in scope, and this isn't a class 10487 // member, set the visibility of this variable. 10488 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 10489 AddPushedVisibilityAttribute(VD); 10490 10491 // FIXME: Warn on unused templates. 10492 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 10493 !isa<VarTemplatePartialSpecializationDecl>(VD)) 10494 MarkUnusedFileScopedDecl(VD); 10495 10496 // Now we have parsed the initializer and can update the table of magic 10497 // tag values. 10498 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 10499 !VD->getType()->isIntegralOrEnumerationType()) 10500 return; 10501 10502 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 10503 const Expr *MagicValueExpr = VD->getInit(); 10504 if (!MagicValueExpr) { 10505 continue; 10506 } 10507 llvm::APSInt MagicValueInt; 10508 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 10509 Diag(I->getRange().getBegin(), 10510 diag::err_type_tag_for_datatype_not_ice) 10511 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10512 continue; 10513 } 10514 if (MagicValueInt.getActiveBits() > 64) { 10515 Diag(I->getRange().getBegin(), 10516 diag::err_type_tag_for_datatype_too_large) 10517 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10518 continue; 10519 } 10520 uint64_t MagicValue = MagicValueInt.getZExtValue(); 10521 RegisterTypeTagForDatatype(I->getArgumentKind(), 10522 MagicValue, 10523 I->getMatchingCType(), 10524 I->getLayoutCompatible(), 10525 I->getMustBeNull()); 10526 } 10527 } 10528 10529 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 10530 ArrayRef<Decl *> Group) { 10531 SmallVector<Decl*, 8> Decls; 10532 10533 if (DS.isTypeSpecOwned()) 10534 Decls.push_back(DS.getRepAsDecl()); 10535 10536 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 10537 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10538 if (Decl *D = Group[i]) { 10539 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 10540 if (!FirstDeclaratorInGroup) 10541 FirstDeclaratorInGroup = DD; 10542 Decls.push_back(D); 10543 } 10544 10545 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 10546 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 10547 handleTagNumbering(Tag, S); 10548 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 10549 getLangOpts().CPlusPlus) 10550 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 10551 } 10552 } 10553 10554 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 10555 } 10556 10557 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 10558 /// group, performing any necessary semantic checking. 10559 Sema::DeclGroupPtrTy 10560 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 10561 bool TypeMayContainAuto) { 10562 // C++0x [dcl.spec.auto]p7: 10563 // If the type deduced for the template parameter U is not the same in each 10564 // deduction, the program is ill-formed. 10565 // FIXME: When initializer-list support is added, a distinction is needed 10566 // between the deduced type U and the deduced type which 'auto' stands for. 10567 // auto a = 0, b = { 1, 2, 3 }; 10568 // is legal because the deduced type U is 'int' in both cases. 10569 if (TypeMayContainAuto && Group.size() > 1) { 10570 QualType Deduced; 10571 CanQualType DeducedCanon; 10572 VarDecl *DeducedDecl = nullptr; 10573 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10574 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 10575 AutoType *AT = D->getType()->getContainedAutoType(); 10576 // Don't reissue diagnostics when instantiating a template. 10577 if (AT && D->isInvalidDecl()) 10578 break; 10579 QualType U = AT ? AT->getDeducedType() : QualType(); 10580 if (!U.isNull()) { 10581 CanQualType UCanon = Context.getCanonicalType(U); 10582 if (Deduced.isNull()) { 10583 Deduced = U; 10584 DeducedCanon = UCanon; 10585 DeducedDecl = D; 10586 } else if (DeducedCanon != UCanon) { 10587 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 10588 diag::err_auto_different_deductions) 10589 << (unsigned)AT->getKeyword() 10590 << Deduced << DeducedDecl->getDeclName() 10591 << U << D->getDeclName() 10592 << DeducedDecl->getInit()->getSourceRange() 10593 << D->getInit()->getSourceRange(); 10594 D->setInvalidDecl(); 10595 break; 10596 } 10597 } 10598 } 10599 } 10600 } 10601 10602 ActOnDocumentableDecls(Group); 10603 10604 return DeclGroupPtrTy::make( 10605 DeclGroupRef::Create(Context, Group.data(), Group.size())); 10606 } 10607 10608 void Sema::ActOnDocumentableDecl(Decl *D) { 10609 ActOnDocumentableDecls(D); 10610 } 10611 10612 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 10613 // Don't parse the comment if Doxygen diagnostics are ignored. 10614 if (Group.empty() || !Group[0]) 10615 return; 10616 10617 if (Diags.isIgnored(diag::warn_doc_param_not_found, 10618 Group[0]->getLocation()) && 10619 Diags.isIgnored(diag::warn_unknown_comment_command_name, 10620 Group[0]->getLocation())) 10621 return; 10622 10623 if (Group.size() >= 2) { 10624 // This is a decl group. Normally it will contain only declarations 10625 // produced from declarator list. But in case we have any definitions or 10626 // additional declaration references: 10627 // 'typedef struct S {} S;' 10628 // 'typedef struct S *S;' 10629 // 'struct S *pS;' 10630 // FinalizeDeclaratorGroup adds these as separate declarations. 10631 Decl *MaybeTagDecl = Group[0]; 10632 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 10633 Group = Group.slice(1); 10634 } 10635 } 10636 10637 // See if there are any new comments that are not attached to a decl. 10638 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 10639 if (!Comments.empty() && 10640 !Comments.back()->isAttached()) { 10641 // There is at least one comment that not attached to a decl. 10642 // Maybe it should be attached to one of these decls? 10643 // 10644 // Note that this way we pick up not only comments that precede the 10645 // declaration, but also comments that *follow* the declaration -- thanks to 10646 // the lookahead in the lexer: we've consumed the semicolon and looked 10647 // ahead through comments. 10648 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10649 Context.getCommentForDecl(Group[i], &PP); 10650 } 10651 } 10652 10653 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 10654 /// to introduce parameters into function prototype scope. 10655 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 10656 const DeclSpec &DS = D.getDeclSpec(); 10657 10658 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 10659 10660 // C++03 [dcl.stc]p2 also permits 'auto'. 10661 StorageClass SC = SC_None; 10662 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 10663 SC = SC_Register; 10664 } else if (getLangOpts().CPlusPlus && 10665 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 10666 SC = SC_Auto; 10667 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 10668 Diag(DS.getStorageClassSpecLoc(), 10669 diag::err_invalid_storage_class_in_func_decl); 10670 D.getMutableDeclSpec().ClearStorageClassSpecs(); 10671 } 10672 10673 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 10674 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 10675 << DeclSpec::getSpecifierName(TSCS); 10676 if (DS.isConstexprSpecified()) 10677 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 10678 << 0; 10679 if (DS.isConceptSpecified()) 10680 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 10681 10682 DiagnoseFunctionSpecifiers(DS); 10683 10684 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10685 QualType parmDeclType = TInfo->getType(); 10686 10687 if (getLangOpts().CPlusPlus) { 10688 // Check that there are no default arguments inside the type of this 10689 // parameter. 10690 CheckExtraCXXDefaultArguments(D); 10691 10692 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 10693 if (D.getCXXScopeSpec().isSet()) { 10694 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 10695 << D.getCXXScopeSpec().getRange(); 10696 D.getCXXScopeSpec().clear(); 10697 } 10698 } 10699 10700 // Ensure we have a valid name 10701 IdentifierInfo *II = nullptr; 10702 if (D.hasName()) { 10703 II = D.getIdentifier(); 10704 if (!II) { 10705 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 10706 << GetNameForDeclarator(D).getName(); 10707 D.setInvalidType(true); 10708 } 10709 } 10710 10711 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 10712 if (II) { 10713 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 10714 ForRedeclaration); 10715 LookupName(R, S); 10716 if (R.isSingleResult()) { 10717 NamedDecl *PrevDecl = R.getFoundDecl(); 10718 if (PrevDecl->isTemplateParameter()) { 10719 // Maybe we will complain about the shadowed template parameter. 10720 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10721 // Just pretend that we didn't see the previous declaration. 10722 PrevDecl = nullptr; 10723 } else if (S->isDeclScope(PrevDecl)) { 10724 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 10725 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10726 10727 // Recover by removing the name 10728 II = nullptr; 10729 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 10730 D.setInvalidType(true); 10731 } 10732 } 10733 } 10734 10735 // Temporarily put parameter variables in the translation unit, not 10736 // the enclosing context. This prevents them from accidentally 10737 // looking like class members in C++. 10738 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 10739 D.getLocStart(), 10740 D.getIdentifierLoc(), II, 10741 parmDeclType, TInfo, 10742 SC); 10743 10744 if (D.isInvalidType()) 10745 New->setInvalidDecl(); 10746 10747 assert(S->isFunctionPrototypeScope()); 10748 assert(S->getFunctionPrototypeDepth() >= 1); 10749 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 10750 S->getNextFunctionPrototypeIndex()); 10751 10752 // Add the parameter declaration into this scope. 10753 S->AddDecl(New); 10754 if (II) 10755 IdResolver.AddDecl(New); 10756 10757 ProcessDeclAttributes(S, New, D); 10758 10759 if (D.getDeclSpec().isModulePrivateSpecified()) 10760 Diag(New->getLocation(), diag::err_module_private_local) 10761 << 1 << New->getDeclName() 10762 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10763 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10764 10765 if (New->hasAttr<BlocksAttr>()) { 10766 Diag(New->getLocation(), diag::err_block_on_nonlocal); 10767 } 10768 return New; 10769 } 10770 10771 /// \brief Synthesizes a variable for a parameter arising from a 10772 /// typedef. 10773 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 10774 SourceLocation Loc, 10775 QualType T) { 10776 /* FIXME: setting StartLoc == Loc. 10777 Would it be worth to modify callers so as to provide proper source 10778 location for the unnamed parameters, embedding the parameter's type? */ 10779 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 10780 T, Context.getTrivialTypeSourceInfo(T, Loc), 10781 SC_None, nullptr); 10782 Param->setImplicit(); 10783 return Param; 10784 } 10785 10786 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 10787 ParmVarDecl * const *ParamEnd) { 10788 // Don't diagnose unused-parameter errors in template instantiations; we 10789 // will already have done so in the template itself. 10790 if (!ActiveTemplateInstantiations.empty()) 10791 return; 10792 10793 for (; Param != ParamEnd; ++Param) { 10794 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 10795 !(*Param)->hasAttr<UnusedAttr>()) { 10796 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 10797 << (*Param)->getDeclName(); 10798 } 10799 } 10800 } 10801 10802 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 10803 ParmVarDecl * const *ParamEnd, 10804 QualType ReturnTy, 10805 NamedDecl *D) { 10806 if (LangOpts.NumLargeByValueCopy == 0) // No check. 10807 return; 10808 10809 // Warn if the return value is pass-by-value and larger than the specified 10810 // threshold. 10811 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 10812 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 10813 if (Size > LangOpts.NumLargeByValueCopy) 10814 Diag(D->getLocation(), diag::warn_return_value_size) 10815 << D->getDeclName() << Size; 10816 } 10817 10818 // Warn if any parameter is pass-by-value and larger than the specified 10819 // threshold. 10820 for (; Param != ParamEnd; ++Param) { 10821 QualType T = (*Param)->getType(); 10822 if (T->isDependentType() || !T.isPODType(Context)) 10823 continue; 10824 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 10825 if (Size > LangOpts.NumLargeByValueCopy) 10826 Diag((*Param)->getLocation(), diag::warn_parameter_size) 10827 << (*Param)->getDeclName() << Size; 10828 } 10829 } 10830 10831 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 10832 SourceLocation NameLoc, IdentifierInfo *Name, 10833 QualType T, TypeSourceInfo *TSInfo, 10834 StorageClass SC) { 10835 // In ARC, infer a lifetime qualifier for appropriate parameter types. 10836 if (getLangOpts().ObjCAutoRefCount && 10837 T.getObjCLifetime() == Qualifiers::OCL_None && 10838 T->isObjCLifetimeType()) { 10839 10840 Qualifiers::ObjCLifetime lifetime; 10841 10842 // Special cases for arrays: 10843 // - if it's const, use __unsafe_unretained 10844 // - otherwise, it's an error 10845 if (T->isArrayType()) { 10846 if (!T.isConstQualified()) { 10847 DelayedDiagnostics.add( 10848 sema::DelayedDiagnostic::makeForbiddenType( 10849 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 10850 } 10851 lifetime = Qualifiers::OCL_ExplicitNone; 10852 } else { 10853 lifetime = T->getObjCARCImplicitLifetime(); 10854 } 10855 T = Context.getLifetimeQualifiedType(T, lifetime); 10856 } 10857 10858 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 10859 Context.getAdjustedParameterType(T), 10860 TSInfo, SC, nullptr); 10861 10862 // Parameters can not be abstract class types. 10863 // For record types, this is done by the AbstractClassUsageDiagnoser once 10864 // the class has been completely parsed. 10865 if (!CurContext->isRecord() && 10866 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 10867 AbstractParamType)) 10868 New->setInvalidDecl(); 10869 10870 // Parameter declarators cannot be interface types. All ObjC objects are 10871 // passed by reference. 10872 if (T->isObjCObjectType()) { 10873 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 10874 Diag(NameLoc, 10875 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 10876 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 10877 T = Context.getObjCObjectPointerType(T); 10878 New->setType(T); 10879 } 10880 10881 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 10882 // duration shall not be qualified by an address-space qualifier." 10883 // Since all parameters have automatic store duration, they can not have 10884 // an address space. 10885 if (T.getAddressSpace() != 0) { 10886 // OpenCL allows function arguments declared to be an array of a type 10887 // to be qualified with an address space. 10888 if (!(getLangOpts().OpenCL && T->isArrayType())) { 10889 Diag(NameLoc, diag::err_arg_with_address_space); 10890 New->setInvalidDecl(); 10891 } 10892 } 10893 10894 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. 10895 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. 10896 if (getLangOpts().OpenCL && T->isPointerType()) { 10897 const QualType PTy = T->getPointeeType(); 10898 if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) { 10899 Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy; 10900 New->setInvalidDecl(); 10901 } 10902 } 10903 10904 return New; 10905 } 10906 10907 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 10908 SourceLocation LocAfterDecls) { 10909 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10910 10911 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 10912 // for a K&R function. 10913 if (!FTI.hasPrototype) { 10914 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10915 --i; 10916 if (FTI.Params[i].Param == nullptr) { 10917 SmallString<256> Code; 10918 llvm::raw_svector_ostream(Code) 10919 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10920 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10921 << FTI.Params[i].Ident 10922 << FixItHint::CreateInsertion(LocAfterDecls, Code); 10923 10924 // Implicitly declare the argument as type 'int' for lack of a better 10925 // type. 10926 AttributeFactory attrs; 10927 DeclSpec DS(attrs); 10928 const char* PrevSpec; // unused 10929 unsigned DiagID; // unused 10930 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10931 DiagID, Context.getPrintingPolicy()); 10932 // Use the identifier location for the type source range. 10933 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10934 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10935 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10936 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10937 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10938 } 10939 } 10940 } 10941 } 10942 10943 Decl * 10944 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 10945 MultiTemplateParamsArg TemplateParameterLists, 10946 SkipBodyInfo *SkipBody) { 10947 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10948 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10949 Scope *ParentScope = FnBodyScope->getParent(); 10950 10951 D.setFunctionDefinitionKind(FDK_Definition); 10952 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 10953 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 10954 } 10955 10956 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 10957 Consumer.HandleInlineFunctionDefinition(D); 10958 } 10959 10960 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10961 const FunctionDecl*& PossibleZeroParamPrototype) { 10962 // Don't warn about invalid declarations. 10963 if (FD->isInvalidDecl()) 10964 return false; 10965 10966 // Or declarations that aren't global. 10967 if (!FD->isGlobal()) 10968 return false; 10969 10970 // Don't warn about C++ member functions. 10971 if (isa<CXXMethodDecl>(FD)) 10972 return false; 10973 10974 // Don't warn about 'main'. 10975 if (FD->isMain()) 10976 return false; 10977 10978 // Don't warn about inline functions. 10979 if (FD->isInlined()) 10980 return false; 10981 10982 // Don't warn about function templates. 10983 if (FD->getDescribedFunctionTemplate()) 10984 return false; 10985 10986 // Don't warn about function template specializations. 10987 if (FD->isFunctionTemplateSpecialization()) 10988 return false; 10989 10990 // Don't warn for OpenCL kernels. 10991 if (FD->hasAttr<OpenCLKernelAttr>()) 10992 return false; 10993 10994 // Don't warn on explicitly deleted functions. 10995 if (FD->isDeleted()) 10996 return false; 10997 10998 bool MissingPrototype = true; 10999 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11000 Prev; Prev = Prev->getPreviousDecl()) { 11001 // Ignore any declarations that occur in function or method 11002 // scope, because they aren't visible from the header. 11003 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11004 continue; 11005 11006 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11007 if (FD->getNumParams() == 0) 11008 PossibleZeroParamPrototype = Prev; 11009 break; 11010 } 11011 11012 return MissingPrototype; 11013 } 11014 11015 void 11016 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11017 const FunctionDecl *EffectiveDefinition, 11018 SkipBodyInfo *SkipBody) { 11019 // Don't complain if we're in GNU89 mode and the previous definition 11020 // was an extern inline function. 11021 const FunctionDecl *Definition = EffectiveDefinition; 11022 if (!Definition) 11023 if (!FD->isDefined(Definition)) 11024 return; 11025 11026 if (canRedefineFunction(Definition, getLangOpts())) 11027 return; 11028 11029 // If we don't have a visible definition of the function, and it's inline or 11030 // a template, skip the new definition. 11031 if (SkipBody && !hasVisibleDefinition(Definition) && 11032 (Definition->getFormalLinkage() == InternalLinkage || 11033 Definition->isInlined() || 11034 Definition->getDescribedFunctionTemplate() || 11035 Definition->getNumTemplateParameterLists())) { 11036 SkipBody->ShouldSkip = true; 11037 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11038 makeMergedDefinitionVisible(TD, FD->getLocation()); 11039 else 11040 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 11041 FD->getLocation()); 11042 return; 11043 } 11044 11045 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11046 Definition->getStorageClass() == SC_Extern) 11047 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11048 << FD->getDeclName() << getLangOpts().CPlusPlus; 11049 else 11050 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11051 11052 Diag(Definition->getLocation(), diag::note_previous_definition); 11053 FD->setInvalidDecl(); 11054 } 11055 11056 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11057 Sema &S) { 11058 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11059 11060 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11061 LSI->CallOperator = CallOperator; 11062 LSI->Lambda = LambdaClass; 11063 LSI->ReturnType = CallOperator->getReturnType(); 11064 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11065 11066 if (LCD == LCD_None) 11067 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11068 else if (LCD == LCD_ByCopy) 11069 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11070 else if (LCD == LCD_ByRef) 11071 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11072 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11073 11074 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11075 LSI->Mutable = !CallOperator->isConst(); 11076 11077 // Add the captures to the LSI so they can be noted as already 11078 // captured within tryCaptureVar. 11079 auto I = LambdaClass->field_begin(); 11080 for (const auto &C : LambdaClass->captures()) { 11081 if (C.capturesVariable()) { 11082 VarDecl *VD = C.getCapturedVar(); 11083 if (VD->isInitCapture()) 11084 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11085 QualType CaptureType = VD->getType(); 11086 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11087 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11088 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11089 /*EllipsisLoc*/C.isPackExpansion() 11090 ? C.getEllipsisLoc() : SourceLocation(), 11091 CaptureType, /*Expr*/ nullptr); 11092 11093 } else if (C.capturesThis()) { 11094 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11095 S.getCurrentThisType(), /*Expr*/ nullptr, 11096 C.getCaptureKind() == LCK_StarThis); 11097 } else { 11098 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11099 } 11100 ++I; 11101 } 11102 } 11103 11104 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11105 SkipBodyInfo *SkipBody) { 11106 // Clear the last template instantiation error context. 11107 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 11108 11109 if (!D) 11110 return D; 11111 FunctionDecl *FD = nullptr; 11112 11113 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11114 FD = FunTmpl->getTemplatedDecl(); 11115 else 11116 FD = cast<FunctionDecl>(D); 11117 11118 // See if this is a redefinition. 11119 if (!FD->isLateTemplateParsed()) { 11120 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11121 11122 // If we're skipping the body, we're done. Don't enter the scope. 11123 if (SkipBody && SkipBody->ShouldSkip) 11124 return D; 11125 } 11126 11127 // If we are instantiating a generic lambda call operator, push 11128 // a LambdaScopeInfo onto the function stack. But use the information 11129 // that's already been calculated (ActOnLambdaExpr) to prime the current 11130 // LambdaScopeInfo. 11131 // When the template operator is being specialized, the LambdaScopeInfo, 11132 // has to be properly restored so that tryCaptureVariable doesn't try 11133 // and capture any new variables. In addition when calculating potential 11134 // captures during transformation of nested lambdas, it is necessary to 11135 // have the LSI properly restored. 11136 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11137 assert(ActiveTemplateInstantiations.size() && 11138 "There should be an active template instantiation on the stack " 11139 "when instantiating a generic lambda!"); 11140 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 11141 } 11142 else 11143 // Enter a new function scope 11144 PushFunctionScope(); 11145 11146 // Builtin functions cannot be defined. 11147 if (unsigned BuiltinID = FD->getBuiltinID()) { 11148 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 11149 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 11150 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 11151 FD->setInvalidDecl(); 11152 } 11153 } 11154 11155 // The return type of a function definition must be complete 11156 // (C99 6.9.1p3, C++ [dcl.fct]p6). 11157 QualType ResultType = FD->getReturnType(); 11158 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 11159 !FD->isInvalidDecl() && 11160 RequireCompleteType(FD->getLocation(), ResultType, 11161 diag::err_func_def_incomplete_result)) 11162 FD->setInvalidDecl(); 11163 11164 if (FnBodyScope) 11165 PushDeclContext(FnBodyScope, FD); 11166 11167 // Check the validity of our function parameters 11168 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 11169 /*CheckParameterNames=*/true); 11170 11171 // Introduce our parameters into the function scope 11172 for (auto Param : FD->params()) { 11173 Param->setOwningFunction(FD); 11174 11175 // If this has an identifier, add it to the scope stack. 11176 if (Param->getIdentifier() && FnBodyScope) { 11177 CheckShadow(FnBodyScope, Param); 11178 11179 PushOnScopeChains(Param, FnBodyScope); 11180 } 11181 } 11182 11183 // If we had any tags defined in the function prototype, 11184 // introduce them into the function scope. 11185 if (FnBodyScope) { 11186 for (ArrayRef<NamedDecl *>::iterator 11187 I = FD->getDeclsInPrototypeScope().begin(), 11188 E = FD->getDeclsInPrototypeScope().end(); 11189 I != E; ++I) { 11190 NamedDecl *D = *I; 11191 11192 // Some of these decls (like enums) may have been pinned to the 11193 // translation unit for lack of a real context earlier. If so, remove 11194 // from the translation unit and reattach to the current context. 11195 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 11196 // Is the decl actually in the context? 11197 if (Context.getTranslationUnitDecl()->containsDecl(D)) 11198 Context.getTranslationUnitDecl()->removeDecl(D); 11199 // Either way, reassign the lexical decl context to our FunctionDecl. 11200 D->setLexicalDeclContext(CurContext); 11201 } 11202 11203 // If the decl has a non-null name, make accessible in the current scope. 11204 if (!D->getName().empty()) 11205 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 11206 11207 // Similarly, dive into enums and fish their constants out, making them 11208 // accessible in this scope. 11209 if (auto *ED = dyn_cast<EnumDecl>(D)) { 11210 for (auto *EI : ED->enumerators()) 11211 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11212 } 11213 } 11214 } 11215 11216 // Ensure that the function's exception specification is instantiated. 11217 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11218 ResolveExceptionSpec(D->getLocation(), FPT); 11219 11220 // dllimport cannot be applied to non-inline function definitions. 11221 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11222 !FD->isTemplateInstantiation()) { 11223 assert(!FD->hasAttr<DLLExportAttr>()); 11224 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11225 FD->setInvalidDecl(); 11226 return D; 11227 } 11228 // We want to attach documentation to original Decl (which might be 11229 // a function template). 11230 ActOnDocumentableDecl(D); 11231 if (getCurLexicalContext()->isObjCContainer() && 11232 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11233 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11234 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11235 11236 return D; 11237 } 11238 11239 /// \brief Given the set of return statements within a function body, 11240 /// compute the variables that are subject to the named return value 11241 /// optimization. 11242 /// 11243 /// Each of the variables that is subject to the named return value 11244 /// optimization will be marked as NRVO variables in the AST, and any 11245 /// return statement that has a marked NRVO variable as its NRVO candidate can 11246 /// use the named return value optimization. 11247 /// 11248 /// This function applies a very simplistic algorithm for NRVO: if every return 11249 /// statement in the scope of a variable has the same NRVO candidate, that 11250 /// candidate is an NRVO variable. 11251 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11252 ReturnStmt **Returns = Scope->Returns.data(); 11253 11254 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11255 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11256 if (!NRVOCandidate->isNRVOVariable()) 11257 Returns[I]->setNRVOCandidate(nullptr); 11258 } 11259 } 11260 } 11261 11262 bool Sema::canDelayFunctionBody(const Declarator &D) { 11263 // We can't delay parsing the body of a constexpr function template (yet). 11264 if (D.getDeclSpec().isConstexprSpecified()) 11265 return false; 11266 11267 // We can't delay parsing the body of a function template with a deduced 11268 // return type (yet). 11269 if (D.getDeclSpec().containsPlaceholderType()) { 11270 // If the placeholder introduces a non-deduced trailing return type, 11271 // we can still delay parsing it. 11272 if (D.getNumTypeObjects()) { 11273 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11274 if (Outer.Kind == DeclaratorChunk::Function && 11275 Outer.Fun.hasTrailingReturnType()) { 11276 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11277 return Ty.isNull() || !Ty->isUndeducedType(); 11278 } 11279 } 11280 return false; 11281 } 11282 11283 return true; 11284 } 11285 11286 bool Sema::canSkipFunctionBody(Decl *D) { 11287 // We cannot skip the body of a function (or function template) which is 11288 // constexpr, since we may need to evaluate its body in order to parse the 11289 // rest of the file. 11290 // We cannot skip the body of a function with an undeduced return type, 11291 // because any callers of that function need to know the type. 11292 if (const FunctionDecl *FD = D->getAsFunction()) 11293 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11294 return false; 11295 return Consumer.shouldSkipFunctionBody(D); 11296 } 11297 11298 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11299 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11300 FD->setHasSkippedBody(); 11301 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11302 MD->setHasSkippedBody(); 11303 return ActOnFinishFunctionBody(Decl, nullptr); 11304 } 11305 11306 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11307 return ActOnFinishFunctionBody(D, BodyArg, false); 11308 } 11309 11310 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11311 bool IsInstantiation) { 11312 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11313 11314 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11315 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11316 11317 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty()) 11318 CheckCompletedCoroutineBody(FD, Body); 11319 11320 if (FD) { 11321 FD->setBody(Body); 11322 11323 if (getLangOpts().CPlusPlus14) { 11324 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 11325 FD->getReturnType()->isUndeducedType()) { 11326 // If the function has a deduced result type but contains no 'return' 11327 // statements, the result type as written must be exactly 'auto', and 11328 // the deduced result type is 'void'. 11329 if (!FD->getReturnType()->getAs<AutoType>()) { 11330 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 11331 << FD->getReturnType(); 11332 FD->setInvalidDecl(); 11333 } else { 11334 // Substitute 'void' for the 'auto' in the type. 11335 TypeLoc ResultType = getReturnTypeLoc(FD); 11336 Context.adjustDeducedFunctionResultType( 11337 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 11338 } 11339 } 11340 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11341 // In C++11, we don't use 'auto' deduction rules for lambda call 11342 // operators because we don't support return type deduction. 11343 auto *LSI = getCurLambda(); 11344 if (LSI->HasImplicitReturnType) { 11345 deduceClosureReturnType(*LSI); 11346 11347 // C++11 [expr.prim.lambda]p4: 11348 // [...] if there are no return statements in the compound-statement 11349 // [the deduced type is] the type void 11350 QualType RetType = 11351 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11352 11353 // Update the return type to the deduced type. 11354 const FunctionProtoType *Proto = 11355 FD->getType()->getAs<FunctionProtoType>(); 11356 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11357 Proto->getExtProtoInfo())); 11358 } 11359 } 11360 11361 // The only way to be included in UndefinedButUsed is if there is an 11362 // ODR use before the definition. Avoid the expensive map lookup if this 11363 // is the first declaration. 11364 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11365 if (!FD->isExternallyVisible()) 11366 UndefinedButUsed.erase(FD); 11367 else if (FD->isInlined() && 11368 !LangOpts.GNUInline && 11369 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11370 UndefinedButUsed.erase(FD); 11371 } 11372 11373 // If the function implicitly returns zero (like 'main') or is naked, 11374 // don't complain about missing return statements. 11375 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11376 WP.disableCheckFallThrough(); 11377 11378 // MSVC permits the use of pure specifier (=0) on function definition, 11379 // defined at class scope, warn about this non-standard construct. 11380 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11381 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11382 11383 if (!FD->isInvalidDecl()) { 11384 // Don't diagnose unused parameters of defaulted or deleted functions. 11385 if (!FD->isDeleted() && !FD->isDefaulted()) 11386 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 11387 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 11388 FD->getReturnType(), FD); 11389 11390 // If this is a structor, we need a vtable. 11391 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11392 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11393 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 11394 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 11395 11396 // Try to apply the named return value optimization. We have to check 11397 // if we can do this here because lambdas keep return statements around 11398 // to deduce an implicit return type. 11399 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 11400 !FD->isDependentContext()) 11401 computeNRVO(Body, getCurFunction()); 11402 } 11403 11404 // GNU warning -Wmissing-prototypes: 11405 // Warn if a global function is defined without a previous 11406 // prototype declaration. This warning is issued even if the 11407 // definition itself provides a prototype. The aim is to detect 11408 // global functions that fail to be declared in header files. 11409 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 11410 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 11411 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 11412 11413 if (PossibleZeroParamPrototype) { 11414 // We found a declaration that is not a prototype, 11415 // but that could be a zero-parameter prototype 11416 if (TypeSourceInfo *TI = 11417 PossibleZeroParamPrototype->getTypeSourceInfo()) { 11418 TypeLoc TL = TI->getTypeLoc(); 11419 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 11420 Diag(PossibleZeroParamPrototype->getLocation(), 11421 diag::note_declaration_not_a_prototype) 11422 << PossibleZeroParamPrototype 11423 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 11424 } 11425 } 11426 } 11427 11428 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11429 const CXXMethodDecl *KeyFunction; 11430 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 11431 MD->isVirtual() && 11432 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 11433 MD == KeyFunction->getCanonicalDecl()) { 11434 // Update the key-function state if necessary for this ABI. 11435 if (FD->isInlined() && 11436 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11437 Context.setNonKeyFunction(MD); 11438 11439 // If the newly-chosen key function is already defined, then we 11440 // need to mark the vtable as used retroactively. 11441 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 11442 const FunctionDecl *Definition; 11443 if (KeyFunction && KeyFunction->isDefined(Definition)) 11444 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 11445 } else { 11446 // We just defined they key function; mark the vtable as used. 11447 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 11448 } 11449 } 11450 } 11451 11452 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 11453 "Function parsing confused"); 11454 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 11455 assert(MD == getCurMethodDecl() && "Method parsing confused"); 11456 MD->setBody(Body); 11457 if (!MD->isInvalidDecl()) { 11458 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 11459 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 11460 MD->getReturnType(), MD); 11461 11462 if (Body) 11463 computeNRVO(Body, getCurFunction()); 11464 } 11465 if (getCurFunction()->ObjCShouldCallSuper) { 11466 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 11467 << MD->getSelector().getAsString(); 11468 getCurFunction()->ObjCShouldCallSuper = false; 11469 } 11470 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 11471 const ObjCMethodDecl *InitMethod = nullptr; 11472 bool isDesignated = 11473 MD->isDesignatedInitializerForTheInterface(&InitMethod); 11474 assert(isDesignated && InitMethod); 11475 (void)isDesignated; 11476 11477 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 11478 auto IFace = MD->getClassInterface(); 11479 if (!IFace) 11480 return false; 11481 auto SuperD = IFace->getSuperClass(); 11482 if (!SuperD) 11483 return false; 11484 return SuperD->getIdentifier() == 11485 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 11486 }; 11487 // Don't issue this warning for unavailable inits or direct subclasses 11488 // of NSObject. 11489 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 11490 Diag(MD->getLocation(), 11491 diag::warn_objc_designated_init_missing_super_call); 11492 Diag(InitMethod->getLocation(), 11493 diag::note_objc_designated_init_marked_here); 11494 } 11495 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 11496 } 11497 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 11498 // Don't issue this warning for unavaialable inits. 11499 if (!MD->isUnavailable()) 11500 Diag(MD->getLocation(), 11501 diag::warn_objc_secondary_init_missing_init_call); 11502 getCurFunction()->ObjCWarnForNoInitDelegation = false; 11503 } 11504 } else { 11505 return nullptr; 11506 } 11507 11508 assert(!getCurFunction()->ObjCShouldCallSuper && 11509 "This should only be set for ObjC methods, which should have been " 11510 "handled in the block above."); 11511 11512 // Verify and clean out per-function state. 11513 if (Body && (!FD || !FD->isDefaulted())) { 11514 // C++ constructors that have function-try-blocks can't have return 11515 // statements in the handlers of that block. (C++ [except.handle]p14) 11516 // Verify this. 11517 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 11518 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 11519 11520 // Verify that gotos and switch cases don't jump into scopes illegally. 11521 if (getCurFunction()->NeedsScopeChecking() && 11522 !PP.isCodeCompletionEnabled()) 11523 DiagnoseInvalidJumps(Body); 11524 11525 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 11526 if (!Destructor->getParent()->isDependentType()) 11527 CheckDestructor(Destructor); 11528 11529 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11530 Destructor->getParent()); 11531 } 11532 11533 // If any errors have occurred, clear out any temporaries that may have 11534 // been leftover. This ensures that these temporaries won't be picked up for 11535 // deletion in some later function. 11536 if (getDiagnostics().hasErrorOccurred() || 11537 getDiagnostics().getSuppressAllDiagnostics()) { 11538 DiscardCleanupsInEvaluationContext(); 11539 } 11540 if (!getDiagnostics().hasUncompilableErrorOccurred() && 11541 !isa<FunctionTemplateDecl>(dcl)) { 11542 // Since the body is valid, issue any analysis-based warnings that are 11543 // enabled. 11544 ActivePolicy = &WP; 11545 } 11546 11547 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 11548 (!CheckConstexprFunctionDecl(FD) || 11549 !CheckConstexprFunctionBody(FD, Body))) 11550 FD->setInvalidDecl(); 11551 11552 if (FD && FD->hasAttr<NakedAttr>()) { 11553 for (const Stmt *S : Body->children()) { 11554 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 11555 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 11556 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 11557 FD->setInvalidDecl(); 11558 break; 11559 } 11560 } 11561 } 11562 11563 assert(ExprCleanupObjects.size() == 11564 ExprEvalContexts.back().NumCleanupObjects && 11565 "Leftover temporaries in function"); 11566 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 11567 assert(MaybeODRUseExprs.empty() && 11568 "Leftover expressions for odr-use checking"); 11569 } 11570 11571 if (!IsInstantiation) 11572 PopDeclContext(); 11573 11574 PopFunctionScopeInfo(ActivePolicy, dcl); 11575 // If any errors have occurred, clear out any temporaries that may have 11576 // been leftover. This ensures that these temporaries won't be picked up for 11577 // deletion in some later function. 11578 if (getDiagnostics().hasErrorOccurred()) { 11579 DiscardCleanupsInEvaluationContext(); 11580 } 11581 11582 return dcl; 11583 } 11584 11585 /// When we finish delayed parsing of an attribute, we must attach it to the 11586 /// relevant Decl. 11587 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 11588 ParsedAttributes &Attrs) { 11589 // Always attach attributes to the underlying decl. 11590 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 11591 D = TD->getTemplatedDecl(); 11592 ProcessDeclAttributeList(S, D, Attrs.getList()); 11593 11594 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 11595 if (Method->isStatic()) 11596 checkThisInStaticMemberFunctionAttributes(Method); 11597 } 11598 11599 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 11600 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 11601 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 11602 IdentifierInfo &II, Scope *S) { 11603 // Before we produce a declaration for an implicitly defined 11604 // function, see whether there was a locally-scoped declaration of 11605 // this name as a function or variable. If so, use that 11606 // (non-visible) declaration, and complain about it. 11607 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 11608 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 11609 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 11610 return ExternCPrev; 11611 } 11612 11613 // Extension in C99. Legal in C90, but warn about it. 11614 unsigned diag_id; 11615 if (II.getName().startswith("__builtin_")) 11616 diag_id = diag::warn_builtin_unknown; 11617 else if (getLangOpts().C99) 11618 diag_id = diag::ext_implicit_function_decl; 11619 else 11620 diag_id = diag::warn_implicit_function_decl; 11621 Diag(Loc, diag_id) << &II; 11622 11623 // Because typo correction is expensive, only do it if the implicit 11624 // function declaration is going to be treated as an error. 11625 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 11626 TypoCorrection Corrected; 11627 if (S && 11628 (Corrected = CorrectTypo( 11629 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 11630 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 11631 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 11632 /*ErrorRecovery*/false); 11633 } 11634 11635 // Set a Declarator for the implicit definition: int foo(); 11636 const char *Dummy; 11637 AttributeFactory attrFactory; 11638 DeclSpec DS(attrFactory); 11639 unsigned DiagID; 11640 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 11641 Context.getPrintingPolicy()); 11642 (void)Error; // Silence warning. 11643 assert(!Error && "Error setting up implicit decl!"); 11644 SourceLocation NoLoc; 11645 Declarator D(DS, Declarator::BlockContext); 11646 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 11647 /*IsAmbiguous=*/false, 11648 /*LParenLoc=*/NoLoc, 11649 /*Params=*/nullptr, 11650 /*NumParams=*/0, 11651 /*EllipsisLoc=*/NoLoc, 11652 /*RParenLoc=*/NoLoc, 11653 /*TypeQuals=*/0, 11654 /*RefQualifierIsLvalueRef=*/true, 11655 /*RefQualifierLoc=*/NoLoc, 11656 /*ConstQualifierLoc=*/NoLoc, 11657 /*VolatileQualifierLoc=*/NoLoc, 11658 /*RestrictQualifierLoc=*/NoLoc, 11659 /*MutableLoc=*/NoLoc, 11660 EST_None, 11661 /*ESpecRange=*/SourceRange(), 11662 /*Exceptions=*/nullptr, 11663 /*ExceptionRanges=*/nullptr, 11664 /*NumExceptions=*/0, 11665 /*NoexceptExpr=*/nullptr, 11666 /*ExceptionSpecTokens=*/nullptr, 11667 Loc, Loc, D), 11668 DS.getAttributes(), 11669 SourceLocation()); 11670 D.SetIdentifier(&II, Loc); 11671 11672 // Insert this function into translation-unit scope. 11673 11674 DeclContext *PrevDC = CurContext; 11675 CurContext = Context.getTranslationUnitDecl(); 11676 11677 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 11678 FD->setImplicit(); 11679 11680 CurContext = PrevDC; 11681 11682 AddKnownFunctionAttributes(FD); 11683 11684 return FD; 11685 } 11686 11687 /// \brief Adds any function attributes that we know a priori based on 11688 /// the declaration of this function. 11689 /// 11690 /// These attributes can apply both to implicitly-declared builtins 11691 /// (like __builtin___printf_chk) or to library-declared functions 11692 /// like NSLog or printf. 11693 /// 11694 /// We need to check for duplicate attributes both here and where user-written 11695 /// attributes are applied to declarations. 11696 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 11697 if (FD->isInvalidDecl()) 11698 return; 11699 11700 // If this is a built-in function, map its builtin attributes to 11701 // actual attributes. 11702 if (unsigned BuiltinID = FD->getBuiltinID()) { 11703 // Handle printf-formatting attributes. 11704 unsigned FormatIdx; 11705 bool HasVAListArg; 11706 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 11707 if (!FD->hasAttr<FormatAttr>()) { 11708 const char *fmt = "printf"; 11709 unsigned int NumParams = FD->getNumParams(); 11710 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 11711 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 11712 fmt = "NSString"; 11713 FD->addAttr(FormatAttr::CreateImplicit(Context, 11714 &Context.Idents.get(fmt), 11715 FormatIdx+1, 11716 HasVAListArg ? 0 : FormatIdx+2, 11717 FD->getLocation())); 11718 } 11719 } 11720 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 11721 HasVAListArg)) { 11722 if (!FD->hasAttr<FormatAttr>()) 11723 FD->addAttr(FormatAttr::CreateImplicit(Context, 11724 &Context.Idents.get("scanf"), 11725 FormatIdx+1, 11726 HasVAListArg ? 0 : FormatIdx+2, 11727 FD->getLocation())); 11728 } 11729 11730 // Mark const if we don't care about errno and that is the only 11731 // thing preventing the function from being const. This allows 11732 // IRgen to use LLVM intrinsics for such functions. 11733 if (!getLangOpts().MathErrno && 11734 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 11735 if (!FD->hasAttr<ConstAttr>()) 11736 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11737 } 11738 11739 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 11740 !FD->hasAttr<ReturnsTwiceAttr>()) 11741 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 11742 FD->getLocation())); 11743 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 11744 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 11745 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 11746 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 11747 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 11748 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11749 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 11750 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 11751 // Add the appropriate attribute, depending on the CUDA compilation mode 11752 // and which target the builtin belongs to. For example, during host 11753 // compilation, aux builtins are __device__, while the rest are __host__. 11754 if (getLangOpts().CUDAIsDevice != 11755 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 11756 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 11757 else 11758 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 11759 } 11760 } 11761 11762 // If C++ exceptions are enabled but we are told extern "C" functions cannot 11763 // throw, add an implicit nothrow attribute to any extern "C" function we come 11764 // across. 11765 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 11766 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 11767 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 11768 if (!FPT || FPT->getExceptionSpecType() == EST_None) 11769 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 11770 } 11771 11772 IdentifierInfo *Name = FD->getIdentifier(); 11773 if (!Name) 11774 return; 11775 if ((!getLangOpts().CPlusPlus && 11776 FD->getDeclContext()->isTranslationUnit()) || 11777 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 11778 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 11779 LinkageSpecDecl::lang_c)) { 11780 // Okay: this could be a libc/libm/Objective-C function we know 11781 // about. 11782 } else 11783 return; 11784 11785 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 11786 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 11787 // target-specific builtins, perhaps? 11788 if (!FD->hasAttr<FormatAttr>()) 11789 FD->addAttr(FormatAttr::CreateImplicit(Context, 11790 &Context.Idents.get("printf"), 2, 11791 Name->isStr("vasprintf") ? 0 : 3, 11792 FD->getLocation())); 11793 } 11794 11795 if (Name->isStr("__CFStringMakeConstantString")) { 11796 // We already have a __builtin___CFStringMakeConstantString, 11797 // but builds that use -fno-constant-cfstrings don't go through that. 11798 if (!FD->hasAttr<FormatArgAttr>()) 11799 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 11800 FD->getLocation())); 11801 } 11802 } 11803 11804 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 11805 TypeSourceInfo *TInfo) { 11806 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 11807 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 11808 11809 if (!TInfo) { 11810 assert(D.isInvalidType() && "no declarator info for valid type"); 11811 TInfo = Context.getTrivialTypeSourceInfo(T); 11812 } 11813 11814 // Scope manipulation handled by caller. 11815 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 11816 D.getLocStart(), 11817 D.getIdentifierLoc(), 11818 D.getIdentifier(), 11819 TInfo); 11820 11821 // Bail out immediately if we have an invalid declaration. 11822 if (D.isInvalidType()) { 11823 NewTD->setInvalidDecl(); 11824 return NewTD; 11825 } 11826 11827 if (D.getDeclSpec().isModulePrivateSpecified()) { 11828 if (CurContext->isFunctionOrMethod()) 11829 Diag(NewTD->getLocation(), diag::err_module_private_local) 11830 << 2 << NewTD->getDeclName() 11831 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11832 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11833 else 11834 NewTD->setModulePrivate(); 11835 } 11836 11837 // C++ [dcl.typedef]p8: 11838 // If the typedef declaration defines an unnamed class (or 11839 // enum), the first typedef-name declared by the declaration 11840 // to be that class type (or enum type) is used to denote the 11841 // class type (or enum type) for linkage purposes only. 11842 // We need to check whether the type was declared in the declaration. 11843 switch (D.getDeclSpec().getTypeSpecType()) { 11844 case TST_enum: 11845 case TST_struct: 11846 case TST_interface: 11847 case TST_union: 11848 case TST_class: { 11849 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 11850 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 11851 break; 11852 } 11853 11854 default: 11855 break; 11856 } 11857 11858 return NewTD; 11859 } 11860 11861 /// \brief Check that this is a valid underlying type for an enum declaration. 11862 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 11863 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 11864 QualType T = TI->getType(); 11865 11866 if (T->isDependentType()) 11867 return false; 11868 11869 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 11870 if (BT->isInteger()) 11871 return false; 11872 11873 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 11874 return true; 11875 } 11876 11877 /// Check whether this is a valid redeclaration of a previous enumeration. 11878 /// \return true if the redeclaration was invalid. 11879 bool Sema::CheckEnumRedeclaration( 11880 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 11881 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 11882 bool IsFixed = !EnumUnderlyingTy.isNull(); 11883 11884 if (IsScoped != Prev->isScoped()) { 11885 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 11886 << Prev->isScoped(); 11887 Diag(Prev->getLocation(), diag::note_previous_declaration); 11888 return true; 11889 } 11890 11891 if (IsFixed && Prev->isFixed()) { 11892 if (!EnumUnderlyingTy->isDependentType() && 11893 !Prev->getIntegerType()->isDependentType() && 11894 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 11895 Prev->getIntegerType())) { 11896 // TODO: Highlight the underlying type of the redeclaration. 11897 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 11898 << EnumUnderlyingTy << Prev->getIntegerType(); 11899 Diag(Prev->getLocation(), diag::note_previous_declaration) 11900 << Prev->getIntegerTypeRange(); 11901 return true; 11902 } 11903 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 11904 ; 11905 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 11906 ; 11907 } else if (IsFixed != Prev->isFixed()) { 11908 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 11909 << Prev->isFixed(); 11910 Diag(Prev->getLocation(), diag::note_previous_declaration); 11911 return true; 11912 } 11913 11914 return false; 11915 } 11916 11917 /// \brief Get diagnostic %select index for tag kind for 11918 /// redeclaration diagnostic message. 11919 /// WARNING: Indexes apply to particular diagnostics only! 11920 /// 11921 /// \returns diagnostic %select index. 11922 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 11923 switch (Tag) { 11924 case TTK_Struct: return 0; 11925 case TTK_Interface: return 1; 11926 case TTK_Class: return 2; 11927 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 11928 } 11929 } 11930 11931 /// \brief Determine if tag kind is a class-key compatible with 11932 /// class for redeclaration (class, struct, or __interface). 11933 /// 11934 /// \returns true iff the tag kind is compatible. 11935 static bool isClassCompatTagKind(TagTypeKind Tag) 11936 { 11937 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 11938 } 11939 11940 /// \brief Determine whether a tag with a given kind is acceptable 11941 /// as a redeclaration of the given tag declaration. 11942 /// 11943 /// \returns true if the new tag kind is acceptable, false otherwise. 11944 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 11945 TagTypeKind NewTag, bool isDefinition, 11946 SourceLocation NewTagLoc, 11947 const IdentifierInfo *Name) { 11948 // C++ [dcl.type.elab]p3: 11949 // The class-key or enum keyword present in the 11950 // elaborated-type-specifier shall agree in kind with the 11951 // declaration to which the name in the elaborated-type-specifier 11952 // refers. This rule also applies to the form of 11953 // elaborated-type-specifier that declares a class-name or 11954 // friend class since it can be construed as referring to the 11955 // definition of the class. Thus, in any 11956 // elaborated-type-specifier, the enum keyword shall be used to 11957 // refer to an enumeration (7.2), the union class-key shall be 11958 // used to refer to a union (clause 9), and either the class or 11959 // struct class-key shall be used to refer to a class (clause 9) 11960 // declared using the class or struct class-key. 11961 TagTypeKind OldTag = Previous->getTagKind(); 11962 if (!isDefinition || !isClassCompatTagKind(NewTag)) 11963 if (OldTag == NewTag) 11964 return true; 11965 11966 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 11967 // Warn about the struct/class tag mismatch. 11968 bool isTemplate = false; 11969 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 11970 isTemplate = Record->getDescribedClassTemplate(); 11971 11972 if (!ActiveTemplateInstantiations.empty()) { 11973 // In a template instantiation, do not offer fix-its for tag mismatches 11974 // since they usually mess up the template instead of fixing the problem. 11975 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11976 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 11977 << getRedeclDiagFromTagKind(OldTag); 11978 return true; 11979 } 11980 11981 if (isDefinition) { 11982 // On definitions, check previous tags and issue a fix-it for each 11983 // one that doesn't match the current tag. 11984 if (Previous->getDefinition()) { 11985 // Don't suggest fix-its for redefinitions. 11986 return true; 11987 } 11988 11989 bool previousMismatch = false; 11990 for (auto I : Previous->redecls()) { 11991 if (I->getTagKind() != NewTag) { 11992 if (!previousMismatch) { 11993 previousMismatch = true; 11994 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11995 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 11996 << getRedeclDiagFromTagKind(I->getTagKind()); 11997 } 11998 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11999 << getRedeclDiagFromTagKind(NewTag) 12000 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12001 TypeWithKeyword::getTagTypeKindName(NewTag)); 12002 } 12003 } 12004 return true; 12005 } 12006 12007 // Check for a previous definition. If current tag and definition 12008 // are same type, do nothing. If no definition, but disagree with 12009 // with previous tag type, give a warning, but no fix-it. 12010 const TagDecl *Redecl = Previous->getDefinition() ? 12011 Previous->getDefinition() : Previous; 12012 if (Redecl->getTagKind() == NewTag) { 12013 return true; 12014 } 12015 12016 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12017 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12018 << getRedeclDiagFromTagKind(OldTag); 12019 Diag(Redecl->getLocation(), diag::note_previous_use); 12020 12021 // If there is a previous definition, suggest a fix-it. 12022 if (Previous->getDefinition()) { 12023 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12024 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12025 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12026 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12027 } 12028 12029 return true; 12030 } 12031 return false; 12032 } 12033 12034 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12035 /// from an outer enclosing namespace or file scope inside a friend declaration. 12036 /// This should provide the commented out code in the following snippet: 12037 /// namespace N { 12038 /// struct X; 12039 /// namespace M { 12040 /// struct Y { friend struct /*N::*/ X; }; 12041 /// } 12042 /// } 12043 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12044 SourceLocation NameLoc) { 12045 // While the decl is in a namespace, do repeated lookup of that name and see 12046 // if we get the same namespace back. If we do not, continue until 12047 // translation unit scope, at which point we have a fully qualified NNS. 12048 SmallVector<IdentifierInfo *, 4> Namespaces; 12049 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12050 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12051 // This tag should be declared in a namespace, which can only be enclosed by 12052 // other namespaces. Bail if there's an anonymous namespace in the chain. 12053 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12054 if (!Namespace || Namespace->isAnonymousNamespace()) 12055 return FixItHint(); 12056 IdentifierInfo *II = Namespace->getIdentifier(); 12057 Namespaces.push_back(II); 12058 NamedDecl *Lookup = SemaRef.LookupSingleName( 12059 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12060 if (Lookup == Namespace) 12061 break; 12062 } 12063 12064 // Once we have all the namespaces, reverse them to go outermost first, and 12065 // build an NNS. 12066 SmallString<64> Insertion; 12067 llvm::raw_svector_ostream OS(Insertion); 12068 if (DC->isTranslationUnit()) 12069 OS << "::"; 12070 std::reverse(Namespaces.begin(), Namespaces.end()); 12071 for (auto *II : Namespaces) 12072 OS << II->getName() << "::"; 12073 return FixItHint::CreateInsertion(NameLoc, Insertion); 12074 } 12075 12076 /// \brief Determine whether a tag originally declared in context \p OldDC can 12077 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12078 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12079 /// using-declaration). 12080 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12081 DeclContext *NewDC) { 12082 OldDC = OldDC->getRedeclContext(); 12083 NewDC = NewDC->getRedeclContext(); 12084 12085 if (OldDC->Equals(NewDC)) 12086 return true; 12087 12088 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12089 // encloses the other). 12090 if (S.getLangOpts().MSVCCompat && 12091 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 12092 return true; 12093 12094 return false; 12095 } 12096 12097 /// Find the DeclContext in which a tag is implicitly declared if we see an 12098 /// elaborated type specifier in the specified context, and lookup finds 12099 /// nothing. 12100 static DeclContext *getTagInjectionContext(DeclContext *DC) { 12101 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 12102 DC = DC->getParent(); 12103 return DC; 12104 } 12105 12106 /// Find the Scope in which a tag is implicitly declared if we see an 12107 /// elaborated type specifier in the specified context, and lookup finds 12108 /// nothing. 12109 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 12110 while (S->isClassScope() || 12111 (LangOpts.CPlusPlus && 12112 S->isFunctionPrototypeScope()) || 12113 ((S->getFlags() & Scope::DeclScope) == 0) || 12114 (S->getEntity() && S->getEntity()->isTransparentContext())) 12115 S = S->getParent(); 12116 return S; 12117 } 12118 12119 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 12120 /// former case, Name will be non-null. In the later case, Name will be null. 12121 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 12122 /// reference/declaration/definition of a tag. 12123 /// 12124 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 12125 /// trailing-type-specifier) other than one in an alias-declaration. 12126 /// 12127 /// \param SkipBody If non-null, will be set to indicate if the caller should 12128 /// skip the definition of this tag and treat it as if it were a declaration. 12129 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12130 SourceLocation KWLoc, CXXScopeSpec &SS, 12131 IdentifierInfo *Name, SourceLocation NameLoc, 12132 AttributeList *Attr, AccessSpecifier AS, 12133 SourceLocation ModulePrivateLoc, 12134 MultiTemplateParamsArg TemplateParameterLists, 12135 bool &OwnedDecl, bool &IsDependent, 12136 SourceLocation ScopedEnumKWLoc, 12137 bool ScopedEnumUsesClassTag, 12138 TypeResult UnderlyingType, 12139 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 12140 // If this is not a definition, it must have a name. 12141 IdentifierInfo *OrigName = Name; 12142 assert((Name != nullptr || TUK == TUK_Definition) && 12143 "Nameless record must be a definition!"); 12144 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 12145 12146 OwnedDecl = false; 12147 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12148 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 12149 12150 // FIXME: Check explicit specializations more carefully. 12151 bool isExplicitSpecialization = false; 12152 bool Invalid = false; 12153 12154 // We only need to do this matching if we have template parameters 12155 // or a scope specifier, which also conveniently avoids this work 12156 // for non-C++ cases. 12157 if (TemplateParameterLists.size() > 0 || 12158 (SS.isNotEmpty() && TUK != TUK_Reference)) { 12159 if (TemplateParameterList *TemplateParams = 12160 MatchTemplateParametersToScopeSpecifier( 12161 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 12162 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 12163 if (Kind == TTK_Enum) { 12164 Diag(KWLoc, diag::err_enum_template); 12165 return nullptr; 12166 } 12167 12168 if (TemplateParams->size() > 0) { 12169 // This is a declaration or definition of a class template (which may 12170 // be a member of another template). 12171 12172 if (Invalid) 12173 return nullptr; 12174 12175 OwnedDecl = false; 12176 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 12177 SS, Name, NameLoc, Attr, 12178 TemplateParams, AS, 12179 ModulePrivateLoc, 12180 /*FriendLoc*/SourceLocation(), 12181 TemplateParameterLists.size()-1, 12182 TemplateParameterLists.data(), 12183 SkipBody); 12184 return Result.get(); 12185 } else { 12186 // The "template<>" header is extraneous. 12187 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12188 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12189 isExplicitSpecialization = true; 12190 } 12191 } 12192 } 12193 12194 // Figure out the underlying type if this a enum declaration. We need to do 12195 // this early, because it's needed to detect if this is an incompatible 12196 // redeclaration. 12197 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12198 bool EnumUnderlyingIsImplicit = false; 12199 12200 if (Kind == TTK_Enum) { 12201 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12202 // No underlying type explicitly specified, or we failed to parse the 12203 // type, default to int. 12204 EnumUnderlying = Context.IntTy.getTypePtr(); 12205 else if (UnderlyingType.get()) { 12206 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12207 // integral type; any cv-qualification is ignored. 12208 TypeSourceInfo *TI = nullptr; 12209 GetTypeFromParser(UnderlyingType.get(), &TI); 12210 EnumUnderlying = TI; 12211 12212 if (CheckEnumUnderlyingType(TI)) 12213 // Recover by falling back to int. 12214 EnumUnderlying = Context.IntTy.getTypePtr(); 12215 12216 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12217 UPPC_FixedUnderlyingType)) 12218 EnumUnderlying = Context.IntTy.getTypePtr(); 12219 12220 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12221 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12222 // Microsoft enums are always of int type. 12223 EnumUnderlying = Context.IntTy.getTypePtr(); 12224 EnumUnderlyingIsImplicit = true; 12225 } 12226 } 12227 } 12228 12229 DeclContext *SearchDC = CurContext; 12230 DeclContext *DC = CurContext; 12231 bool isStdBadAlloc = false; 12232 12233 RedeclarationKind Redecl = ForRedeclaration; 12234 if (TUK == TUK_Friend || TUK == TUK_Reference) 12235 Redecl = NotForRedeclaration; 12236 12237 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12238 if (Name && SS.isNotEmpty()) { 12239 // We have a nested-name tag ('struct foo::bar'). 12240 12241 // Check for invalid 'foo::'. 12242 if (SS.isInvalid()) { 12243 Name = nullptr; 12244 goto CreateNewDecl; 12245 } 12246 12247 // If this is a friend or a reference to a class in a dependent 12248 // context, don't try to make a decl for it. 12249 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12250 DC = computeDeclContext(SS, false); 12251 if (!DC) { 12252 IsDependent = true; 12253 return nullptr; 12254 } 12255 } else { 12256 DC = computeDeclContext(SS, true); 12257 if (!DC) { 12258 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12259 << SS.getRange(); 12260 return nullptr; 12261 } 12262 } 12263 12264 if (RequireCompleteDeclContext(SS, DC)) 12265 return nullptr; 12266 12267 SearchDC = DC; 12268 // Look-up name inside 'foo::'. 12269 LookupQualifiedName(Previous, DC); 12270 12271 if (Previous.isAmbiguous()) 12272 return nullptr; 12273 12274 if (Previous.empty()) { 12275 // Name lookup did not find anything. However, if the 12276 // nested-name-specifier refers to the current instantiation, 12277 // and that current instantiation has any dependent base 12278 // classes, we might find something at instantiation time: treat 12279 // this as a dependent elaborated-type-specifier. 12280 // But this only makes any sense for reference-like lookups. 12281 if (Previous.wasNotFoundInCurrentInstantiation() && 12282 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12283 IsDependent = true; 12284 return nullptr; 12285 } 12286 12287 // A tag 'foo::bar' must already exist. 12288 Diag(NameLoc, diag::err_not_tag_in_scope) 12289 << Kind << Name << DC << SS.getRange(); 12290 Name = nullptr; 12291 Invalid = true; 12292 goto CreateNewDecl; 12293 } 12294 } else if (Name) { 12295 // C++14 [class.mem]p14: 12296 // If T is the name of a class, then each of the following shall have a 12297 // name different from T: 12298 // -- every member of class T that is itself a type 12299 if (TUK != TUK_Reference && TUK != TUK_Friend && 12300 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 12301 return nullptr; 12302 12303 // If this is a named struct, check to see if there was a previous forward 12304 // declaration or definition. 12305 // FIXME: We're looking into outer scopes here, even when we 12306 // shouldn't be. Doing so can result in ambiguities that we 12307 // shouldn't be diagnosing. 12308 LookupName(Previous, S); 12309 12310 // When declaring or defining a tag, ignore ambiguities introduced 12311 // by types using'ed into this scope. 12312 if (Previous.isAmbiguous() && 12313 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 12314 LookupResult::Filter F = Previous.makeFilter(); 12315 while (F.hasNext()) { 12316 NamedDecl *ND = F.next(); 12317 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 12318 F.erase(); 12319 } 12320 F.done(); 12321 } 12322 12323 // C++11 [namespace.memdef]p3: 12324 // If the name in a friend declaration is neither qualified nor 12325 // a template-id and the declaration is a function or an 12326 // elaborated-type-specifier, the lookup to determine whether 12327 // the entity has been previously declared shall not consider 12328 // any scopes outside the innermost enclosing namespace. 12329 // 12330 // MSVC doesn't implement the above rule for types, so a friend tag 12331 // declaration may be a redeclaration of a type declared in an enclosing 12332 // scope. They do implement this rule for friend functions. 12333 // 12334 // Does it matter that this should be by scope instead of by 12335 // semantic context? 12336 if (!Previous.empty() && TUK == TUK_Friend) { 12337 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 12338 LookupResult::Filter F = Previous.makeFilter(); 12339 bool FriendSawTagOutsideEnclosingNamespace = false; 12340 while (F.hasNext()) { 12341 NamedDecl *ND = F.next(); 12342 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12343 if (DC->isFileContext() && 12344 !EnclosingNS->Encloses(ND->getDeclContext())) { 12345 if (getLangOpts().MSVCCompat) 12346 FriendSawTagOutsideEnclosingNamespace = true; 12347 else 12348 F.erase(); 12349 } 12350 } 12351 F.done(); 12352 12353 // Diagnose this MSVC extension in the easy case where lookup would have 12354 // unambiguously found something outside the enclosing namespace. 12355 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 12356 NamedDecl *ND = Previous.getFoundDecl(); 12357 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 12358 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 12359 } 12360 } 12361 12362 // Note: there used to be some attempt at recovery here. 12363 if (Previous.isAmbiguous()) 12364 return nullptr; 12365 12366 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 12367 // FIXME: This makes sure that we ignore the contexts associated 12368 // with C structs, unions, and enums when looking for a matching 12369 // tag declaration or definition. See the similar lookup tweak 12370 // in Sema::LookupName; is there a better way to deal with this? 12371 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 12372 SearchDC = SearchDC->getParent(); 12373 } 12374 } 12375 12376 if (Previous.isSingleResult() && 12377 Previous.getFoundDecl()->isTemplateParameter()) { 12378 // Maybe we will complain about the shadowed template parameter. 12379 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 12380 // Just pretend that we didn't see the previous declaration. 12381 Previous.clear(); 12382 } 12383 12384 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 12385 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 12386 // This is a declaration of or a reference to "std::bad_alloc". 12387 isStdBadAlloc = true; 12388 12389 if (Previous.empty() && StdBadAlloc) { 12390 // std::bad_alloc has been implicitly declared (but made invisible to 12391 // name lookup). Fill in this implicit declaration as the previous 12392 // declaration, so that the declarations get chained appropriately. 12393 Previous.addDecl(getStdBadAlloc()); 12394 } 12395 } 12396 12397 // If we didn't find a previous declaration, and this is a reference 12398 // (or friend reference), move to the correct scope. In C++, we 12399 // also need to do a redeclaration lookup there, just in case 12400 // there's a shadow friend decl. 12401 if (Name && Previous.empty() && 12402 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12403 if (Invalid) goto CreateNewDecl; 12404 assert(SS.isEmpty()); 12405 12406 if (TUK == TUK_Reference) { 12407 // C++ [basic.scope.pdecl]p5: 12408 // -- for an elaborated-type-specifier of the form 12409 // 12410 // class-key identifier 12411 // 12412 // if the elaborated-type-specifier is used in the 12413 // decl-specifier-seq or parameter-declaration-clause of a 12414 // function defined in namespace scope, the identifier is 12415 // declared as a class-name in the namespace that contains 12416 // the declaration; otherwise, except as a friend 12417 // declaration, the identifier is declared in the smallest 12418 // non-class, non-function-prototype scope that contains the 12419 // declaration. 12420 // 12421 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 12422 // C structs and unions. 12423 // 12424 // It is an error in C++ to declare (rather than define) an enum 12425 // type, including via an elaborated type specifier. We'll 12426 // diagnose that later; for now, declare the enum in the same 12427 // scope as we would have picked for any other tag type. 12428 // 12429 // GNU C also supports this behavior as part of its incomplete 12430 // enum types extension, while GNU C++ does not. 12431 // 12432 // Find the context where we'll be declaring the tag. 12433 // FIXME: We would like to maintain the current DeclContext as the 12434 // lexical context, 12435 SearchDC = getTagInjectionContext(SearchDC); 12436 12437 // Find the scope where we'll be declaring the tag. 12438 S = getTagInjectionScope(S, getLangOpts()); 12439 } else { 12440 assert(TUK == TUK_Friend); 12441 // C++ [namespace.memdef]p3: 12442 // If a friend declaration in a non-local class first declares a 12443 // class or function, the friend class or function is a member of 12444 // the innermost enclosing namespace. 12445 SearchDC = SearchDC->getEnclosingNamespaceContext(); 12446 } 12447 12448 // In C++, we need to do a redeclaration lookup to properly 12449 // diagnose some problems. 12450 // FIXME: redeclaration lookup is also used (with and without C++) to find a 12451 // hidden declaration so that we don't get ambiguity errors when using a 12452 // type declared by an elaborated-type-specifier. In C that is not correct 12453 // and we should instead merge compatible types found by lookup. 12454 if (getLangOpts().CPlusPlus) { 12455 Previous.setRedeclarationKind(ForRedeclaration); 12456 LookupQualifiedName(Previous, SearchDC); 12457 } else { 12458 Previous.setRedeclarationKind(ForRedeclaration); 12459 LookupName(Previous, S); 12460 } 12461 } 12462 12463 // If we have a known previous declaration to use, then use it. 12464 if (Previous.empty() && SkipBody && SkipBody->Previous) 12465 Previous.addDecl(SkipBody->Previous); 12466 12467 if (!Previous.empty()) { 12468 NamedDecl *PrevDecl = Previous.getFoundDecl(); 12469 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 12470 12471 // It's okay to have a tag decl in the same scope as a typedef 12472 // which hides a tag decl in the same scope. Finding this 12473 // insanity with a redeclaration lookup can only actually happen 12474 // in C++. 12475 // 12476 // This is also okay for elaborated-type-specifiers, which is 12477 // technically forbidden by the current standard but which is 12478 // okay according to the likely resolution of an open issue; 12479 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 12480 if (getLangOpts().CPlusPlus) { 12481 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12482 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 12483 TagDecl *Tag = TT->getDecl(); 12484 if (Tag->getDeclName() == Name && 12485 Tag->getDeclContext()->getRedeclContext() 12486 ->Equals(TD->getDeclContext()->getRedeclContext())) { 12487 PrevDecl = Tag; 12488 Previous.clear(); 12489 Previous.addDecl(Tag); 12490 Previous.resolveKind(); 12491 } 12492 } 12493 } 12494 } 12495 12496 // If this is a redeclaration of a using shadow declaration, it must 12497 // declare a tag in the same context. In MSVC mode, we allow a 12498 // redefinition if either context is within the other. 12499 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 12500 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 12501 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 12502 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 12503 !(OldTag && isAcceptableTagRedeclContext( 12504 *this, OldTag->getDeclContext(), SearchDC))) { 12505 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 12506 Diag(Shadow->getTargetDecl()->getLocation(), 12507 diag::note_using_decl_target); 12508 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 12509 << 0; 12510 // Recover by ignoring the old declaration. 12511 Previous.clear(); 12512 goto CreateNewDecl; 12513 } 12514 } 12515 12516 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 12517 // If this is a use of a previous tag, or if the tag is already declared 12518 // in the same scope (so that the definition/declaration completes or 12519 // rementions the tag), reuse the decl. 12520 if (TUK == TUK_Reference || TUK == TUK_Friend || 12521 isDeclInScope(DirectPrevDecl, SearchDC, S, 12522 SS.isNotEmpty() || isExplicitSpecialization)) { 12523 // Make sure that this wasn't declared as an enum and now used as a 12524 // struct or something similar. 12525 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 12526 TUK == TUK_Definition, KWLoc, 12527 Name)) { 12528 bool SafeToContinue 12529 = (PrevTagDecl->getTagKind() != TTK_Enum && 12530 Kind != TTK_Enum); 12531 if (SafeToContinue) 12532 Diag(KWLoc, diag::err_use_with_wrong_tag) 12533 << Name 12534 << FixItHint::CreateReplacement(SourceRange(KWLoc), 12535 PrevTagDecl->getKindName()); 12536 else 12537 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 12538 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 12539 12540 if (SafeToContinue) 12541 Kind = PrevTagDecl->getTagKind(); 12542 else { 12543 // Recover by making this an anonymous redefinition. 12544 Name = nullptr; 12545 Previous.clear(); 12546 Invalid = true; 12547 } 12548 } 12549 12550 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 12551 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 12552 12553 // If this is an elaborated-type-specifier for a scoped enumeration, 12554 // the 'class' keyword is not necessary and not permitted. 12555 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12556 if (ScopedEnum) 12557 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 12558 << PrevEnum->isScoped() 12559 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 12560 return PrevTagDecl; 12561 } 12562 12563 QualType EnumUnderlyingTy; 12564 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12565 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 12566 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 12567 EnumUnderlyingTy = QualType(T, 0); 12568 12569 // All conflicts with previous declarations are recovered by 12570 // returning the previous declaration, unless this is a definition, 12571 // in which case we want the caller to bail out. 12572 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 12573 ScopedEnum, EnumUnderlyingTy, 12574 EnumUnderlyingIsImplicit, PrevEnum)) 12575 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 12576 } 12577 12578 // C++11 [class.mem]p1: 12579 // A member shall not be declared twice in the member-specification, 12580 // except that a nested class or member class template can be declared 12581 // and then later defined. 12582 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 12583 S->isDeclScope(PrevDecl)) { 12584 Diag(NameLoc, diag::ext_member_redeclared); 12585 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 12586 } 12587 12588 if (!Invalid) { 12589 // If this is a use, just return the declaration we found, unless 12590 // we have attributes. 12591 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12592 if (Attr) { 12593 // FIXME: Diagnose these attributes. For now, we create a new 12594 // declaration to hold them. 12595 } else if (TUK == TUK_Reference && 12596 (PrevTagDecl->getFriendObjectKind() == 12597 Decl::FOK_Undeclared || 12598 PP.getModuleContainingLocation( 12599 PrevDecl->getLocation()) != 12600 PP.getModuleContainingLocation(KWLoc)) && 12601 SS.isEmpty()) { 12602 // This declaration is a reference to an existing entity, but 12603 // has different visibility from that entity: it either makes 12604 // a friend visible or it makes a type visible in a new module. 12605 // In either case, create a new declaration. We only do this if 12606 // the declaration would have meant the same thing if no prior 12607 // declaration were found, that is, if it was found in the same 12608 // scope where we would have injected a declaration. 12609 if (!getTagInjectionContext(CurContext)->getRedeclContext() 12610 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 12611 return PrevTagDecl; 12612 // This is in the injected scope, create a new declaration in 12613 // that scope. 12614 S = getTagInjectionScope(S, getLangOpts()); 12615 } else { 12616 return PrevTagDecl; 12617 } 12618 } 12619 12620 // Diagnose attempts to redefine a tag. 12621 if (TUK == TUK_Definition) { 12622 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 12623 // If we're defining a specialization and the previous definition 12624 // is from an implicit instantiation, don't emit an error 12625 // here; we'll catch this in the general case below. 12626 bool IsExplicitSpecializationAfterInstantiation = false; 12627 if (isExplicitSpecialization) { 12628 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 12629 IsExplicitSpecializationAfterInstantiation = 12630 RD->getTemplateSpecializationKind() != 12631 TSK_ExplicitSpecialization; 12632 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 12633 IsExplicitSpecializationAfterInstantiation = 12634 ED->getTemplateSpecializationKind() != 12635 TSK_ExplicitSpecialization; 12636 } 12637 12638 NamedDecl *Hidden = nullptr; 12639 if (SkipBody && getLangOpts().CPlusPlus && 12640 !hasVisibleDefinition(Def, &Hidden)) { 12641 // There is a definition of this tag, but it is not visible. We 12642 // explicitly make use of C++'s one definition rule here, and 12643 // assume that this definition is identical to the hidden one 12644 // we already have. Make the existing definition visible and 12645 // use it in place of this one. 12646 SkipBody->ShouldSkip = true; 12647 makeMergedDefinitionVisible(Hidden, KWLoc); 12648 return Def; 12649 } else if (!IsExplicitSpecializationAfterInstantiation) { 12650 // A redeclaration in function prototype scope in C isn't 12651 // visible elsewhere, so merely issue a warning. 12652 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 12653 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 12654 else 12655 Diag(NameLoc, diag::err_redefinition) << Name; 12656 Diag(Def->getLocation(), diag::note_previous_definition); 12657 // If this is a redefinition, recover by making this 12658 // struct be anonymous, which will make any later 12659 // references get the previous definition. 12660 Name = nullptr; 12661 Previous.clear(); 12662 Invalid = true; 12663 } 12664 } else { 12665 // If the type is currently being defined, complain 12666 // about a nested redefinition. 12667 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 12668 if (TD->isBeingDefined()) { 12669 Diag(NameLoc, diag::err_nested_redefinition) << Name; 12670 Diag(PrevTagDecl->getLocation(), 12671 diag::note_previous_definition); 12672 Name = nullptr; 12673 Previous.clear(); 12674 Invalid = true; 12675 } 12676 } 12677 12678 // Okay, this is definition of a previously declared or referenced 12679 // tag. We're going to create a new Decl for it. 12680 } 12681 12682 // Okay, we're going to make a redeclaration. If this is some kind 12683 // of reference, make sure we build the redeclaration in the same DC 12684 // as the original, and ignore the current access specifier. 12685 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12686 SearchDC = PrevTagDecl->getDeclContext(); 12687 AS = AS_none; 12688 } 12689 } 12690 // If we get here we have (another) forward declaration or we 12691 // have a definition. Just create a new decl. 12692 12693 } else { 12694 // If we get here, this is a definition of a new tag type in a nested 12695 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 12696 // new decl/type. We set PrevDecl to NULL so that the entities 12697 // have distinct types. 12698 Previous.clear(); 12699 } 12700 // If we get here, we're going to create a new Decl. If PrevDecl 12701 // is non-NULL, it's a definition of the tag declared by 12702 // PrevDecl. If it's NULL, we have a new definition. 12703 12704 // Otherwise, PrevDecl is not a tag, but was found with tag 12705 // lookup. This is only actually possible in C++, where a few 12706 // things like templates still live in the tag namespace. 12707 } else { 12708 // Use a better diagnostic if an elaborated-type-specifier 12709 // found the wrong kind of type on the first 12710 // (non-redeclaration) lookup. 12711 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 12712 !Previous.isForRedeclaration()) { 12713 unsigned Kind = 0; 12714 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 12715 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 12716 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 12717 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 12718 Diag(PrevDecl->getLocation(), diag::note_declared_at); 12719 Invalid = true; 12720 12721 // Otherwise, only diagnose if the declaration is in scope. 12722 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 12723 SS.isNotEmpty() || isExplicitSpecialization)) { 12724 // do nothing 12725 12726 // Diagnose implicit declarations introduced by elaborated types. 12727 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 12728 unsigned Kind = 0; 12729 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 12730 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 12731 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 12732 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 12733 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 12734 Invalid = true; 12735 12736 // Otherwise it's a declaration. Call out a particularly common 12737 // case here. 12738 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12739 unsigned Kind = 0; 12740 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 12741 Diag(NameLoc, diag::err_tag_definition_of_typedef) 12742 << Name << Kind << TND->getUnderlyingType(); 12743 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 12744 Invalid = true; 12745 12746 // Otherwise, diagnose. 12747 } else { 12748 // The tag name clashes with something else in the target scope, 12749 // issue an error and recover by making this tag be anonymous. 12750 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 12751 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12752 Name = nullptr; 12753 Invalid = true; 12754 } 12755 12756 // The existing declaration isn't relevant to us; we're in a 12757 // new scope, so clear out the previous declaration. 12758 Previous.clear(); 12759 } 12760 } 12761 12762 CreateNewDecl: 12763 12764 TagDecl *PrevDecl = nullptr; 12765 if (Previous.isSingleResult()) 12766 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 12767 12768 // If there is an identifier, use the location of the identifier as the 12769 // location of the decl, otherwise use the location of the struct/union 12770 // keyword. 12771 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 12772 12773 // Otherwise, create a new declaration. If there is a previous 12774 // declaration of the same entity, the two will be linked via 12775 // PrevDecl. 12776 TagDecl *New; 12777 12778 bool IsForwardReference = false; 12779 if (Kind == TTK_Enum) { 12780 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 12781 // enum X { A, B, C } D; D should chain to X. 12782 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 12783 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 12784 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 12785 // If this is an undefined enum, warn. 12786 if (TUK != TUK_Definition && !Invalid) { 12787 TagDecl *Def; 12788 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 12789 cast<EnumDecl>(New)->isFixed()) { 12790 // C++0x: 7.2p2: opaque-enum-declaration. 12791 // Conflicts are diagnosed above. Do nothing. 12792 } 12793 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 12794 Diag(Loc, diag::ext_forward_ref_enum_def) 12795 << New; 12796 Diag(Def->getLocation(), diag::note_previous_definition); 12797 } else { 12798 unsigned DiagID = diag::ext_forward_ref_enum; 12799 if (getLangOpts().MSVCCompat) 12800 DiagID = diag::ext_ms_forward_ref_enum; 12801 else if (getLangOpts().CPlusPlus) 12802 DiagID = diag::err_forward_ref_enum; 12803 Diag(Loc, DiagID); 12804 12805 // If this is a forward-declared reference to an enumeration, make a 12806 // note of it; we won't actually be introducing the declaration into 12807 // the declaration context. 12808 if (TUK == TUK_Reference) 12809 IsForwardReference = true; 12810 } 12811 } 12812 12813 if (EnumUnderlying) { 12814 EnumDecl *ED = cast<EnumDecl>(New); 12815 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12816 ED->setIntegerTypeSourceInfo(TI); 12817 else 12818 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 12819 ED->setPromotionType(ED->getIntegerType()); 12820 } 12821 } else { 12822 // struct/union/class 12823 12824 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 12825 // struct X { int A; } D; D should chain to X. 12826 if (getLangOpts().CPlusPlus) { 12827 // FIXME: Look for a way to use RecordDecl for simple structs. 12828 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12829 cast_or_null<CXXRecordDecl>(PrevDecl)); 12830 12831 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 12832 StdBadAlloc = cast<CXXRecordDecl>(New); 12833 } else 12834 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12835 cast_or_null<RecordDecl>(PrevDecl)); 12836 } 12837 12838 // C++11 [dcl.type]p3: 12839 // A type-specifier-seq shall not define a class or enumeration [...]. 12840 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 12841 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 12842 << Context.getTagDeclType(New); 12843 Invalid = true; 12844 } 12845 12846 // Maybe add qualifier info. 12847 if (SS.isNotEmpty()) { 12848 if (SS.isSet()) { 12849 // If this is either a declaration or a definition, check the 12850 // nested-name-specifier against the current context. We don't do this 12851 // for explicit specializations, because they have similar checking 12852 // (with more specific diagnostics) in the call to 12853 // CheckMemberSpecialization, below. 12854 if (!isExplicitSpecialization && 12855 (TUK == TUK_Definition || TUK == TUK_Declaration) && 12856 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 12857 Invalid = true; 12858 12859 New->setQualifierInfo(SS.getWithLocInContext(Context)); 12860 if (TemplateParameterLists.size() > 0) { 12861 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 12862 } 12863 } 12864 else 12865 Invalid = true; 12866 } 12867 12868 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 12869 // Add alignment attributes if necessary; these attributes are checked when 12870 // the ASTContext lays out the structure. 12871 // 12872 // It is important for implementing the correct semantics that this 12873 // happen here (in act on tag decl). The #pragma pack stack is 12874 // maintained as a result of parser callbacks which can occur at 12875 // many points during the parsing of a struct declaration (because 12876 // the #pragma tokens are effectively skipped over during the 12877 // parsing of the struct). 12878 if (TUK == TUK_Definition) { 12879 AddAlignmentAttributesForRecord(RD); 12880 AddMsStructLayoutForRecord(RD); 12881 } 12882 } 12883 12884 if (ModulePrivateLoc.isValid()) { 12885 if (isExplicitSpecialization) 12886 Diag(New->getLocation(), diag::err_module_private_specialization) 12887 << 2 12888 << FixItHint::CreateRemoval(ModulePrivateLoc); 12889 // __module_private__ does not apply to local classes. However, we only 12890 // diagnose this as an error when the declaration specifiers are 12891 // freestanding. Here, we just ignore the __module_private__. 12892 else if (!SearchDC->isFunctionOrMethod()) 12893 New->setModulePrivate(); 12894 } 12895 12896 // If this is a specialization of a member class (of a class template), 12897 // check the specialization. 12898 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 12899 Invalid = true; 12900 12901 // If we're declaring or defining a tag in function prototype scope in C, 12902 // note that this type can only be used within the function and add it to 12903 // the list of decls to inject into the function definition scope. 12904 if ((Name || Kind == TTK_Enum) && 12905 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 12906 if (getLangOpts().CPlusPlus) { 12907 // C++ [dcl.fct]p6: 12908 // Types shall not be defined in return or parameter types. 12909 if (TUK == TUK_Definition && !IsTypeSpecifier) { 12910 Diag(Loc, diag::err_type_defined_in_param_type) 12911 << Name; 12912 Invalid = true; 12913 } 12914 } else if (!PrevDecl) { 12915 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 12916 } 12917 DeclsInPrototypeScope.push_back(New); 12918 } 12919 12920 if (Invalid) 12921 New->setInvalidDecl(); 12922 12923 if (Attr) 12924 ProcessDeclAttributeList(S, New, Attr); 12925 12926 // Set the lexical context. If the tag has a C++ scope specifier, the 12927 // lexical context will be different from the semantic context. 12928 New->setLexicalDeclContext(CurContext); 12929 12930 // Mark this as a friend decl if applicable. 12931 // In Microsoft mode, a friend declaration also acts as a forward 12932 // declaration so we always pass true to setObjectOfFriendDecl to make 12933 // the tag name visible. 12934 if (TUK == TUK_Friend) 12935 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 12936 12937 // Set the access specifier. 12938 if (!Invalid && SearchDC->isRecord()) 12939 SetMemberAccessSpecifier(New, PrevDecl, AS); 12940 12941 if (TUK == TUK_Definition) 12942 New->startDefinition(); 12943 12944 // If this has an identifier, add it to the scope stack. 12945 if (TUK == TUK_Friend) { 12946 // We might be replacing an existing declaration in the lookup tables; 12947 // if so, borrow its access specifier. 12948 if (PrevDecl) 12949 New->setAccess(PrevDecl->getAccess()); 12950 12951 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 12952 DC->makeDeclVisibleInContext(New); 12953 if (Name) // can be null along some error paths 12954 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12955 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 12956 } else if (Name) { 12957 S = getNonFieldDeclScope(S); 12958 PushOnScopeChains(New, S, !IsForwardReference); 12959 if (IsForwardReference) 12960 SearchDC->makeDeclVisibleInContext(New); 12961 } else { 12962 CurContext->addDecl(New); 12963 } 12964 12965 // If this is the C FILE type, notify the AST context. 12966 if (IdentifierInfo *II = New->getIdentifier()) 12967 if (!New->isInvalidDecl() && 12968 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 12969 II->isStr("FILE")) 12970 Context.setFILEDecl(New); 12971 12972 if (PrevDecl) 12973 mergeDeclAttributes(New, PrevDecl); 12974 12975 // If there's a #pragma GCC visibility in scope, set the visibility of this 12976 // record. 12977 AddPushedVisibilityAttribute(New); 12978 12979 OwnedDecl = true; 12980 // In C++, don't return an invalid declaration. We can't recover well from 12981 // the cases where we make the type anonymous. 12982 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 12983 } 12984 12985 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 12986 AdjustDeclIfTemplate(TagD); 12987 TagDecl *Tag = cast<TagDecl>(TagD); 12988 12989 // Enter the tag context. 12990 PushDeclContext(S, Tag); 12991 12992 ActOnDocumentableDecl(TagD); 12993 12994 // If there's a #pragma GCC visibility in scope, set the visibility of this 12995 // record. 12996 AddPushedVisibilityAttribute(Tag); 12997 } 12998 12999 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13000 assert(isa<ObjCContainerDecl>(IDecl) && 13001 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13002 DeclContext *OCD = cast<DeclContext>(IDecl); 13003 assert(getContainingDC(OCD) == CurContext && 13004 "The next DeclContext should be lexically contained in the current one."); 13005 CurContext = OCD; 13006 return IDecl; 13007 } 13008 13009 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13010 SourceLocation FinalLoc, 13011 bool IsFinalSpelledSealed, 13012 SourceLocation LBraceLoc) { 13013 AdjustDeclIfTemplate(TagD); 13014 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13015 13016 FieldCollector->StartClass(); 13017 13018 if (!Record->getIdentifier()) 13019 return; 13020 13021 if (FinalLoc.isValid()) 13022 Record->addAttr(new (Context) 13023 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13024 13025 // C++ [class]p2: 13026 // [...] The class-name is also inserted into the scope of the 13027 // class itself; this is known as the injected-class-name. For 13028 // purposes of access checking, the injected-class-name is treated 13029 // as if it were a public member name. 13030 CXXRecordDecl *InjectedClassName 13031 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13032 Record->getLocStart(), Record->getLocation(), 13033 Record->getIdentifier(), 13034 /*PrevDecl=*/nullptr, 13035 /*DelayTypeCreation=*/true); 13036 Context.getTypeDeclType(InjectedClassName, Record); 13037 InjectedClassName->setImplicit(); 13038 InjectedClassName->setAccess(AS_public); 13039 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13040 InjectedClassName->setDescribedClassTemplate(Template); 13041 PushOnScopeChains(InjectedClassName, S); 13042 assert(InjectedClassName->isInjectedClassName() && 13043 "Broken injected-class-name"); 13044 } 13045 13046 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13047 SourceLocation RBraceLoc) { 13048 AdjustDeclIfTemplate(TagD); 13049 TagDecl *Tag = cast<TagDecl>(TagD); 13050 Tag->setRBraceLoc(RBraceLoc); 13051 13052 // Make sure we "complete" the definition even it is invalid. 13053 if (Tag->isBeingDefined()) { 13054 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13055 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13056 RD->completeDefinition(); 13057 } 13058 13059 if (isa<CXXRecordDecl>(Tag)) 13060 FieldCollector->FinishClass(); 13061 13062 // Exit this scope of this tag's definition. 13063 PopDeclContext(); 13064 13065 if (getCurLexicalContext()->isObjCContainer() && 13066 Tag->getDeclContext()->isFileContext()) 13067 Tag->setTopLevelDeclInObjCContainer(); 13068 13069 // Notify the consumer that we've defined a tag. 13070 if (!Tag->isInvalidDecl()) 13071 Consumer.HandleTagDeclDefinition(Tag); 13072 } 13073 13074 void Sema::ActOnObjCContainerFinishDefinition() { 13075 // Exit this scope of this interface definition. 13076 PopDeclContext(); 13077 } 13078 13079 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13080 assert(DC == CurContext && "Mismatch of container contexts"); 13081 OriginalLexicalContext = DC; 13082 ActOnObjCContainerFinishDefinition(); 13083 } 13084 13085 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13086 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13087 OriginalLexicalContext = nullptr; 13088 } 13089 13090 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13091 AdjustDeclIfTemplate(TagD); 13092 TagDecl *Tag = cast<TagDecl>(TagD); 13093 Tag->setInvalidDecl(); 13094 13095 // Make sure we "complete" the definition even it is invalid. 13096 if (Tag->isBeingDefined()) { 13097 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13098 RD->completeDefinition(); 13099 } 13100 13101 // We're undoing ActOnTagStartDefinition here, not 13102 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 13103 // the FieldCollector. 13104 13105 PopDeclContext(); 13106 } 13107 13108 // Note that FieldName may be null for anonymous bitfields. 13109 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 13110 IdentifierInfo *FieldName, 13111 QualType FieldTy, bool IsMsStruct, 13112 Expr *BitWidth, bool *ZeroWidth) { 13113 // Default to true; that shouldn't confuse checks for emptiness 13114 if (ZeroWidth) 13115 *ZeroWidth = true; 13116 13117 // C99 6.7.2.1p4 - verify the field type. 13118 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 13119 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 13120 // Handle incomplete types with specific error. 13121 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 13122 return ExprError(); 13123 if (FieldName) 13124 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 13125 << FieldName << FieldTy << BitWidth->getSourceRange(); 13126 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 13127 << FieldTy << BitWidth->getSourceRange(); 13128 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 13129 UPPC_BitFieldWidth)) 13130 return ExprError(); 13131 13132 // If the bit-width is type- or value-dependent, don't try to check 13133 // it now. 13134 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 13135 return BitWidth; 13136 13137 llvm::APSInt Value; 13138 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 13139 if (ICE.isInvalid()) 13140 return ICE; 13141 BitWidth = ICE.get(); 13142 13143 if (Value != 0 && ZeroWidth) 13144 *ZeroWidth = false; 13145 13146 // Zero-width bitfield is ok for anonymous field. 13147 if (Value == 0 && FieldName) 13148 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 13149 13150 if (Value.isSigned() && Value.isNegative()) { 13151 if (FieldName) 13152 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 13153 << FieldName << Value.toString(10); 13154 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 13155 << Value.toString(10); 13156 } 13157 13158 if (!FieldTy->isDependentType()) { 13159 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 13160 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 13161 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 13162 13163 // Over-wide bitfields are an error in C or when using the MSVC bitfield 13164 // ABI. 13165 bool CStdConstraintViolation = 13166 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 13167 bool MSBitfieldViolation = 13168 Value.ugt(TypeStorageSize) && 13169 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 13170 if (CStdConstraintViolation || MSBitfieldViolation) { 13171 unsigned DiagWidth = 13172 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 13173 if (FieldName) 13174 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 13175 << FieldName << (unsigned)Value.getZExtValue() 13176 << !CStdConstraintViolation << DiagWidth; 13177 13178 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 13179 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 13180 << DiagWidth; 13181 } 13182 13183 // Warn on types where the user might conceivably expect to get all 13184 // specified bits as value bits: that's all integral types other than 13185 // 'bool'. 13186 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13187 if (FieldName) 13188 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13189 << FieldName << (unsigned)Value.getZExtValue() 13190 << (unsigned)TypeWidth; 13191 else 13192 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13193 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13194 } 13195 } 13196 13197 return BitWidth; 13198 } 13199 13200 /// ActOnField - Each field of a C struct/union is passed into this in order 13201 /// to create a FieldDecl object for it. 13202 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13203 Declarator &D, Expr *BitfieldWidth) { 13204 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13205 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13206 /*InitStyle=*/ICIS_NoInit, AS_public); 13207 return Res; 13208 } 13209 13210 /// HandleField - Analyze a field of a C struct or a C++ data member. 13211 /// 13212 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13213 SourceLocation DeclStart, 13214 Declarator &D, Expr *BitWidth, 13215 InClassInitStyle InitStyle, 13216 AccessSpecifier AS) { 13217 IdentifierInfo *II = D.getIdentifier(); 13218 SourceLocation Loc = DeclStart; 13219 if (II) Loc = D.getIdentifierLoc(); 13220 13221 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13222 QualType T = TInfo->getType(); 13223 if (getLangOpts().CPlusPlus) { 13224 CheckExtraCXXDefaultArguments(D); 13225 13226 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13227 UPPC_DataMemberType)) { 13228 D.setInvalidType(); 13229 T = Context.IntTy; 13230 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13231 } 13232 } 13233 13234 // TR 18037 does not allow fields to be declared with address spaces. 13235 if (T.getQualifiers().hasAddressSpace()) { 13236 Diag(Loc, diag::err_field_with_address_space); 13237 D.setInvalidType(); 13238 } 13239 13240 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 13241 // used as structure or union field: image, sampler, event or block types. 13242 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 13243 T->isSamplerT() || T->isBlockPointerType())) { 13244 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 13245 D.setInvalidType(); 13246 } 13247 13248 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13249 13250 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13251 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13252 diag::err_invalid_thread) 13253 << DeclSpec::getSpecifierName(TSCS); 13254 13255 // Check to see if this name was declared as a member previously 13256 NamedDecl *PrevDecl = nullptr; 13257 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13258 LookupName(Previous, S); 13259 switch (Previous.getResultKind()) { 13260 case LookupResult::Found: 13261 case LookupResult::FoundUnresolvedValue: 13262 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13263 break; 13264 13265 case LookupResult::FoundOverloaded: 13266 PrevDecl = Previous.getRepresentativeDecl(); 13267 break; 13268 13269 case LookupResult::NotFound: 13270 case LookupResult::NotFoundInCurrentInstantiation: 13271 case LookupResult::Ambiguous: 13272 break; 13273 } 13274 Previous.suppressDiagnostics(); 13275 13276 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13277 // Maybe we will complain about the shadowed template parameter. 13278 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13279 // Just pretend that we didn't see the previous declaration. 13280 PrevDecl = nullptr; 13281 } 13282 13283 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13284 PrevDecl = nullptr; 13285 13286 bool Mutable 13287 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 13288 SourceLocation TSSL = D.getLocStart(); 13289 FieldDecl *NewFD 13290 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 13291 TSSL, AS, PrevDecl, &D); 13292 13293 if (NewFD->isInvalidDecl()) 13294 Record->setInvalidDecl(); 13295 13296 if (D.getDeclSpec().isModulePrivateSpecified()) 13297 NewFD->setModulePrivate(); 13298 13299 if (NewFD->isInvalidDecl() && PrevDecl) { 13300 // Don't introduce NewFD into scope; there's already something 13301 // with the same name in the same scope. 13302 } else if (II) { 13303 PushOnScopeChains(NewFD, S); 13304 } else 13305 Record->addDecl(NewFD); 13306 13307 return NewFD; 13308 } 13309 13310 /// \brief Build a new FieldDecl and check its well-formedness. 13311 /// 13312 /// This routine builds a new FieldDecl given the fields name, type, 13313 /// record, etc. \p PrevDecl should refer to any previous declaration 13314 /// with the same name and in the same scope as the field to be 13315 /// created. 13316 /// 13317 /// \returns a new FieldDecl. 13318 /// 13319 /// \todo The Declarator argument is a hack. It will be removed once 13320 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 13321 TypeSourceInfo *TInfo, 13322 RecordDecl *Record, SourceLocation Loc, 13323 bool Mutable, Expr *BitWidth, 13324 InClassInitStyle InitStyle, 13325 SourceLocation TSSL, 13326 AccessSpecifier AS, NamedDecl *PrevDecl, 13327 Declarator *D) { 13328 IdentifierInfo *II = Name.getAsIdentifierInfo(); 13329 bool InvalidDecl = false; 13330 if (D) InvalidDecl = D->isInvalidType(); 13331 13332 // If we receive a broken type, recover by assuming 'int' and 13333 // marking this declaration as invalid. 13334 if (T.isNull()) { 13335 InvalidDecl = true; 13336 T = Context.IntTy; 13337 } 13338 13339 QualType EltTy = Context.getBaseElementType(T); 13340 if (!EltTy->isDependentType()) { 13341 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 13342 // Fields of incomplete type force their record to be invalid. 13343 Record->setInvalidDecl(); 13344 InvalidDecl = true; 13345 } else { 13346 NamedDecl *Def; 13347 EltTy->isIncompleteType(&Def); 13348 if (Def && Def->isInvalidDecl()) { 13349 Record->setInvalidDecl(); 13350 InvalidDecl = true; 13351 } 13352 } 13353 } 13354 13355 // OpenCL v1.2 s6.9.c: bitfields are not supported. 13356 if (BitWidth && getLangOpts().OpenCL) { 13357 Diag(Loc, diag::err_opencl_bitfields); 13358 InvalidDecl = true; 13359 } 13360 13361 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13362 // than a variably modified type. 13363 if (!InvalidDecl && T->isVariablyModifiedType()) { 13364 bool SizeIsNegative; 13365 llvm::APSInt Oversized; 13366 13367 TypeSourceInfo *FixedTInfo = 13368 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 13369 SizeIsNegative, 13370 Oversized); 13371 if (FixedTInfo) { 13372 Diag(Loc, diag::warn_illegal_constant_array_size); 13373 TInfo = FixedTInfo; 13374 T = FixedTInfo->getType(); 13375 } else { 13376 if (SizeIsNegative) 13377 Diag(Loc, diag::err_typecheck_negative_array_size); 13378 else if (Oversized.getBoolValue()) 13379 Diag(Loc, diag::err_array_too_large) 13380 << Oversized.toString(10); 13381 else 13382 Diag(Loc, diag::err_typecheck_field_variable_size); 13383 InvalidDecl = true; 13384 } 13385 } 13386 13387 // Fields can not have abstract class types 13388 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 13389 diag::err_abstract_type_in_decl, 13390 AbstractFieldType)) 13391 InvalidDecl = true; 13392 13393 bool ZeroWidth = false; 13394 if (InvalidDecl) 13395 BitWidth = nullptr; 13396 // If this is declared as a bit-field, check the bit-field. 13397 if (BitWidth) { 13398 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 13399 &ZeroWidth).get(); 13400 if (!BitWidth) { 13401 InvalidDecl = true; 13402 BitWidth = nullptr; 13403 ZeroWidth = false; 13404 } 13405 } 13406 13407 // Check that 'mutable' is consistent with the type of the declaration. 13408 if (!InvalidDecl && Mutable) { 13409 unsigned DiagID = 0; 13410 if (T->isReferenceType()) 13411 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 13412 : diag::err_mutable_reference; 13413 else if (T.isConstQualified()) 13414 DiagID = diag::err_mutable_const; 13415 13416 if (DiagID) { 13417 SourceLocation ErrLoc = Loc; 13418 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 13419 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 13420 Diag(ErrLoc, DiagID); 13421 if (DiagID != diag::ext_mutable_reference) { 13422 Mutable = false; 13423 InvalidDecl = true; 13424 } 13425 } 13426 } 13427 13428 // C++11 [class.union]p8 (DR1460): 13429 // At most one variant member of a union may have a 13430 // brace-or-equal-initializer. 13431 if (InitStyle != ICIS_NoInit) 13432 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 13433 13434 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 13435 BitWidth, Mutable, InitStyle); 13436 if (InvalidDecl) 13437 NewFD->setInvalidDecl(); 13438 13439 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 13440 Diag(Loc, diag::err_duplicate_member) << II; 13441 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13442 NewFD->setInvalidDecl(); 13443 } 13444 13445 if (!InvalidDecl && getLangOpts().CPlusPlus) { 13446 if (Record->isUnion()) { 13447 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13448 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13449 if (RDecl->getDefinition()) { 13450 // C++ [class.union]p1: An object of a class with a non-trivial 13451 // constructor, a non-trivial copy constructor, a non-trivial 13452 // destructor, or a non-trivial copy assignment operator 13453 // cannot be a member of a union, nor can an array of such 13454 // objects. 13455 if (CheckNontrivialField(NewFD)) 13456 NewFD->setInvalidDecl(); 13457 } 13458 } 13459 13460 // C++ [class.union]p1: If a union contains a member of reference type, 13461 // the program is ill-formed, except when compiling with MSVC extensions 13462 // enabled. 13463 if (EltTy->isReferenceType()) { 13464 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 13465 diag::ext_union_member_of_reference_type : 13466 diag::err_union_member_of_reference_type) 13467 << NewFD->getDeclName() << EltTy; 13468 if (!getLangOpts().MicrosoftExt) 13469 NewFD->setInvalidDecl(); 13470 } 13471 } 13472 } 13473 13474 // FIXME: We need to pass in the attributes given an AST 13475 // representation, not a parser representation. 13476 if (D) { 13477 // FIXME: The current scope is almost... but not entirely... correct here. 13478 ProcessDeclAttributes(getCurScope(), NewFD, *D); 13479 13480 if (NewFD->hasAttrs()) 13481 CheckAlignasUnderalignment(NewFD); 13482 } 13483 13484 // In auto-retain/release, infer strong retension for fields of 13485 // retainable type. 13486 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 13487 NewFD->setInvalidDecl(); 13488 13489 if (T.isObjCGCWeak()) 13490 Diag(Loc, diag::warn_attribute_weak_on_field); 13491 13492 NewFD->setAccess(AS); 13493 return NewFD; 13494 } 13495 13496 bool Sema::CheckNontrivialField(FieldDecl *FD) { 13497 assert(FD); 13498 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 13499 13500 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 13501 return false; 13502 13503 QualType EltTy = Context.getBaseElementType(FD->getType()); 13504 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13505 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13506 if (RDecl->getDefinition()) { 13507 // We check for copy constructors before constructors 13508 // because otherwise we'll never get complaints about 13509 // copy constructors. 13510 13511 CXXSpecialMember member = CXXInvalid; 13512 // We're required to check for any non-trivial constructors. Since the 13513 // implicit default constructor is suppressed if there are any 13514 // user-declared constructors, we just need to check that there is a 13515 // trivial default constructor and a trivial copy constructor. (We don't 13516 // worry about move constructors here, since this is a C++98 check.) 13517 if (RDecl->hasNonTrivialCopyConstructor()) 13518 member = CXXCopyConstructor; 13519 else if (!RDecl->hasTrivialDefaultConstructor()) 13520 member = CXXDefaultConstructor; 13521 else if (RDecl->hasNonTrivialCopyAssignment()) 13522 member = CXXCopyAssignment; 13523 else if (RDecl->hasNonTrivialDestructor()) 13524 member = CXXDestructor; 13525 13526 if (member != CXXInvalid) { 13527 if (!getLangOpts().CPlusPlus11 && 13528 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 13529 // Objective-C++ ARC: it is an error to have a non-trivial field of 13530 // a union. However, system headers in Objective-C programs 13531 // occasionally have Objective-C lifetime objects within unions, 13532 // and rather than cause the program to fail, we make those 13533 // members unavailable. 13534 SourceLocation Loc = FD->getLocation(); 13535 if (getSourceManager().isInSystemHeader(Loc)) { 13536 if (!FD->hasAttr<UnavailableAttr>()) 13537 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13538 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 13539 return false; 13540 } 13541 } 13542 13543 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 13544 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 13545 diag::err_illegal_union_or_anon_struct_member) 13546 << FD->getParent()->isUnion() << FD->getDeclName() << member; 13547 DiagnoseNontrivial(RDecl, member); 13548 return !getLangOpts().CPlusPlus11; 13549 } 13550 } 13551 } 13552 13553 return false; 13554 } 13555 13556 /// TranslateIvarVisibility - Translate visibility from a token ID to an 13557 /// AST enum value. 13558 static ObjCIvarDecl::AccessControl 13559 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 13560 switch (ivarVisibility) { 13561 default: llvm_unreachable("Unknown visitibility kind"); 13562 case tok::objc_private: return ObjCIvarDecl::Private; 13563 case tok::objc_public: return ObjCIvarDecl::Public; 13564 case tok::objc_protected: return ObjCIvarDecl::Protected; 13565 case tok::objc_package: return ObjCIvarDecl::Package; 13566 } 13567 } 13568 13569 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 13570 /// in order to create an IvarDecl object for it. 13571 Decl *Sema::ActOnIvar(Scope *S, 13572 SourceLocation DeclStart, 13573 Declarator &D, Expr *BitfieldWidth, 13574 tok::ObjCKeywordKind Visibility) { 13575 13576 IdentifierInfo *II = D.getIdentifier(); 13577 Expr *BitWidth = (Expr*)BitfieldWidth; 13578 SourceLocation Loc = DeclStart; 13579 if (II) Loc = D.getIdentifierLoc(); 13580 13581 // FIXME: Unnamed fields can be handled in various different ways, for 13582 // example, unnamed unions inject all members into the struct namespace! 13583 13584 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13585 QualType T = TInfo->getType(); 13586 13587 if (BitWidth) { 13588 // 6.7.2.1p3, 6.7.2.1p4 13589 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 13590 if (!BitWidth) 13591 D.setInvalidType(); 13592 } else { 13593 // Not a bitfield. 13594 13595 // validate II. 13596 13597 } 13598 if (T->isReferenceType()) { 13599 Diag(Loc, diag::err_ivar_reference_type); 13600 D.setInvalidType(); 13601 } 13602 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13603 // than a variably modified type. 13604 else if (T->isVariablyModifiedType()) { 13605 Diag(Loc, diag::err_typecheck_ivar_variable_size); 13606 D.setInvalidType(); 13607 } 13608 13609 // Get the visibility (access control) for this ivar. 13610 ObjCIvarDecl::AccessControl ac = 13611 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 13612 : ObjCIvarDecl::None; 13613 // Must set ivar's DeclContext to its enclosing interface. 13614 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 13615 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 13616 return nullptr; 13617 ObjCContainerDecl *EnclosingContext; 13618 if (ObjCImplementationDecl *IMPDecl = 13619 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13620 if (LangOpts.ObjCRuntime.isFragile()) { 13621 // Case of ivar declared in an implementation. Context is that of its class. 13622 EnclosingContext = IMPDecl->getClassInterface(); 13623 assert(EnclosingContext && "Implementation has no class interface!"); 13624 } 13625 else 13626 EnclosingContext = EnclosingDecl; 13627 } else { 13628 if (ObjCCategoryDecl *CDecl = 13629 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13630 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 13631 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 13632 return nullptr; 13633 } 13634 } 13635 EnclosingContext = EnclosingDecl; 13636 } 13637 13638 // Construct the decl. 13639 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 13640 DeclStart, Loc, II, T, 13641 TInfo, ac, (Expr *)BitfieldWidth); 13642 13643 if (II) { 13644 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 13645 ForRedeclaration); 13646 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 13647 && !isa<TagDecl>(PrevDecl)) { 13648 Diag(Loc, diag::err_duplicate_member) << II; 13649 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13650 NewID->setInvalidDecl(); 13651 } 13652 } 13653 13654 // Process attributes attached to the ivar. 13655 ProcessDeclAttributes(S, NewID, D); 13656 13657 if (D.isInvalidType()) 13658 NewID->setInvalidDecl(); 13659 13660 // In ARC, infer 'retaining' for ivars of retainable type. 13661 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 13662 NewID->setInvalidDecl(); 13663 13664 if (D.getDeclSpec().isModulePrivateSpecified()) 13665 NewID->setModulePrivate(); 13666 13667 if (II) { 13668 // FIXME: When interfaces are DeclContexts, we'll need to add 13669 // these to the interface. 13670 S->AddDecl(NewID); 13671 IdResolver.AddDecl(NewID); 13672 } 13673 13674 if (LangOpts.ObjCRuntime.isNonFragile() && 13675 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 13676 Diag(Loc, diag::warn_ivars_in_interface); 13677 13678 return NewID; 13679 } 13680 13681 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 13682 /// class and class extensions. For every class \@interface and class 13683 /// extension \@interface, if the last ivar is a bitfield of any type, 13684 /// then add an implicit `char :0` ivar to the end of that interface. 13685 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 13686 SmallVectorImpl<Decl *> &AllIvarDecls) { 13687 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 13688 return; 13689 13690 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 13691 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 13692 13693 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 13694 return; 13695 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 13696 if (!ID) { 13697 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 13698 if (!CD->IsClassExtension()) 13699 return; 13700 } 13701 // No need to add this to end of @implementation. 13702 else 13703 return; 13704 } 13705 // All conditions are met. Add a new bitfield to the tail end of ivars. 13706 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 13707 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 13708 13709 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 13710 DeclLoc, DeclLoc, nullptr, 13711 Context.CharTy, 13712 Context.getTrivialTypeSourceInfo(Context.CharTy, 13713 DeclLoc), 13714 ObjCIvarDecl::Private, BW, 13715 true); 13716 AllIvarDecls.push_back(Ivar); 13717 } 13718 13719 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 13720 ArrayRef<Decl *> Fields, SourceLocation LBrac, 13721 SourceLocation RBrac, AttributeList *Attr) { 13722 assert(EnclosingDecl && "missing record or interface decl"); 13723 13724 // If this is an Objective-C @implementation or category and we have 13725 // new fields here we should reset the layout of the interface since 13726 // it will now change. 13727 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 13728 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 13729 switch (DC->getKind()) { 13730 default: break; 13731 case Decl::ObjCCategory: 13732 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 13733 break; 13734 case Decl::ObjCImplementation: 13735 Context. 13736 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 13737 break; 13738 } 13739 } 13740 13741 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 13742 13743 // Start counting up the number of named members; make sure to include 13744 // members of anonymous structs and unions in the total. 13745 unsigned NumNamedMembers = 0; 13746 if (Record) { 13747 for (const auto *I : Record->decls()) { 13748 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 13749 if (IFD->getDeclName()) 13750 ++NumNamedMembers; 13751 } 13752 } 13753 13754 // Verify that all the fields are okay. 13755 SmallVector<FieldDecl*, 32> RecFields; 13756 13757 bool ARCErrReported = false; 13758 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 13759 i != end; ++i) { 13760 FieldDecl *FD = cast<FieldDecl>(*i); 13761 13762 // Get the type for the field. 13763 const Type *FDTy = FD->getType().getTypePtr(); 13764 13765 if (!FD->isAnonymousStructOrUnion()) { 13766 // Remember all fields written by the user. 13767 RecFields.push_back(FD); 13768 } 13769 13770 // If the field is already invalid for some reason, don't emit more 13771 // diagnostics about it. 13772 if (FD->isInvalidDecl()) { 13773 EnclosingDecl->setInvalidDecl(); 13774 continue; 13775 } 13776 13777 // C99 6.7.2.1p2: 13778 // A structure or union shall not contain a member with 13779 // incomplete or function type (hence, a structure shall not 13780 // contain an instance of itself, but may contain a pointer to 13781 // an instance of itself), except that the last member of a 13782 // structure with more than one named member may have incomplete 13783 // array type; such a structure (and any union containing, 13784 // possibly recursively, a member that is such a structure) 13785 // shall not be a member of a structure or an element of an 13786 // array. 13787 if (FDTy->isFunctionType()) { 13788 // Field declared as a function. 13789 Diag(FD->getLocation(), diag::err_field_declared_as_function) 13790 << FD->getDeclName(); 13791 FD->setInvalidDecl(); 13792 EnclosingDecl->setInvalidDecl(); 13793 continue; 13794 } else if (FDTy->isIncompleteArrayType() && Record && 13795 ((i + 1 == Fields.end() && !Record->isUnion()) || 13796 ((getLangOpts().MicrosoftExt || 13797 getLangOpts().CPlusPlus) && 13798 (i + 1 == Fields.end() || Record->isUnion())))) { 13799 // Flexible array member. 13800 // Microsoft and g++ is more permissive regarding flexible array. 13801 // It will accept flexible array in union and also 13802 // as the sole element of a struct/class. 13803 unsigned DiagID = 0; 13804 if (Record->isUnion()) 13805 DiagID = getLangOpts().MicrosoftExt 13806 ? diag::ext_flexible_array_union_ms 13807 : getLangOpts().CPlusPlus 13808 ? diag::ext_flexible_array_union_gnu 13809 : diag::err_flexible_array_union; 13810 else if (Fields.size() == 1) 13811 DiagID = getLangOpts().MicrosoftExt 13812 ? diag::ext_flexible_array_empty_aggregate_ms 13813 : getLangOpts().CPlusPlus 13814 ? diag::ext_flexible_array_empty_aggregate_gnu 13815 : NumNamedMembers < 1 13816 ? diag::err_flexible_array_empty_aggregate 13817 : 0; 13818 13819 if (DiagID) 13820 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 13821 << Record->getTagKind(); 13822 // While the layout of types that contain virtual bases is not specified 13823 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 13824 // virtual bases after the derived members. This would make a flexible 13825 // array member declared at the end of an object not adjacent to the end 13826 // of the type. 13827 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 13828 if (RD->getNumVBases() != 0) 13829 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 13830 << FD->getDeclName() << Record->getTagKind(); 13831 if (!getLangOpts().C99) 13832 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 13833 << FD->getDeclName() << Record->getTagKind(); 13834 13835 // If the element type has a non-trivial destructor, we would not 13836 // implicitly destroy the elements, so disallow it for now. 13837 // 13838 // FIXME: GCC allows this. We should probably either implicitly delete 13839 // the destructor of the containing class, or just allow this. 13840 QualType BaseElem = Context.getBaseElementType(FD->getType()); 13841 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 13842 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 13843 << FD->getDeclName() << FD->getType(); 13844 FD->setInvalidDecl(); 13845 EnclosingDecl->setInvalidDecl(); 13846 continue; 13847 } 13848 // Okay, we have a legal flexible array member at the end of the struct. 13849 Record->setHasFlexibleArrayMember(true); 13850 } else if (!FDTy->isDependentType() && 13851 RequireCompleteType(FD->getLocation(), FD->getType(), 13852 diag::err_field_incomplete)) { 13853 // Incomplete type 13854 FD->setInvalidDecl(); 13855 EnclosingDecl->setInvalidDecl(); 13856 continue; 13857 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 13858 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 13859 // A type which contains a flexible array member is considered to be a 13860 // flexible array member. 13861 Record->setHasFlexibleArrayMember(true); 13862 if (!Record->isUnion()) { 13863 // If this is a struct/class and this is not the last element, reject 13864 // it. Note that GCC supports variable sized arrays in the middle of 13865 // structures. 13866 if (i + 1 != Fields.end()) 13867 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 13868 << FD->getDeclName() << FD->getType(); 13869 else { 13870 // We support flexible arrays at the end of structs in 13871 // other structs as an extension. 13872 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 13873 << FD->getDeclName(); 13874 } 13875 } 13876 } 13877 if (isa<ObjCContainerDecl>(EnclosingDecl) && 13878 RequireNonAbstractType(FD->getLocation(), FD->getType(), 13879 diag::err_abstract_type_in_decl, 13880 AbstractIvarType)) { 13881 // Ivars can not have abstract class types 13882 FD->setInvalidDecl(); 13883 } 13884 if (Record && FDTTy->getDecl()->hasObjectMember()) 13885 Record->setHasObjectMember(true); 13886 if (Record && FDTTy->getDecl()->hasVolatileMember()) 13887 Record->setHasVolatileMember(true); 13888 } else if (FDTy->isObjCObjectType()) { 13889 /// A field cannot be an Objective-c object 13890 Diag(FD->getLocation(), diag::err_statically_allocated_object) 13891 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 13892 QualType T = Context.getObjCObjectPointerType(FD->getType()); 13893 FD->setType(T); 13894 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 13895 (!getLangOpts().CPlusPlus || Record->isUnion())) { 13896 // It's an error in ARC if a field has lifetime. 13897 // We don't want to report this in a system header, though, 13898 // so we just make the field unavailable. 13899 // FIXME: that's really not sufficient; we need to make the type 13900 // itself invalid to, say, initialize or copy. 13901 QualType T = FD->getType(); 13902 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 13903 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 13904 SourceLocation loc = FD->getLocation(); 13905 if (getSourceManager().isInSystemHeader(loc)) { 13906 if (!FD->hasAttr<UnavailableAttr>()) { 13907 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13908 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 13909 } 13910 } else { 13911 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 13912 << T->isBlockPointerType() << Record->getTagKind(); 13913 } 13914 ARCErrReported = true; 13915 } 13916 } else if (getLangOpts().ObjC1 && 13917 getLangOpts().getGC() != LangOptions::NonGC && 13918 Record && !Record->hasObjectMember()) { 13919 if (FD->getType()->isObjCObjectPointerType() || 13920 FD->getType().isObjCGCStrong()) 13921 Record->setHasObjectMember(true); 13922 else if (Context.getAsArrayType(FD->getType())) { 13923 QualType BaseType = Context.getBaseElementType(FD->getType()); 13924 if (BaseType->isRecordType() && 13925 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 13926 Record->setHasObjectMember(true); 13927 else if (BaseType->isObjCObjectPointerType() || 13928 BaseType.isObjCGCStrong()) 13929 Record->setHasObjectMember(true); 13930 } 13931 } 13932 if (Record && FD->getType().isVolatileQualified()) 13933 Record->setHasVolatileMember(true); 13934 // Keep track of the number of named members. 13935 if (FD->getIdentifier()) 13936 ++NumNamedMembers; 13937 } 13938 13939 // Okay, we successfully defined 'Record'. 13940 if (Record) { 13941 bool Completed = false; 13942 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 13943 if (!CXXRecord->isInvalidDecl()) { 13944 // Set access bits correctly on the directly-declared conversions. 13945 for (CXXRecordDecl::conversion_iterator 13946 I = CXXRecord->conversion_begin(), 13947 E = CXXRecord->conversion_end(); I != E; ++I) 13948 I.setAccess((*I)->getAccess()); 13949 } 13950 13951 if (!CXXRecord->isDependentType()) { 13952 if (CXXRecord->hasUserDeclaredDestructor()) { 13953 // Adjust user-defined destructor exception spec. 13954 if (getLangOpts().CPlusPlus11) 13955 AdjustDestructorExceptionSpec(CXXRecord, 13956 CXXRecord->getDestructor()); 13957 } 13958 13959 if (!CXXRecord->isInvalidDecl()) { 13960 // Add any implicitly-declared members to this class. 13961 AddImplicitlyDeclaredMembersToClass(CXXRecord); 13962 13963 // If we have virtual base classes, we may end up finding multiple 13964 // final overriders for a given virtual function. Check for this 13965 // problem now. 13966 if (CXXRecord->getNumVBases()) { 13967 CXXFinalOverriderMap FinalOverriders; 13968 CXXRecord->getFinalOverriders(FinalOverriders); 13969 13970 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 13971 MEnd = FinalOverriders.end(); 13972 M != MEnd; ++M) { 13973 for (OverridingMethods::iterator SO = M->second.begin(), 13974 SOEnd = M->second.end(); 13975 SO != SOEnd; ++SO) { 13976 assert(SO->second.size() > 0 && 13977 "Virtual function without overridding functions?"); 13978 if (SO->second.size() == 1) 13979 continue; 13980 13981 // C++ [class.virtual]p2: 13982 // In a derived class, if a virtual member function of a base 13983 // class subobject has more than one final overrider the 13984 // program is ill-formed. 13985 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 13986 << (const NamedDecl *)M->first << Record; 13987 Diag(M->first->getLocation(), 13988 diag::note_overridden_virtual_function); 13989 for (OverridingMethods::overriding_iterator 13990 OM = SO->second.begin(), 13991 OMEnd = SO->second.end(); 13992 OM != OMEnd; ++OM) 13993 Diag(OM->Method->getLocation(), diag::note_final_overrider) 13994 << (const NamedDecl *)M->first << OM->Method->getParent(); 13995 13996 Record->setInvalidDecl(); 13997 } 13998 } 13999 CXXRecord->completeDefinition(&FinalOverriders); 14000 Completed = true; 14001 } 14002 } 14003 } 14004 } 14005 14006 if (!Completed) 14007 Record->completeDefinition(); 14008 14009 if (Record->hasAttrs()) { 14010 CheckAlignasUnderalignment(Record); 14011 14012 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14013 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14014 IA->getRange(), IA->getBestCase(), 14015 IA->getSemanticSpelling()); 14016 } 14017 14018 // Check if the structure/union declaration is a type that can have zero 14019 // size in C. For C this is a language extension, for C++ it may cause 14020 // compatibility problems. 14021 bool CheckForZeroSize; 14022 if (!getLangOpts().CPlusPlus) { 14023 CheckForZeroSize = true; 14024 } else { 14025 // For C++ filter out types that cannot be referenced in C code. 14026 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14027 CheckForZeroSize = 14028 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14029 !CXXRecord->isDependentType() && 14030 CXXRecord->isCLike(); 14031 } 14032 if (CheckForZeroSize) { 14033 bool ZeroSize = true; 14034 bool IsEmpty = true; 14035 unsigned NonBitFields = 0; 14036 for (RecordDecl::field_iterator I = Record->field_begin(), 14037 E = Record->field_end(); 14038 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14039 IsEmpty = false; 14040 if (I->isUnnamedBitfield()) { 14041 if (I->getBitWidthValue(Context) > 0) 14042 ZeroSize = false; 14043 } else { 14044 ++NonBitFields; 14045 QualType FieldType = I->getType(); 14046 if (FieldType->isIncompleteType() || 14047 !Context.getTypeSizeInChars(FieldType).isZero()) 14048 ZeroSize = false; 14049 } 14050 } 14051 14052 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14053 // allowed in C++, but warn if its declaration is inside 14054 // extern "C" block. 14055 if (ZeroSize) { 14056 Diag(RecLoc, getLangOpts().CPlusPlus ? 14057 diag::warn_zero_size_struct_union_in_extern_c : 14058 diag::warn_zero_size_struct_union_compat) 14059 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14060 } 14061 14062 // Structs without named members are extension in C (C99 6.7.2.1p7), 14063 // but are accepted by GCC. 14064 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14065 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14066 diag::ext_no_named_members_in_struct_union) 14067 << Record->isUnion(); 14068 } 14069 } 14070 } else { 14071 ObjCIvarDecl **ClsFields = 14072 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14073 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14074 ID->setEndOfDefinitionLoc(RBrac); 14075 // Add ivar's to class's DeclContext. 14076 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14077 ClsFields[i]->setLexicalDeclContext(ID); 14078 ID->addDecl(ClsFields[i]); 14079 } 14080 // Must enforce the rule that ivars in the base classes may not be 14081 // duplicates. 14082 if (ID->getSuperClass()) 14083 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 14084 } else if (ObjCImplementationDecl *IMPDecl = 14085 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14086 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 14087 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 14088 // Ivar declared in @implementation never belongs to the implementation. 14089 // Only it is in implementation's lexical context. 14090 ClsFields[I]->setLexicalDeclContext(IMPDecl); 14091 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 14092 IMPDecl->setIvarLBraceLoc(LBrac); 14093 IMPDecl->setIvarRBraceLoc(RBrac); 14094 } else if (ObjCCategoryDecl *CDecl = 14095 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14096 // case of ivars in class extension; all other cases have been 14097 // reported as errors elsewhere. 14098 // FIXME. Class extension does not have a LocEnd field. 14099 // CDecl->setLocEnd(RBrac); 14100 // Add ivar's to class extension's DeclContext. 14101 // Diagnose redeclaration of private ivars. 14102 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 14103 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14104 if (IDecl) { 14105 if (const ObjCIvarDecl *ClsIvar = 14106 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 14107 Diag(ClsFields[i]->getLocation(), 14108 diag::err_duplicate_ivar_declaration); 14109 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 14110 continue; 14111 } 14112 for (const auto *Ext : IDecl->known_extensions()) { 14113 if (const ObjCIvarDecl *ClsExtIvar 14114 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 14115 Diag(ClsFields[i]->getLocation(), 14116 diag::err_duplicate_ivar_declaration); 14117 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 14118 continue; 14119 } 14120 } 14121 } 14122 ClsFields[i]->setLexicalDeclContext(CDecl); 14123 CDecl->addDecl(ClsFields[i]); 14124 } 14125 CDecl->setIvarLBraceLoc(LBrac); 14126 CDecl->setIvarRBraceLoc(RBrac); 14127 } 14128 } 14129 14130 if (Attr) 14131 ProcessDeclAttributeList(S, Record, Attr); 14132 } 14133 14134 /// \brief Determine whether the given integral value is representable within 14135 /// the given type T. 14136 static bool isRepresentableIntegerValue(ASTContext &Context, 14137 llvm::APSInt &Value, 14138 QualType T) { 14139 assert(T->isIntegralType(Context) && "Integral type required!"); 14140 unsigned BitWidth = Context.getIntWidth(T); 14141 14142 if (Value.isUnsigned() || Value.isNonNegative()) { 14143 if (T->isSignedIntegerOrEnumerationType()) 14144 --BitWidth; 14145 return Value.getActiveBits() <= BitWidth; 14146 } 14147 return Value.getMinSignedBits() <= BitWidth; 14148 } 14149 14150 // \brief Given an integral type, return the next larger integral type 14151 // (or a NULL type of no such type exists). 14152 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 14153 // FIXME: Int128/UInt128 support, which also needs to be introduced into 14154 // enum checking below. 14155 assert(T->isIntegralType(Context) && "Integral type required!"); 14156 const unsigned NumTypes = 4; 14157 QualType SignedIntegralTypes[NumTypes] = { 14158 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 14159 }; 14160 QualType UnsignedIntegralTypes[NumTypes] = { 14161 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 14162 Context.UnsignedLongLongTy 14163 }; 14164 14165 unsigned BitWidth = Context.getTypeSize(T); 14166 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 14167 : UnsignedIntegralTypes; 14168 for (unsigned I = 0; I != NumTypes; ++I) 14169 if (Context.getTypeSize(Types[I]) > BitWidth) 14170 return Types[I]; 14171 14172 return QualType(); 14173 } 14174 14175 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 14176 EnumConstantDecl *LastEnumConst, 14177 SourceLocation IdLoc, 14178 IdentifierInfo *Id, 14179 Expr *Val) { 14180 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14181 llvm::APSInt EnumVal(IntWidth); 14182 QualType EltTy; 14183 14184 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 14185 Val = nullptr; 14186 14187 if (Val) 14188 Val = DefaultLvalueConversion(Val).get(); 14189 14190 if (Val) { 14191 if (Enum->isDependentType() || Val->isTypeDependent()) 14192 EltTy = Context.DependentTy; 14193 else { 14194 SourceLocation ExpLoc; 14195 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14196 !getLangOpts().MSVCCompat) { 14197 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14198 // constant-expression in the enumerator-definition shall be a converted 14199 // constant expression of the underlying type. 14200 EltTy = Enum->getIntegerType(); 14201 ExprResult Converted = 14202 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14203 CCEK_Enumerator); 14204 if (Converted.isInvalid()) 14205 Val = nullptr; 14206 else 14207 Val = Converted.get(); 14208 } else if (!Val->isValueDependent() && 14209 !(Val = VerifyIntegerConstantExpression(Val, 14210 &EnumVal).get())) { 14211 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14212 } else { 14213 if (Enum->isFixed()) { 14214 EltTy = Enum->getIntegerType(); 14215 14216 // In Obj-C and Microsoft mode, require the enumeration value to be 14217 // representable in the underlying type of the enumeration. In C++11, 14218 // we perform a non-narrowing conversion as part of converted constant 14219 // expression checking. 14220 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14221 if (getLangOpts().MSVCCompat) { 14222 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14223 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14224 } else 14225 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14226 } else 14227 Val = ImpCastExprToType(Val, EltTy, 14228 EltTy->isBooleanType() ? 14229 CK_IntegralToBoolean : CK_IntegralCast) 14230 .get(); 14231 } else if (getLangOpts().CPlusPlus) { 14232 // C++11 [dcl.enum]p5: 14233 // If the underlying type is not fixed, the type of each enumerator 14234 // is the type of its initializing value: 14235 // - If an initializer is specified for an enumerator, the 14236 // initializing value has the same type as the expression. 14237 EltTy = Val->getType(); 14238 } else { 14239 // C99 6.7.2.2p2: 14240 // The expression that defines the value of an enumeration constant 14241 // shall be an integer constant expression that has a value 14242 // representable as an int. 14243 14244 // Complain if the value is not representable in an int. 14245 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14246 Diag(IdLoc, diag::ext_enum_value_not_int) 14247 << EnumVal.toString(10) << Val->getSourceRange() 14248 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14249 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14250 // Force the type of the expression to 'int'. 14251 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14252 } 14253 EltTy = Val->getType(); 14254 } 14255 } 14256 } 14257 } 14258 14259 if (!Val) { 14260 if (Enum->isDependentType()) 14261 EltTy = Context.DependentTy; 14262 else if (!LastEnumConst) { 14263 // C++0x [dcl.enum]p5: 14264 // If the underlying type is not fixed, the type of each enumerator 14265 // is the type of its initializing value: 14266 // - If no initializer is specified for the first enumerator, the 14267 // initializing value has an unspecified integral type. 14268 // 14269 // GCC uses 'int' for its unspecified integral type, as does 14270 // C99 6.7.2.2p3. 14271 if (Enum->isFixed()) { 14272 EltTy = Enum->getIntegerType(); 14273 } 14274 else { 14275 EltTy = Context.IntTy; 14276 } 14277 } else { 14278 // Assign the last value + 1. 14279 EnumVal = LastEnumConst->getInitVal(); 14280 ++EnumVal; 14281 EltTy = LastEnumConst->getType(); 14282 14283 // Check for overflow on increment. 14284 if (EnumVal < LastEnumConst->getInitVal()) { 14285 // C++0x [dcl.enum]p5: 14286 // If the underlying type is not fixed, the type of each enumerator 14287 // is the type of its initializing value: 14288 // 14289 // - Otherwise the type of the initializing value is the same as 14290 // the type of the initializing value of the preceding enumerator 14291 // unless the incremented value is not representable in that type, 14292 // in which case the type is an unspecified integral type 14293 // sufficient to contain the incremented value. If no such type 14294 // exists, the program is ill-formed. 14295 QualType T = getNextLargerIntegralType(Context, EltTy); 14296 if (T.isNull() || Enum->isFixed()) { 14297 // There is no integral type larger enough to represent this 14298 // value. Complain, then allow the value to wrap around. 14299 EnumVal = LastEnumConst->getInitVal(); 14300 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 14301 ++EnumVal; 14302 if (Enum->isFixed()) 14303 // When the underlying type is fixed, this is ill-formed. 14304 Diag(IdLoc, diag::err_enumerator_wrapped) 14305 << EnumVal.toString(10) 14306 << EltTy; 14307 else 14308 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 14309 << EnumVal.toString(10); 14310 } else { 14311 EltTy = T; 14312 } 14313 14314 // Retrieve the last enumerator's value, extent that type to the 14315 // type that is supposed to be large enough to represent the incremented 14316 // value, then increment. 14317 EnumVal = LastEnumConst->getInitVal(); 14318 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14319 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 14320 ++EnumVal; 14321 14322 // If we're not in C++, diagnose the overflow of enumerator values, 14323 // which in C99 means that the enumerator value is not representable in 14324 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 14325 // permits enumerator values that are representable in some larger 14326 // integral type. 14327 if (!getLangOpts().CPlusPlus && !T.isNull()) 14328 Diag(IdLoc, diag::warn_enum_value_overflow); 14329 } else if (!getLangOpts().CPlusPlus && 14330 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14331 // Enforce C99 6.7.2.2p2 even when we compute the next value. 14332 Diag(IdLoc, diag::ext_enum_value_not_int) 14333 << EnumVal.toString(10) << 1; 14334 } 14335 } 14336 } 14337 14338 if (!EltTy->isDependentType()) { 14339 // Make the enumerator value match the signedness and size of the 14340 // enumerator's type. 14341 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 14342 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14343 } 14344 14345 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 14346 Val, EnumVal); 14347 } 14348 14349 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 14350 SourceLocation IILoc) { 14351 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 14352 !getLangOpts().CPlusPlus) 14353 return SkipBodyInfo(); 14354 14355 // We have an anonymous enum definition. Look up the first enumerator to 14356 // determine if we should merge the definition with an existing one and 14357 // skip the body. 14358 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 14359 ForRedeclaration); 14360 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 14361 if (!PrevECD) 14362 return SkipBodyInfo(); 14363 14364 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 14365 NamedDecl *Hidden; 14366 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 14367 SkipBodyInfo Skip; 14368 Skip.Previous = Hidden; 14369 return Skip; 14370 } 14371 14372 return SkipBodyInfo(); 14373 } 14374 14375 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 14376 SourceLocation IdLoc, IdentifierInfo *Id, 14377 AttributeList *Attr, 14378 SourceLocation EqualLoc, Expr *Val) { 14379 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 14380 EnumConstantDecl *LastEnumConst = 14381 cast_or_null<EnumConstantDecl>(lastEnumConst); 14382 14383 // The scope passed in may not be a decl scope. Zip up the scope tree until 14384 // we find one that is. 14385 S = getNonFieldDeclScope(S); 14386 14387 // Verify that there isn't already something declared with this name in this 14388 // scope. 14389 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 14390 ForRedeclaration); 14391 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14392 // Maybe we will complain about the shadowed template parameter. 14393 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 14394 // Just pretend that we didn't see the previous declaration. 14395 PrevDecl = nullptr; 14396 } 14397 14398 // C++ [class.mem]p15: 14399 // If T is the name of a class, then each of the following shall have a name 14400 // different from T: 14401 // - every enumerator of every member of class T that is an unscoped 14402 // enumerated type 14403 if (!TheEnumDecl->isScoped()) 14404 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 14405 DeclarationNameInfo(Id, IdLoc)); 14406 14407 EnumConstantDecl *New = 14408 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 14409 if (!New) 14410 return nullptr; 14411 14412 if (PrevDecl) { 14413 // When in C++, we may get a TagDecl with the same name; in this case the 14414 // enum constant will 'hide' the tag. 14415 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 14416 "Received TagDecl when not in C++!"); 14417 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 14418 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 14419 if (isa<EnumConstantDecl>(PrevDecl)) 14420 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 14421 else 14422 Diag(IdLoc, diag::err_redefinition) << Id; 14423 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14424 return nullptr; 14425 } 14426 } 14427 14428 // Process attributes. 14429 if (Attr) ProcessDeclAttributeList(S, New, Attr); 14430 14431 // Register this decl in the current scope stack. 14432 New->setAccess(TheEnumDecl->getAccess()); 14433 PushOnScopeChains(New, S); 14434 14435 ActOnDocumentableDecl(New); 14436 14437 return New; 14438 } 14439 14440 // Returns true when the enum initial expression does not trigger the 14441 // duplicate enum warning. A few common cases are exempted as follows: 14442 // Element2 = Element1 14443 // Element2 = Element1 + 1 14444 // Element2 = Element1 - 1 14445 // Where Element2 and Element1 are from the same enum. 14446 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 14447 Expr *InitExpr = ECD->getInitExpr(); 14448 if (!InitExpr) 14449 return true; 14450 InitExpr = InitExpr->IgnoreImpCasts(); 14451 14452 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 14453 if (!BO->isAdditiveOp()) 14454 return true; 14455 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 14456 if (!IL) 14457 return true; 14458 if (IL->getValue() != 1) 14459 return true; 14460 14461 InitExpr = BO->getLHS(); 14462 } 14463 14464 // This checks if the elements are from the same enum. 14465 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 14466 if (!DRE) 14467 return true; 14468 14469 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 14470 if (!EnumConstant) 14471 return true; 14472 14473 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 14474 Enum) 14475 return true; 14476 14477 return false; 14478 } 14479 14480 namespace { 14481 struct DupKey { 14482 int64_t val; 14483 bool isTombstoneOrEmptyKey; 14484 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 14485 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 14486 }; 14487 14488 static DupKey GetDupKey(const llvm::APSInt& Val) { 14489 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 14490 false); 14491 } 14492 14493 struct DenseMapInfoDupKey { 14494 static DupKey getEmptyKey() { return DupKey(0, true); } 14495 static DupKey getTombstoneKey() { return DupKey(1, true); } 14496 static unsigned getHashValue(const DupKey Key) { 14497 return (unsigned)(Key.val * 37); 14498 } 14499 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 14500 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 14501 LHS.val == RHS.val; 14502 } 14503 }; 14504 } // end anonymous namespace 14505 14506 // Emits a warning when an element is implicitly set a value that 14507 // a previous element has already been set to. 14508 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 14509 EnumDecl *Enum, 14510 QualType EnumType) { 14511 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 14512 return; 14513 // Avoid anonymous enums 14514 if (!Enum->getIdentifier()) 14515 return; 14516 14517 // Only check for small enums. 14518 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 14519 return; 14520 14521 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 14522 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 14523 14524 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 14525 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 14526 ValueToVectorMap; 14527 14528 DuplicatesVector DupVector; 14529 ValueToVectorMap EnumMap; 14530 14531 // Populate the EnumMap with all values represented by enum constants without 14532 // an initialier. 14533 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14534 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 14535 14536 // Null EnumConstantDecl means a previous diagnostic has been emitted for 14537 // this constant. Skip this enum since it may be ill-formed. 14538 if (!ECD) { 14539 return; 14540 } 14541 14542 if (ECD->getInitExpr()) 14543 continue; 14544 14545 DupKey Key = GetDupKey(ECD->getInitVal()); 14546 DeclOrVector &Entry = EnumMap[Key]; 14547 14548 // First time encountering this value. 14549 if (Entry.isNull()) 14550 Entry = ECD; 14551 } 14552 14553 // Create vectors for any values that has duplicates. 14554 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14555 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 14556 if (!ValidDuplicateEnum(ECD, Enum)) 14557 continue; 14558 14559 DupKey Key = GetDupKey(ECD->getInitVal()); 14560 14561 DeclOrVector& Entry = EnumMap[Key]; 14562 if (Entry.isNull()) 14563 continue; 14564 14565 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 14566 // Ensure constants are different. 14567 if (D == ECD) 14568 continue; 14569 14570 // Create new vector and push values onto it. 14571 ECDVector *Vec = new ECDVector(); 14572 Vec->push_back(D); 14573 Vec->push_back(ECD); 14574 14575 // Update entry to point to the duplicates vector. 14576 Entry = Vec; 14577 14578 // Store the vector somewhere we can consult later for quick emission of 14579 // diagnostics. 14580 DupVector.push_back(Vec); 14581 continue; 14582 } 14583 14584 ECDVector *Vec = Entry.get<ECDVector*>(); 14585 // Make sure constants are not added more than once. 14586 if (*Vec->begin() == ECD) 14587 continue; 14588 14589 Vec->push_back(ECD); 14590 } 14591 14592 // Emit diagnostics. 14593 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 14594 DupVectorEnd = DupVector.end(); 14595 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 14596 ECDVector *Vec = *DupVectorIter; 14597 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 14598 14599 // Emit warning for one enum constant. 14600 ECDVector::iterator I = Vec->begin(); 14601 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 14602 << (*I)->getName() << (*I)->getInitVal().toString(10) 14603 << (*I)->getSourceRange(); 14604 ++I; 14605 14606 // Emit one note for each of the remaining enum constants with 14607 // the same value. 14608 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 14609 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 14610 << (*I)->getName() << (*I)->getInitVal().toString(10) 14611 << (*I)->getSourceRange(); 14612 delete Vec; 14613 } 14614 } 14615 14616 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 14617 bool AllowMask) const { 14618 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 14619 assert(ED->isCompleteDefinition() && "expected enum definition"); 14620 14621 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 14622 llvm::APInt &FlagBits = R.first->second; 14623 14624 if (R.second) { 14625 for (auto *E : ED->enumerators()) { 14626 const auto &EVal = E->getInitVal(); 14627 // Only single-bit enumerators introduce new flag values. 14628 if (EVal.isPowerOf2()) 14629 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 14630 } 14631 } 14632 14633 // A value is in a flag enum if either its bits are a subset of the enum's 14634 // flag bits (the first condition) or we are allowing masks and the same is 14635 // true of its complement (the second condition). When masks are allowed, we 14636 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 14637 // 14638 // While it's true that any value could be used as a mask, the assumption is 14639 // that a mask will have all of the insignificant bits set. Anything else is 14640 // likely a logic error. 14641 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 14642 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 14643 } 14644 14645 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 14646 SourceLocation RBraceLoc, Decl *EnumDeclX, 14647 ArrayRef<Decl *> Elements, 14648 Scope *S, AttributeList *Attr) { 14649 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 14650 QualType EnumType = Context.getTypeDeclType(Enum); 14651 14652 if (Attr) 14653 ProcessDeclAttributeList(S, Enum, Attr); 14654 14655 if (Enum->isDependentType()) { 14656 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14657 EnumConstantDecl *ECD = 14658 cast_or_null<EnumConstantDecl>(Elements[i]); 14659 if (!ECD) continue; 14660 14661 ECD->setType(EnumType); 14662 } 14663 14664 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 14665 return; 14666 } 14667 14668 // TODO: If the result value doesn't fit in an int, it must be a long or long 14669 // long value. ISO C does not support this, but GCC does as an extension, 14670 // emit a warning. 14671 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14672 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 14673 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 14674 14675 // Verify that all the values are okay, compute the size of the values, and 14676 // reverse the list. 14677 unsigned NumNegativeBits = 0; 14678 unsigned NumPositiveBits = 0; 14679 14680 // Keep track of whether all elements have type int. 14681 bool AllElementsInt = true; 14682 14683 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14684 EnumConstantDecl *ECD = 14685 cast_or_null<EnumConstantDecl>(Elements[i]); 14686 if (!ECD) continue; // Already issued a diagnostic. 14687 14688 const llvm::APSInt &InitVal = ECD->getInitVal(); 14689 14690 // Keep track of the size of positive and negative values. 14691 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 14692 NumPositiveBits = std::max(NumPositiveBits, 14693 (unsigned)InitVal.getActiveBits()); 14694 else 14695 NumNegativeBits = std::max(NumNegativeBits, 14696 (unsigned)InitVal.getMinSignedBits()); 14697 14698 // Keep track of whether every enum element has type int (very commmon). 14699 if (AllElementsInt) 14700 AllElementsInt = ECD->getType() == Context.IntTy; 14701 } 14702 14703 // Figure out the type that should be used for this enum. 14704 QualType BestType; 14705 unsigned BestWidth; 14706 14707 // C++0x N3000 [conv.prom]p3: 14708 // An rvalue of an unscoped enumeration type whose underlying 14709 // type is not fixed can be converted to an rvalue of the first 14710 // of the following types that can represent all the values of 14711 // the enumeration: int, unsigned int, long int, unsigned long 14712 // int, long long int, or unsigned long long int. 14713 // C99 6.4.4.3p2: 14714 // An identifier declared as an enumeration constant has type int. 14715 // The C99 rule is modified by a gcc extension 14716 QualType BestPromotionType; 14717 14718 bool Packed = Enum->hasAttr<PackedAttr>(); 14719 // -fshort-enums is the equivalent to specifying the packed attribute on all 14720 // enum definitions. 14721 if (LangOpts.ShortEnums) 14722 Packed = true; 14723 14724 if (Enum->isFixed()) { 14725 BestType = Enum->getIntegerType(); 14726 if (BestType->isPromotableIntegerType()) 14727 BestPromotionType = Context.getPromotedIntegerType(BestType); 14728 else 14729 BestPromotionType = BestType; 14730 14731 BestWidth = Context.getIntWidth(BestType); 14732 } 14733 else if (NumNegativeBits) { 14734 // If there is a negative value, figure out the smallest integer type (of 14735 // int/long/longlong) that fits. 14736 // If it's packed, check also if it fits a char or a short. 14737 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 14738 BestType = Context.SignedCharTy; 14739 BestWidth = CharWidth; 14740 } else if (Packed && NumNegativeBits <= ShortWidth && 14741 NumPositiveBits < ShortWidth) { 14742 BestType = Context.ShortTy; 14743 BestWidth = ShortWidth; 14744 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 14745 BestType = Context.IntTy; 14746 BestWidth = IntWidth; 14747 } else { 14748 BestWidth = Context.getTargetInfo().getLongWidth(); 14749 14750 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 14751 BestType = Context.LongTy; 14752 } else { 14753 BestWidth = Context.getTargetInfo().getLongLongWidth(); 14754 14755 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 14756 Diag(Enum->getLocation(), diag::ext_enum_too_large); 14757 BestType = Context.LongLongTy; 14758 } 14759 } 14760 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 14761 } else { 14762 // If there is no negative value, figure out the smallest type that fits 14763 // all of the enumerator values. 14764 // If it's packed, check also if it fits a char or a short. 14765 if (Packed && NumPositiveBits <= CharWidth) { 14766 BestType = Context.UnsignedCharTy; 14767 BestPromotionType = Context.IntTy; 14768 BestWidth = CharWidth; 14769 } else if (Packed && NumPositiveBits <= ShortWidth) { 14770 BestType = Context.UnsignedShortTy; 14771 BestPromotionType = Context.IntTy; 14772 BestWidth = ShortWidth; 14773 } else if (NumPositiveBits <= IntWidth) { 14774 BestType = Context.UnsignedIntTy; 14775 BestWidth = IntWidth; 14776 BestPromotionType 14777 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14778 ? Context.UnsignedIntTy : Context.IntTy; 14779 } else if (NumPositiveBits <= 14780 (BestWidth = Context.getTargetInfo().getLongWidth())) { 14781 BestType = Context.UnsignedLongTy; 14782 BestPromotionType 14783 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14784 ? Context.UnsignedLongTy : Context.LongTy; 14785 } else { 14786 BestWidth = Context.getTargetInfo().getLongLongWidth(); 14787 assert(NumPositiveBits <= BestWidth && 14788 "How could an initializer get larger than ULL?"); 14789 BestType = Context.UnsignedLongLongTy; 14790 BestPromotionType 14791 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14792 ? Context.UnsignedLongLongTy : Context.LongLongTy; 14793 } 14794 } 14795 14796 // Loop over all of the enumerator constants, changing their types to match 14797 // the type of the enum if needed. 14798 for (auto *D : Elements) { 14799 auto *ECD = cast_or_null<EnumConstantDecl>(D); 14800 if (!ECD) continue; // Already issued a diagnostic. 14801 14802 // Standard C says the enumerators have int type, but we allow, as an 14803 // extension, the enumerators to be larger than int size. If each 14804 // enumerator value fits in an int, type it as an int, otherwise type it the 14805 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 14806 // that X has type 'int', not 'unsigned'. 14807 14808 // Determine whether the value fits into an int. 14809 llvm::APSInt InitVal = ECD->getInitVal(); 14810 14811 // If it fits into an integer type, force it. Otherwise force it to match 14812 // the enum decl type. 14813 QualType NewTy; 14814 unsigned NewWidth; 14815 bool NewSign; 14816 if (!getLangOpts().CPlusPlus && 14817 !Enum->isFixed() && 14818 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 14819 NewTy = Context.IntTy; 14820 NewWidth = IntWidth; 14821 NewSign = true; 14822 } else if (ECD->getType() == BestType) { 14823 // Already the right type! 14824 if (getLangOpts().CPlusPlus) 14825 // C++ [dcl.enum]p4: Following the closing brace of an 14826 // enum-specifier, each enumerator has the type of its 14827 // enumeration. 14828 ECD->setType(EnumType); 14829 continue; 14830 } else { 14831 NewTy = BestType; 14832 NewWidth = BestWidth; 14833 NewSign = BestType->isSignedIntegerOrEnumerationType(); 14834 } 14835 14836 // Adjust the APSInt value. 14837 InitVal = InitVal.extOrTrunc(NewWidth); 14838 InitVal.setIsSigned(NewSign); 14839 ECD->setInitVal(InitVal); 14840 14841 // Adjust the Expr initializer and type. 14842 if (ECD->getInitExpr() && 14843 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 14844 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 14845 CK_IntegralCast, 14846 ECD->getInitExpr(), 14847 /*base paths*/ nullptr, 14848 VK_RValue)); 14849 if (getLangOpts().CPlusPlus) 14850 // C++ [dcl.enum]p4: Following the closing brace of an 14851 // enum-specifier, each enumerator has the type of its 14852 // enumeration. 14853 ECD->setType(EnumType); 14854 else 14855 ECD->setType(NewTy); 14856 } 14857 14858 Enum->completeDefinition(BestType, BestPromotionType, 14859 NumPositiveBits, NumNegativeBits); 14860 14861 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 14862 14863 if (Enum->hasAttr<FlagEnumAttr>()) { 14864 for (Decl *D : Elements) { 14865 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 14866 if (!ECD) continue; // Already issued a diagnostic. 14867 14868 llvm::APSInt InitVal = ECD->getInitVal(); 14869 if (InitVal != 0 && !InitVal.isPowerOf2() && 14870 !IsValueInFlagEnum(Enum, InitVal, true)) 14871 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 14872 << ECD << Enum; 14873 } 14874 } 14875 14876 // Now that the enum type is defined, ensure it's not been underaligned. 14877 if (Enum->hasAttrs()) 14878 CheckAlignasUnderalignment(Enum); 14879 } 14880 14881 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 14882 SourceLocation StartLoc, 14883 SourceLocation EndLoc) { 14884 StringLiteral *AsmString = cast<StringLiteral>(expr); 14885 14886 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 14887 AsmString, StartLoc, 14888 EndLoc); 14889 CurContext->addDecl(New); 14890 return New; 14891 } 14892 14893 static void checkModuleImportContext(Sema &S, Module *M, 14894 SourceLocation ImportLoc, DeclContext *DC, 14895 bool FromInclude = false) { 14896 SourceLocation ExternCLoc; 14897 14898 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 14899 switch (LSD->getLanguage()) { 14900 case LinkageSpecDecl::lang_c: 14901 if (ExternCLoc.isInvalid()) 14902 ExternCLoc = LSD->getLocStart(); 14903 break; 14904 case LinkageSpecDecl::lang_cxx: 14905 break; 14906 } 14907 DC = LSD->getParent(); 14908 } 14909 14910 while (isa<LinkageSpecDecl>(DC)) 14911 DC = DC->getParent(); 14912 14913 if (!isa<TranslationUnitDecl>(DC)) { 14914 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 14915 ? diag::ext_module_import_not_at_top_level_noop 14916 : diag::err_module_import_not_at_top_level_fatal) 14917 << M->getFullModuleName() << DC; 14918 S.Diag(cast<Decl>(DC)->getLocStart(), 14919 diag::note_module_import_not_at_top_level) << DC; 14920 } else if (!M->IsExternC && ExternCLoc.isValid()) { 14921 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 14922 << M->getFullModuleName(); 14923 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c); 14924 } 14925 } 14926 14927 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) { 14928 return checkModuleImportContext(*this, M, ImportLoc, CurContext); 14929 } 14930 14931 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 14932 SourceLocation ImportLoc, 14933 ModuleIdPath Path) { 14934 Module *Mod = 14935 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 14936 /*IsIncludeDirective=*/false); 14937 if (!Mod) 14938 return true; 14939 14940 VisibleModules.setVisible(Mod, ImportLoc); 14941 14942 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 14943 14944 // FIXME: we should support importing a submodule within a different submodule 14945 // of the same top-level module. Until we do, make it an error rather than 14946 // silently ignoring the import. 14947 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 14948 Diag(ImportLoc, getLangOpts().CompilingModule 14949 ? diag::err_module_self_import 14950 : diag::err_module_import_in_implementation) 14951 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 14952 14953 SmallVector<SourceLocation, 2> IdentifierLocs; 14954 Module *ModCheck = Mod; 14955 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 14956 // If we've run out of module parents, just drop the remaining identifiers. 14957 // We need the length to be consistent. 14958 if (!ModCheck) 14959 break; 14960 ModCheck = ModCheck->Parent; 14961 14962 IdentifierLocs.push_back(Path[I].second); 14963 } 14964 14965 ImportDecl *Import = ImportDecl::Create(Context, 14966 Context.getTranslationUnitDecl(), 14967 AtLoc.isValid()? AtLoc : ImportLoc, 14968 Mod, IdentifierLocs); 14969 Context.getTranslationUnitDecl()->addDecl(Import); 14970 return Import; 14971 } 14972 14973 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 14974 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 14975 14976 // Determine whether we're in the #include buffer for a module. The #includes 14977 // in that buffer do not qualify as module imports; they're just an 14978 // implementation detail of us building the module. 14979 // 14980 // FIXME: Should we even get ActOnModuleInclude calls for those? 14981 bool IsInModuleIncludes = 14982 TUKind == TU_Module && 14983 getSourceManager().isWrittenInMainFile(DirectiveLoc); 14984 14985 // Similarly, if we're in the implementation of a module, don't 14986 // synthesize an illegal module import. FIXME: Why not? 14987 bool ShouldAddImport = 14988 !IsInModuleIncludes && 14989 (getLangOpts().CompilingModule || 14990 getLangOpts().CurrentModule.empty() || 14991 getLangOpts().CurrentModule != Mod->getTopLevelModuleName()); 14992 14993 // If this module import was due to an inclusion directive, create an 14994 // implicit import declaration to capture it in the AST. 14995 if (ShouldAddImport) { 14996 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14997 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14998 DirectiveLoc, Mod, 14999 DirectiveLoc); 15000 TU->addDecl(ImportD); 15001 Consumer.HandleImplicitImportDecl(ImportD); 15002 } 15003 15004 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 15005 VisibleModules.setVisible(Mod, DirectiveLoc); 15006 } 15007 15008 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 15009 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 15010 15011 if (getLangOpts().ModulesLocalVisibility) 15012 VisibleModulesStack.push_back(std::move(VisibleModules)); 15013 VisibleModules.setVisible(Mod, DirectiveLoc); 15014 } 15015 15016 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) { 15017 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 15018 15019 if (getLangOpts().ModulesLocalVisibility) { 15020 VisibleModules = std::move(VisibleModulesStack.back()); 15021 VisibleModulesStack.pop_back(); 15022 VisibleModules.setVisible(Mod, DirectiveLoc); 15023 // Leaving a module hides namespace names, so our visible namespace cache 15024 // is now out of date. 15025 VisibleNamespaceCache.clear(); 15026 } 15027 } 15028 15029 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 15030 Module *Mod) { 15031 // Bail if we're not allowed to implicitly import a module here. 15032 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 15033 return; 15034 15035 // Create the implicit import declaration. 15036 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15037 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15038 Loc, Mod, Loc); 15039 TU->addDecl(ImportD); 15040 Consumer.HandleImplicitImportDecl(ImportD); 15041 15042 // Make the module visible. 15043 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 15044 VisibleModules.setVisible(Mod, Loc); 15045 } 15046 15047 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 15048 IdentifierInfo* AliasName, 15049 SourceLocation PragmaLoc, 15050 SourceLocation NameLoc, 15051 SourceLocation AliasNameLoc) { 15052 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 15053 LookupOrdinaryName); 15054 AsmLabelAttr *Attr = 15055 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 15056 15057 // If a declaration that: 15058 // 1) declares a function or a variable 15059 // 2) has external linkage 15060 // already exists, add a label attribute to it. 15061 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15062 if (isDeclExternC(PrevDecl)) 15063 PrevDecl->addAttr(Attr); 15064 else 15065 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 15066 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 15067 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 15068 } else 15069 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 15070 } 15071 15072 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 15073 SourceLocation PragmaLoc, 15074 SourceLocation NameLoc) { 15075 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 15076 15077 if (PrevDecl) { 15078 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 15079 } else { 15080 (void)WeakUndeclaredIdentifiers.insert( 15081 std::pair<IdentifierInfo*,WeakInfo> 15082 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 15083 } 15084 } 15085 15086 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 15087 IdentifierInfo* AliasName, 15088 SourceLocation PragmaLoc, 15089 SourceLocation NameLoc, 15090 SourceLocation AliasNameLoc) { 15091 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 15092 LookupOrdinaryName); 15093 WeakInfo W = WeakInfo(Name, NameLoc); 15094 15095 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15096 if (!PrevDecl->hasAttr<AliasAttr>()) 15097 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 15098 DeclApplyPragmaWeak(TUScope, ND, W); 15099 } else { 15100 (void)WeakUndeclaredIdentifiers.insert( 15101 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 15102 } 15103 } 15104 15105 Decl *Sema::getObjCDeclContext() const { 15106 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 15107 } 15108 15109 AvailabilityResult Sema::getCurContextAvailability() const { 15110 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 15111 if (!D) 15112 return AR_Available; 15113 15114 // If we are within an Objective-C method, we should consult 15115 // both the availability of the method as well as the 15116 // enclosing class. If the class is (say) deprecated, 15117 // the entire method is considered deprecated from the 15118 // purpose of checking if the current context is deprecated. 15119 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 15120 AvailabilityResult R = MD->getAvailability(); 15121 if (R != AR_Available) 15122 return R; 15123 D = MD->getClassInterface(); 15124 } 15125 // If we are within an Objective-c @implementation, it 15126 // gets the same availability context as the @interface. 15127 else if (const ObjCImplementationDecl *ID = 15128 dyn_cast<ObjCImplementationDecl>(D)) { 15129 D = ID->getClassInterface(); 15130 } 15131 // Recover from user error. 15132 return D ? D->getAvailability() : AR_Available; 15133 } 15134