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/Parse/ParseDiagnostic.h" 37 #include "clang/Sema/CXXFieldCollector.h" 38 #include "clang/Sema/DeclSpec.h" 39 #include "clang/Sema/DelayedDiagnostic.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 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 } 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 return true; 115 116 case tok::annot_typename: 117 case tok::kw_char16_t: 118 case tok::kw_char32_t: 119 case tok::kw_typeof: 120 case tok::annot_decltype: 121 case tok::kw_decltype: 122 return getLangOpts().CPlusPlus; 123 124 default: 125 break; 126 } 127 128 return false; 129 } 130 131 namespace { 132 enum class UnqualifiedTypeNameLookupResult { 133 NotFound, 134 FoundNonType, 135 FoundType 136 }; 137 } // namespace 138 139 /// \brief Tries to perform unqualified lookup of the type decls in bases for 140 /// dependent class. 141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 142 /// type decl, \a FoundType if only type decls are found. 143 static UnqualifiedTypeNameLookupResult 144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 145 SourceLocation NameLoc, 146 const CXXRecordDecl *RD) { 147 if (!RD->hasDefinition()) 148 return UnqualifiedTypeNameLookupResult::NotFound; 149 // Look for type decls in base classes. 150 UnqualifiedTypeNameLookupResult FoundTypeDecl = 151 UnqualifiedTypeNameLookupResult::NotFound; 152 for (const auto &Base : RD->bases()) { 153 const CXXRecordDecl *BaseRD = nullptr; 154 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 155 BaseRD = BaseTT->getAsCXXRecordDecl(); 156 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 157 // Look for type decls in dependent base classes that have known primary 158 // templates. 159 if (!TST || !TST->isDependentType()) 160 continue; 161 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 162 if (!TD) 163 continue; 164 auto *BasePrimaryTemplate = 165 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl()); 166 if (!BasePrimaryTemplate) 167 continue; 168 BaseRD = BasePrimaryTemplate; 169 } 170 if (BaseRD) { 171 for (NamedDecl *ND : BaseRD->lookup(&II)) { 172 if (!isa<TypeDecl>(ND)) 173 return UnqualifiedTypeNameLookupResult::FoundNonType; 174 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 175 } 176 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 177 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 178 case UnqualifiedTypeNameLookupResult::FoundNonType: 179 return UnqualifiedTypeNameLookupResult::FoundNonType; 180 case UnqualifiedTypeNameLookupResult::FoundType: 181 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 182 break; 183 case UnqualifiedTypeNameLookupResult::NotFound: 184 break; 185 } 186 } 187 } 188 } 189 190 return FoundTypeDecl; 191 } 192 193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 194 const IdentifierInfo &II, 195 SourceLocation NameLoc) { 196 // Lookup in the parent class template context, if any. 197 const CXXRecordDecl *RD = nullptr; 198 UnqualifiedTypeNameLookupResult FoundTypeDecl = 199 UnqualifiedTypeNameLookupResult::NotFound; 200 for (DeclContext *DC = S.CurContext; 201 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 202 DC = DC->getParent()) { 203 // Look for type decls in dependent base classes that have known primary 204 // templates. 205 RD = dyn_cast<CXXRecordDecl>(DC); 206 if (RD && RD->getDescribedClassTemplate()) 207 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 208 } 209 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 210 return ParsedType(); 211 212 // We found some types in dependent base classes. Recover as if the user 213 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 214 // lookup during template instantiation. 215 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 216 217 ASTContext &Context = S.Context; 218 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 219 cast<Type>(Context.getRecordType(RD))); 220 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 221 222 CXXScopeSpec SS; 223 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 224 225 TypeLocBuilder Builder; 226 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 227 DepTL.setNameLoc(NameLoc); 228 DepTL.setElaboratedKeywordLoc(SourceLocation()); 229 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 230 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 231 } 232 233 /// \brief If the identifier refers to a type name within this scope, 234 /// return the declaration of that type. 235 /// 236 /// This routine performs ordinary name lookup of the identifier II 237 /// within the given scope, with optional C++ scope specifier SS, to 238 /// determine whether the name refers to a type. If so, returns an 239 /// opaque pointer (actually a QualType) corresponding to that 240 /// type. Otherwise, returns NULL. 241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 242 Scope *S, CXXScopeSpec *SS, 243 bool isClassName, bool HasTrailingDot, 244 ParsedType ObjectTypePtr, 245 bool IsCtorOrDtorName, 246 bool WantNontrivialTypeSourceInfo, 247 IdentifierInfo **CorrectedII) { 248 // Determine where we will perform name lookup. 249 DeclContext *LookupCtx = nullptr; 250 if (ObjectTypePtr) { 251 QualType ObjectType = ObjectTypePtr.get(); 252 if (ObjectType->isRecordType()) 253 LookupCtx = computeDeclContext(ObjectType); 254 } else if (SS && SS->isNotEmpty()) { 255 LookupCtx = computeDeclContext(*SS, false); 256 257 if (!LookupCtx) { 258 if (isDependentScopeSpecifier(*SS)) { 259 // C++ [temp.res]p3: 260 // A qualified-id that refers to a type and in which the 261 // nested-name-specifier depends on a template-parameter (14.6.2) 262 // shall be prefixed by the keyword typename to indicate that the 263 // qualified-id denotes a type, forming an 264 // elaborated-type-specifier (7.1.5.3). 265 // 266 // We therefore do not perform any name lookup if the result would 267 // refer to a member of an unknown specialization. 268 if (!isClassName && !IsCtorOrDtorName) 269 return ParsedType(); 270 271 // We know from the grammar that this name refers to a type, 272 // so build a dependent node to describe the type. 273 if (WantNontrivialTypeSourceInfo) 274 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 275 276 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 277 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 278 II, NameLoc); 279 return ParsedType::make(T); 280 } 281 282 return ParsedType(); 283 } 284 285 if (!LookupCtx->isDependentContext() && 286 RequireCompleteDeclContext(*SS, LookupCtx)) 287 return ParsedType(); 288 } 289 290 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 291 // lookup for class-names. 292 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 293 LookupOrdinaryName; 294 LookupResult Result(*this, &II, NameLoc, Kind); 295 if (LookupCtx) { 296 // Perform "qualified" name lookup into the declaration context we 297 // computed, which is either the type of the base of a member access 298 // expression or the declaration context associated with a prior 299 // nested-name-specifier. 300 LookupQualifiedName(Result, LookupCtx); 301 302 if (ObjectTypePtr && Result.empty()) { 303 // C++ [basic.lookup.classref]p3: 304 // If the unqualified-id is ~type-name, the type-name is looked up 305 // in the context of the entire postfix-expression. If the type T of 306 // the object expression is of a class type C, the type-name is also 307 // looked up in the scope of class C. At least one of the lookups shall 308 // find a name that refers to (possibly cv-qualified) T. 309 LookupName(Result, S); 310 } 311 } else { 312 // Perform unqualified name lookup. 313 LookupName(Result, S); 314 315 // For unqualified lookup in a class template in MSVC mode, look into 316 // dependent base classes where the primary class template is known. 317 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 318 if (ParsedType TypeInBase = 319 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 320 return TypeInBase; 321 } 322 } 323 324 NamedDecl *IIDecl = nullptr; 325 switch (Result.getResultKind()) { 326 case LookupResult::NotFound: 327 case LookupResult::NotFoundInCurrentInstantiation: 328 if (CorrectedII) { 329 TypoCorrection Correction = CorrectTypo( 330 Result.getLookupNameInfo(), Kind, S, SS, 331 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName), 332 CTK_ErrorRecovery); 333 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 334 TemplateTy Template; 335 bool MemberOfUnknownSpecialization; 336 UnqualifiedId TemplateName; 337 TemplateName.setIdentifier(NewII, NameLoc); 338 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 339 CXXScopeSpec NewSS, *NewSSPtr = SS; 340 if (SS && NNS) { 341 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 342 NewSSPtr = &NewSS; 343 } 344 if (Correction && (NNS || NewII != &II) && 345 // Ignore a correction to a template type as the to-be-corrected 346 // identifier is not a template (typo correction for template names 347 // is handled elsewhere). 348 !(getLangOpts().CPlusPlus && NewSSPtr && 349 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 350 false, Template, MemberOfUnknownSpecialization))) { 351 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 352 isClassName, HasTrailingDot, ObjectTypePtr, 353 IsCtorOrDtorName, 354 WantNontrivialTypeSourceInfo); 355 if (Ty) { 356 diagnoseTypo(Correction, 357 PDiag(diag::err_unknown_type_or_class_name_suggest) 358 << Result.getLookupName() << isClassName); 359 if (SS && NNS) 360 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 361 *CorrectedII = NewII; 362 return Ty; 363 } 364 } 365 } 366 // If typo correction failed or was not performed, fall through 367 case LookupResult::FoundOverloaded: 368 case LookupResult::FoundUnresolvedValue: 369 Result.suppressDiagnostics(); 370 return ParsedType(); 371 372 case LookupResult::Ambiguous: 373 // Recover from type-hiding ambiguities by hiding the type. We'll 374 // do the lookup again when looking for an object, and we can 375 // diagnose the error then. If we don't do this, then the error 376 // about hiding the type will be immediately followed by an error 377 // that only makes sense if the identifier was treated like a type. 378 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 379 Result.suppressDiagnostics(); 380 return ParsedType(); 381 } 382 383 // Look to see if we have a type anywhere in the list of results. 384 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 385 Res != ResEnd; ++Res) { 386 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 387 if (!IIDecl || 388 (*Res)->getLocation().getRawEncoding() < 389 IIDecl->getLocation().getRawEncoding()) 390 IIDecl = *Res; 391 } 392 } 393 394 if (!IIDecl) { 395 // None of the entities we found is a type, so there is no way 396 // to even assume that the result is a type. In this case, don't 397 // complain about the ambiguity. The parser will either try to 398 // perform this lookup again (e.g., as an object name), which 399 // will produce the ambiguity, or will complain that it expected 400 // a type name. 401 Result.suppressDiagnostics(); 402 return ParsedType(); 403 } 404 405 // We found a type within the ambiguous lookup; diagnose the 406 // ambiguity and then return that type. This might be the right 407 // answer, or it might not be, but it suppresses any attempt to 408 // perform the name lookup again. 409 break; 410 411 case LookupResult::Found: 412 IIDecl = Result.getFoundDecl(); 413 break; 414 } 415 416 assert(IIDecl && "Didn't find decl"); 417 418 QualType T; 419 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 420 DiagnoseUseOfDecl(IIDecl, NameLoc); 421 422 T = Context.getTypeDeclType(TD); 423 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 424 425 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 426 // constructor or destructor name (in such a case, the scope specifier 427 // will be attached to the enclosing Expr or Decl node). 428 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 429 if (WantNontrivialTypeSourceInfo) { 430 // Construct a type with type-source information. 431 TypeLocBuilder Builder; 432 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 433 434 T = getElaboratedType(ETK_None, *SS, T); 435 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 436 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 437 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 438 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 439 } else { 440 T = getElaboratedType(ETK_None, *SS, T); 441 } 442 } 443 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 444 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 445 if (!HasTrailingDot) 446 T = Context.getObjCInterfaceType(IDecl); 447 } 448 449 if (T.isNull()) { 450 // If it's not plausibly a type, suppress diagnostics. 451 Result.suppressDiagnostics(); 452 return ParsedType(); 453 } 454 return ParsedType::make(T); 455 } 456 457 // Builds a fake NNS for the given decl context. 458 static NestedNameSpecifier * 459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 460 for (;; DC = DC->getLookupParent()) { 461 DC = DC->getPrimaryContext(); 462 auto *ND = dyn_cast<NamespaceDecl>(DC); 463 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 464 return NestedNameSpecifier::Create(Context, nullptr, ND); 465 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 466 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 467 RD->getTypeForDecl()); 468 else if (isa<TranslationUnitDecl>(DC)) 469 return NestedNameSpecifier::GlobalSpecifier(Context); 470 } 471 llvm_unreachable("something isn't in TU scope?"); 472 } 473 474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 475 SourceLocation NameLoc) { 476 // Accepting an undeclared identifier as a default argument for a template 477 // type parameter is a Microsoft extension. 478 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 479 480 // Build a fake DependentNameType that will perform lookup into CurContext at 481 // instantiation time. The name specifier isn't dependent, so template 482 // instantiation won't transform it. It will retry the lookup, however. 483 NestedNameSpecifier *NNS = 484 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 485 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 486 487 // Build type location information. We synthesized the qualifier, so we have 488 // to build a fake NestedNameSpecifierLoc. 489 NestedNameSpecifierLocBuilder NNSLocBuilder; 490 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 491 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 492 493 TypeLocBuilder Builder; 494 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 495 DepTL.setNameLoc(NameLoc); 496 DepTL.setElaboratedKeywordLoc(SourceLocation()); 497 DepTL.setQualifierLoc(QualifierLoc); 498 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 499 } 500 501 /// isTagName() - This method is called *for error recovery purposes only* 502 /// to determine if the specified name is a valid tag name ("struct foo"). If 503 /// so, this returns the TST for the tag corresponding to it (TST_enum, 504 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 505 /// cases in C where the user forgot to specify the tag. 506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 507 // Do a tag name lookup in this scope. 508 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 509 LookupName(R, S, false); 510 R.suppressDiagnostics(); 511 if (R.getResultKind() == LookupResult::Found) 512 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 513 switch (TD->getTagKind()) { 514 case TTK_Struct: return DeclSpec::TST_struct; 515 case TTK_Interface: return DeclSpec::TST_interface; 516 case TTK_Union: return DeclSpec::TST_union; 517 case TTK_Class: return DeclSpec::TST_class; 518 case TTK_Enum: return DeclSpec::TST_enum; 519 } 520 } 521 522 return DeclSpec::TST_unspecified; 523 } 524 525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 527 /// then downgrade the missing typename error to a warning. 528 /// This is needed for MSVC compatibility; Example: 529 /// @code 530 /// template<class T> class A { 531 /// public: 532 /// typedef int TYPE; 533 /// }; 534 /// template<class T> class B : public A<T> { 535 /// public: 536 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 537 /// }; 538 /// @endcode 539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 540 if (CurContext->isRecord()) { 541 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 542 return true; 543 544 const Type *Ty = SS->getScopeRep()->getAsType(); 545 546 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 547 for (const auto &Base : RD->bases()) 548 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 549 return true; 550 return S->isFunctionPrototypeScope(); 551 } 552 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 553 } 554 555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 556 SourceLocation IILoc, 557 Scope *S, 558 CXXScopeSpec *SS, 559 ParsedType &SuggestedType, 560 bool AllowClassTemplates) { 561 // We don't have anything to suggest (yet). 562 SuggestedType = ParsedType(); 563 564 // There may have been a typo in the name of the type. Look up typo 565 // results, in case we have something that we can suggest. 566 if (TypoCorrection Corrected = 567 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 568 llvm::make_unique<TypeNameValidatorCCC>( 569 false, false, AllowClassTemplates), 570 CTK_ErrorRecovery)) { 571 if (Corrected.isKeyword()) { 572 // We corrected to a keyword. 573 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 574 II = Corrected.getCorrectionAsIdentifierInfo(); 575 } else { 576 // We found a similarly-named type or interface; suggest that. 577 if (!SS || !SS->isSet()) { 578 diagnoseTypo(Corrected, 579 PDiag(diag::err_unknown_typename_suggest) << II); 580 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 581 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 582 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 583 II->getName().equals(CorrectedStr); 584 diagnoseTypo(Corrected, 585 PDiag(diag::err_unknown_nested_typename_suggest) 586 << II << DC << DroppedSpecifier << SS->getRange()); 587 } else { 588 llvm_unreachable("could not have corrected a typo here"); 589 } 590 591 CXXScopeSpec tmpSS; 592 if (Corrected.getCorrectionSpecifier()) 593 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 594 SourceRange(IILoc)); 595 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 596 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 597 false, ParsedType(), 598 /*IsCtorOrDtorName=*/false, 599 /*NonTrivialTypeSourceInfo=*/true); 600 } 601 return; 602 } 603 604 if (getLangOpts().CPlusPlus) { 605 // See if II is a class template that the user forgot to pass arguments to. 606 UnqualifiedId Name; 607 Name.setIdentifier(II, IILoc); 608 CXXScopeSpec EmptySS; 609 TemplateTy TemplateResult; 610 bool MemberOfUnknownSpecialization; 611 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 612 Name, ParsedType(), true, TemplateResult, 613 MemberOfUnknownSpecialization) == TNK_Type_template) { 614 TemplateName TplName = TemplateResult.get(); 615 Diag(IILoc, diag::err_template_missing_args) << TplName; 616 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 617 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 618 << TplDecl->getTemplateParameters()->getSourceRange(); 619 } 620 return; 621 } 622 } 623 624 // FIXME: Should we move the logic that tries to recover from a missing tag 625 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 626 627 if (!SS || (!SS->isSet() && !SS->isInvalid())) 628 Diag(IILoc, diag::err_unknown_typename) << II; 629 else if (DeclContext *DC = computeDeclContext(*SS, false)) 630 Diag(IILoc, diag::err_typename_nested_not_found) 631 << II << DC << SS->getRange(); 632 else if (isDependentScopeSpecifier(*SS)) { 633 unsigned DiagID = diag::err_typename_missing; 634 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 635 DiagID = diag::ext_typename_missing; 636 637 Diag(SS->getRange().getBegin(), DiagID) 638 << SS->getScopeRep() << II->getName() 639 << SourceRange(SS->getRange().getBegin(), IILoc) 640 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 641 SuggestedType = ActOnTypenameType(S, SourceLocation(), 642 *SS, *II, IILoc).get(); 643 } else { 644 assert(SS && SS->isInvalid() && 645 "Invalid scope specifier has already been diagnosed"); 646 } 647 } 648 649 /// \brief Determine whether the given result set contains either a type name 650 /// or 651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 652 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 653 NextToken.is(tok::less); 654 655 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 656 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 657 return true; 658 659 if (CheckTemplate && isa<TemplateDecl>(*I)) 660 return true; 661 } 662 663 return false; 664 } 665 666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 667 Scope *S, CXXScopeSpec &SS, 668 IdentifierInfo *&Name, 669 SourceLocation NameLoc) { 670 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 671 SemaRef.LookupParsedName(R, S, &SS); 672 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 673 StringRef FixItTagName; 674 switch (Tag->getTagKind()) { 675 case TTK_Class: 676 FixItTagName = "class "; 677 break; 678 679 case TTK_Enum: 680 FixItTagName = "enum "; 681 break; 682 683 case TTK_Struct: 684 FixItTagName = "struct "; 685 break; 686 687 case TTK_Interface: 688 FixItTagName = "__interface "; 689 break; 690 691 case TTK_Union: 692 FixItTagName = "union "; 693 break; 694 } 695 696 StringRef TagName = FixItTagName.drop_back(); 697 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 698 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 699 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 700 701 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 702 I != IEnd; ++I) 703 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 704 << Name << TagName; 705 706 // Replace lookup results with just the tag decl. 707 Result.clear(Sema::LookupTagName); 708 SemaRef.LookupParsedName(Result, S, &SS); 709 return true; 710 } 711 712 return false; 713 } 714 715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 717 QualType T, SourceLocation NameLoc) { 718 ASTContext &Context = S.Context; 719 720 TypeLocBuilder Builder; 721 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 722 723 T = S.getElaboratedType(ETK_None, SS, T); 724 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 725 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 726 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 727 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 728 } 729 730 Sema::NameClassification 731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 732 SourceLocation NameLoc, const Token &NextToken, 733 bool IsAddressOfOperand, 734 std::unique_ptr<CorrectionCandidateCallback> CCC) { 735 DeclarationNameInfo NameInfo(Name, NameLoc); 736 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 737 738 if (NextToken.is(tok::coloncolon)) { 739 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 740 QualType(), false, SS, nullptr, false); 741 } 742 743 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 744 LookupParsedName(Result, S, &SS, !CurMethod); 745 746 // For unqualified lookup in a class template in MSVC mode, look into 747 // dependent base classes where the primary class template is known. 748 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 749 if (ParsedType TypeInBase = 750 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 751 return TypeInBase; 752 } 753 754 // Perform lookup for Objective-C instance variables (including automatically 755 // synthesized instance variables), if we're in an Objective-C method. 756 // FIXME: This lookup really, really needs to be folded in to the normal 757 // unqualified lookup mechanism. 758 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 759 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 760 if (E.get() || E.isInvalid()) 761 return E; 762 } 763 764 bool SecondTry = false; 765 bool IsFilteredTemplateName = false; 766 767 Corrected: 768 switch (Result.getResultKind()) { 769 case LookupResult::NotFound: 770 // If an unqualified-id is followed by a '(', then we have a function 771 // call. 772 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 773 // In C++, this is an ADL-only call. 774 // FIXME: Reference? 775 if (getLangOpts().CPlusPlus) 776 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 777 778 // C90 6.3.2.2: 779 // If the expression that precedes the parenthesized argument list in a 780 // function call consists solely of an identifier, and if no 781 // declaration is visible for this identifier, the identifier is 782 // implicitly declared exactly as if, in the innermost block containing 783 // the function call, the declaration 784 // 785 // extern int identifier (); 786 // 787 // appeared. 788 // 789 // We also allow this in C99 as an extension. 790 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 791 Result.addDecl(D); 792 Result.resolveKind(); 793 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 794 } 795 } 796 797 // In C, we first see whether there is a tag type by the same name, in 798 // which case it's likely that the user just forget to write "enum", 799 // "struct", or "union". 800 if (!getLangOpts().CPlusPlus && !SecondTry && 801 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 802 break; 803 } 804 805 // Perform typo correction to determine if there is another name that is 806 // close to this name. 807 if (!SecondTry && CCC) { 808 SecondTry = true; 809 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 810 Result.getLookupKind(), S, 811 &SS, std::move(CCC), 812 CTK_ErrorRecovery)) { 813 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 814 unsigned QualifiedDiag = diag::err_no_member_suggest; 815 816 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 817 NamedDecl *UnderlyingFirstDecl 818 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr; 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.is(tok::amp) || NextToken.is(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); 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 /// EnterDeclaratorContext - Used when we must lookup names in the context 1085 /// of a declarator's nested name specifier. 1086 /// 1087 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1088 // C++0x [basic.lookup.unqual]p13: 1089 // A name used in the definition of a static data member of class 1090 // X (after the qualified-id of the static member) is looked up as 1091 // if the name was used in a member function of X. 1092 // C++0x [basic.lookup.unqual]p14: 1093 // If a variable member of a namespace is defined outside of the 1094 // scope of its namespace then any name used in the definition of 1095 // the variable member (after the declarator-id) is looked up as 1096 // if the definition of the variable member occurred in its 1097 // namespace. 1098 // Both of these imply that we should push a scope whose context 1099 // is the semantic context of the declaration. We can't use 1100 // PushDeclContext here because that context is not necessarily 1101 // lexically contained in the current context. Fortunately, 1102 // the containing scope should have the appropriate information. 1103 1104 assert(!S->getEntity() && "scope already has entity"); 1105 1106 #ifndef NDEBUG 1107 Scope *Ancestor = S->getParent(); 1108 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1109 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1110 #endif 1111 1112 CurContext = DC; 1113 S->setEntity(DC); 1114 } 1115 1116 void Sema::ExitDeclaratorContext(Scope *S) { 1117 assert(S->getEntity() == CurContext && "Context imbalance!"); 1118 1119 // Switch back to the lexical context. The safety of this is 1120 // enforced by an assert in EnterDeclaratorContext. 1121 Scope *Ancestor = S->getParent(); 1122 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1123 CurContext = Ancestor->getEntity(); 1124 1125 // We don't need to do anything with the scope, which is going to 1126 // disappear. 1127 } 1128 1129 1130 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1131 // We assume that the caller has already called 1132 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1133 FunctionDecl *FD = D->getAsFunction(); 1134 if (!FD) 1135 return; 1136 1137 // Same implementation as PushDeclContext, but enters the context 1138 // from the lexical parent, rather than the top-level class. 1139 assert(CurContext == FD->getLexicalParent() && 1140 "The next DeclContext should be lexically contained in the current one."); 1141 CurContext = FD; 1142 S->setEntity(CurContext); 1143 1144 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1145 ParmVarDecl *Param = FD->getParamDecl(P); 1146 // If the parameter has an identifier, then add it to the scope 1147 if (Param->getIdentifier()) { 1148 S->AddDecl(Param); 1149 IdResolver.AddDecl(Param); 1150 } 1151 } 1152 } 1153 1154 1155 void Sema::ActOnExitFunctionContext() { 1156 // Same implementation as PopDeclContext, but returns to the lexical parent, 1157 // rather than the top-level class. 1158 assert(CurContext && "DeclContext imbalance!"); 1159 CurContext = CurContext->getLexicalParent(); 1160 assert(CurContext && "Popped translation unit!"); 1161 } 1162 1163 1164 /// \brief Determine whether we allow overloading of the function 1165 /// PrevDecl with another declaration. 1166 /// 1167 /// This routine determines whether overloading is possible, not 1168 /// whether some new function is actually an overload. It will return 1169 /// true in C++ (where we can always provide overloads) or, as an 1170 /// extension, in C when the previous function is already an 1171 /// overloaded function declaration or has the "overloadable" 1172 /// attribute. 1173 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1174 ASTContext &Context) { 1175 if (Context.getLangOpts().CPlusPlus) 1176 return true; 1177 1178 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1179 return true; 1180 1181 return (Previous.getResultKind() == LookupResult::Found 1182 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1183 } 1184 1185 /// Add this decl to the scope shadowed decl chains. 1186 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1187 // Move up the scope chain until we find the nearest enclosing 1188 // non-transparent context. The declaration will be introduced into this 1189 // scope. 1190 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1191 S = S->getParent(); 1192 1193 // Add scoped declarations into their context, so that they can be 1194 // found later. Declarations without a context won't be inserted 1195 // into any context. 1196 if (AddToContext) 1197 CurContext->addDecl(D); 1198 1199 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1200 // are function-local declarations. 1201 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1202 !D->getDeclContext()->getRedeclContext()->Equals( 1203 D->getLexicalDeclContext()->getRedeclContext()) && 1204 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1205 return; 1206 1207 // Template instantiations should also not be pushed into scope. 1208 if (isa<FunctionDecl>(D) && 1209 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1210 return; 1211 1212 // If this replaces anything in the current scope, 1213 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1214 IEnd = IdResolver.end(); 1215 for (; I != IEnd; ++I) { 1216 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1217 S->RemoveDecl(*I); 1218 IdResolver.RemoveDecl(*I); 1219 1220 // Should only need to replace one decl. 1221 break; 1222 } 1223 } 1224 1225 S->AddDecl(D); 1226 1227 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1228 // Implicitly-generated labels may end up getting generated in an order that 1229 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1230 // the label at the appropriate place in the identifier chain. 1231 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1232 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1233 if (IDC == CurContext) { 1234 if (!S->isDeclScope(*I)) 1235 continue; 1236 } else if (IDC->Encloses(CurContext)) 1237 break; 1238 } 1239 1240 IdResolver.InsertDeclAfter(I, D); 1241 } else { 1242 IdResolver.AddDecl(D); 1243 } 1244 } 1245 1246 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1247 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1248 TUScope->AddDecl(D); 1249 } 1250 1251 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1252 bool AllowInlineNamespace) { 1253 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1254 } 1255 1256 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1257 DeclContext *TargetDC = DC->getPrimaryContext(); 1258 do { 1259 if (DeclContext *ScopeDC = S->getEntity()) 1260 if (ScopeDC->getPrimaryContext() == TargetDC) 1261 return S; 1262 } while ((S = S->getParent())); 1263 1264 return nullptr; 1265 } 1266 1267 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1268 DeclContext*, 1269 ASTContext&); 1270 1271 /// Filters out lookup results that don't fall within the given scope 1272 /// as determined by isDeclInScope. 1273 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1274 bool ConsiderLinkage, 1275 bool AllowInlineNamespace) { 1276 LookupResult::Filter F = R.makeFilter(); 1277 while (F.hasNext()) { 1278 NamedDecl *D = F.next(); 1279 1280 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1281 continue; 1282 1283 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1284 continue; 1285 1286 F.erase(); 1287 } 1288 1289 F.done(); 1290 } 1291 1292 static bool isUsingDecl(NamedDecl *D) { 1293 return isa<UsingShadowDecl>(D) || 1294 isa<UnresolvedUsingTypenameDecl>(D) || 1295 isa<UnresolvedUsingValueDecl>(D); 1296 } 1297 1298 /// Removes using shadow declarations from the lookup results. 1299 static void RemoveUsingDecls(LookupResult &R) { 1300 LookupResult::Filter F = R.makeFilter(); 1301 while (F.hasNext()) 1302 if (isUsingDecl(F.next())) 1303 F.erase(); 1304 1305 F.done(); 1306 } 1307 1308 /// \brief Check for this common pattern: 1309 /// @code 1310 /// class S { 1311 /// S(const S&); // DO NOT IMPLEMENT 1312 /// void operator=(const S&); // DO NOT IMPLEMENT 1313 /// }; 1314 /// @endcode 1315 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1316 // FIXME: Should check for private access too but access is set after we get 1317 // the decl here. 1318 if (D->doesThisDeclarationHaveABody()) 1319 return false; 1320 1321 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1322 return CD->isCopyConstructor(); 1323 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1324 return Method->isCopyAssignmentOperator(); 1325 return false; 1326 } 1327 1328 // We need this to handle 1329 // 1330 // typedef struct { 1331 // void *foo() { return 0; } 1332 // } A; 1333 // 1334 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1335 // for example. If 'A', foo will have external linkage. If we have '*A', 1336 // foo will have no linkage. Since we can't know until we get to the end 1337 // of the typedef, this function finds out if D might have non-external linkage. 1338 // Callers should verify at the end of the TU if it D has external linkage or 1339 // not. 1340 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1341 const DeclContext *DC = D->getDeclContext(); 1342 while (!DC->isTranslationUnit()) { 1343 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1344 if (!RD->hasNameForLinkage()) 1345 return true; 1346 } 1347 DC = DC->getParent(); 1348 } 1349 1350 return !D->isExternallyVisible(); 1351 } 1352 1353 // FIXME: This needs to be refactored; some other isInMainFile users want 1354 // these semantics. 1355 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1356 if (S.TUKind != TU_Complete) 1357 return false; 1358 return S.SourceMgr.isInMainFile(Loc); 1359 } 1360 1361 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1362 assert(D); 1363 1364 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1365 return false; 1366 1367 // Ignore all entities declared within templates, and out-of-line definitions 1368 // of members of class templates. 1369 if (D->getDeclContext()->isDependentContext() || 1370 D->getLexicalDeclContext()->isDependentContext()) 1371 return false; 1372 1373 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1374 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1375 return false; 1376 1377 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1378 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1379 return false; 1380 } else { 1381 // 'static inline' functions are defined in headers; don't warn. 1382 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1383 return false; 1384 } 1385 1386 if (FD->doesThisDeclarationHaveABody() && 1387 Context.DeclMustBeEmitted(FD)) 1388 return false; 1389 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1390 // Constants and utility variables are defined in headers with internal 1391 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1392 // like "inline".) 1393 if (!isMainFileLoc(*this, VD->getLocation())) 1394 return false; 1395 1396 if (Context.DeclMustBeEmitted(VD)) 1397 return false; 1398 1399 if (VD->isStaticDataMember() && 1400 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1401 return false; 1402 } else { 1403 return false; 1404 } 1405 1406 // Only warn for unused decls internal to the translation unit. 1407 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1408 // for inline functions defined in the main source file, for instance. 1409 return mightHaveNonExternalLinkage(D); 1410 } 1411 1412 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1413 if (!D) 1414 return; 1415 1416 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1417 const FunctionDecl *First = FD->getFirstDecl(); 1418 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1419 return; // First should already be in the vector. 1420 } 1421 1422 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1423 const VarDecl *First = VD->getFirstDecl(); 1424 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1425 return; // First should already be in the vector. 1426 } 1427 1428 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1429 UnusedFileScopedDecls.push_back(D); 1430 } 1431 1432 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1433 if (D->isInvalidDecl()) 1434 return false; 1435 1436 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1437 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1438 return false; 1439 1440 if (isa<LabelDecl>(D)) 1441 return true; 1442 1443 // Except for labels, we only care about unused decls that are local to 1444 // functions. 1445 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1446 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1447 // For dependent types, the diagnostic is deferred. 1448 WithinFunction = 1449 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1450 if (!WithinFunction) 1451 return false; 1452 1453 if (isa<TypedefNameDecl>(D)) 1454 return true; 1455 1456 // White-list anything that isn't a local variable. 1457 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1458 return false; 1459 1460 // Types of valid local variables should be complete, so this should succeed. 1461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1462 1463 // White-list anything with an __attribute__((unused)) type. 1464 QualType Ty = VD->getType(); 1465 1466 // Only look at the outermost level of typedef. 1467 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1468 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1469 return false; 1470 } 1471 1472 // If we failed to complete the type for some reason, or if the type is 1473 // dependent, don't diagnose the variable. 1474 if (Ty->isIncompleteType() || Ty->isDependentType()) 1475 return false; 1476 1477 if (const TagType *TT = Ty->getAs<TagType>()) { 1478 const TagDecl *Tag = TT->getDecl(); 1479 if (Tag->hasAttr<UnusedAttr>()) 1480 return false; 1481 1482 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1483 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1484 return false; 1485 1486 if (const Expr *Init = VD->getInit()) { 1487 if (const ExprWithCleanups *Cleanups = 1488 dyn_cast<ExprWithCleanups>(Init)) 1489 Init = Cleanups->getSubExpr(); 1490 const CXXConstructExpr *Construct = 1491 dyn_cast<CXXConstructExpr>(Init); 1492 if (Construct && !Construct->isElidable()) { 1493 CXXConstructorDecl *CD = Construct->getConstructor(); 1494 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1495 return false; 1496 } 1497 } 1498 } 1499 } 1500 1501 // TODO: __attribute__((unused)) templates? 1502 } 1503 1504 return true; 1505 } 1506 1507 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1508 FixItHint &Hint) { 1509 if (isa<LabelDecl>(D)) { 1510 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1511 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1512 if (AfterColon.isInvalid()) 1513 return; 1514 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1515 getCharRange(D->getLocStart(), AfterColon)); 1516 } 1517 return; 1518 } 1519 1520 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1521 if (D->getTypeForDecl()->isDependentType()) 1522 return; 1523 1524 for (auto *TmpD : D->decls()) { 1525 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1526 DiagnoseUnusedDecl(T); 1527 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1528 DiagnoseUnusedNestedTypedefs(R); 1529 } 1530 } 1531 1532 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1533 /// unless they are marked attr(unused). 1534 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1535 if (!ShouldDiagnoseUnusedDecl(D)) 1536 return; 1537 1538 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1539 // typedefs can be referenced later on, so the diagnostics are emitted 1540 // at end-of-translation-unit. 1541 UnusedLocalTypedefNameCandidates.insert(TD); 1542 return; 1543 } 1544 1545 FixItHint Hint; 1546 GenerateFixForUnusedDecl(D, Context, Hint); 1547 1548 unsigned DiagID; 1549 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1550 DiagID = diag::warn_unused_exception_param; 1551 else if (isa<LabelDecl>(D)) 1552 DiagID = diag::warn_unused_label; 1553 else 1554 DiagID = diag::warn_unused_variable; 1555 1556 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1557 } 1558 1559 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1560 // Verify that we have no forward references left. If so, there was a goto 1561 // or address of a label taken, but no definition of it. Label fwd 1562 // definitions are indicated with a null substmt which is also not a resolved 1563 // MS inline assembly label name. 1564 bool Diagnose = false; 1565 if (L->isMSAsmLabel()) 1566 Diagnose = !L->isResolvedMSAsmLabel(); 1567 else 1568 Diagnose = L->getStmt() == nullptr; 1569 if (Diagnose) 1570 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1571 } 1572 1573 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1574 S->mergeNRVOIntoParent(); 1575 1576 if (S->decl_empty()) return; 1577 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1578 "Scope shouldn't contain decls!"); 1579 1580 for (auto *TmpD : S->decls()) { 1581 assert(TmpD && "This decl didn't get pushed??"); 1582 1583 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1584 NamedDecl *D = cast<NamedDecl>(TmpD); 1585 1586 if (!D->getDeclName()) continue; 1587 1588 // Diagnose unused variables in this scope. 1589 if (!S->hasUnrecoverableErrorOccurred()) { 1590 DiagnoseUnusedDecl(D); 1591 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1592 DiagnoseUnusedNestedTypedefs(RD); 1593 } 1594 1595 // If this was a forward reference to a label, verify it was defined. 1596 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1597 CheckPoppedLabel(LD, *this); 1598 1599 // Remove this name from our lexical scope. 1600 IdResolver.RemoveDecl(D); 1601 } 1602 } 1603 1604 /// \brief Look for an Objective-C class in the translation unit. 1605 /// 1606 /// \param Id The name of the Objective-C class we're looking for. If 1607 /// typo-correction fixes this name, the Id will be updated 1608 /// to the fixed name. 1609 /// 1610 /// \param IdLoc The location of the name in the translation unit. 1611 /// 1612 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1613 /// if there is no class with the given name. 1614 /// 1615 /// \returns The declaration of the named Objective-C class, or NULL if the 1616 /// class could not be found. 1617 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1618 SourceLocation IdLoc, 1619 bool DoTypoCorrection) { 1620 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1621 // creation from this context. 1622 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1623 1624 if (!IDecl && DoTypoCorrection) { 1625 // Perform typo correction at the given location, but only if we 1626 // find an Objective-C class name. 1627 if (TypoCorrection C = CorrectTypo( 1628 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1629 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1630 CTK_ErrorRecovery)) { 1631 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1632 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1633 Id = IDecl->getIdentifier(); 1634 } 1635 } 1636 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1637 // This routine must always return a class definition, if any. 1638 if (Def && Def->getDefinition()) 1639 Def = Def->getDefinition(); 1640 return Def; 1641 } 1642 1643 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1644 /// from S, where a non-field would be declared. This routine copes 1645 /// with the difference between C and C++ scoping rules in structs and 1646 /// unions. For example, the following code is well-formed in C but 1647 /// ill-formed in C++: 1648 /// @code 1649 /// struct S6 { 1650 /// enum { BAR } e; 1651 /// }; 1652 /// 1653 /// void test_S6() { 1654 /// struct S6 a; 1655 /// a.e = BAR; 1656 /// } 1657 /// @endcode 1658 /// For the declaration of BAR, this routine will return a different 1659 /// scope. The scope S will be the scope of the unnamed enumeration 1660 /// within S6. In C++, this routine will return the scope associated 1661 /// with S6, because the enumeration's scope is a transparent 1662 /// context but structures can contain non-field names. In C, this 1663 /// routine will return the translation unit scope, since the 1664 /// enumeration's scope is a transparent context and structures cannot 1665 /// contain non-field names. 1666 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1667 while (((S->getFlags() & Scope::DeclScope) == 0) || 1668 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1669 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1670 S = S->getParent(); 1671 return S; 1672 } 1673 1674 /// \brief Looks up the declaration of "struct objc_super" and 1675 /// saves it for later use in building builtin declaration of 1676 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1677 /// pre-existing declaration exists no action takes place. 1678 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1679 IdentifierInfo *II) { 1680 if (!II->isStr("objc_msgSendSuper")) 1681 return; 1682 ASTContext &Context = ThisSema.Context; 1683 1684 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1685 SourceLocation(), Sema::LookupTagName); 1686 ThisSema.LookupName(Result, S); 1687 if (Result.getResultKind() == LookupResult::Found) 1688 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1689 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1690 } 1691 1692 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1693 switch (Error) { 1694 case ASTContext::GE_None: 1695 return ""; 1696 case ASTContext::GE_Missing_stdio: 1697 return "stdio.h"; 1698 case ASTContext::GE_Missing_setjmp: 1699 return "setjmp.h"; 1700 case ASTContext::GE_Missing_ucontext: 1701 return "ucontext.h"; 1702 } 1703 llvm_unreachable("unhandled error kind"); 1704 } 1705 1706 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1707 /// file scope. lazily create a decl for it. ForRedeclaration is true 1708 /// if we're creating this built-in in anticipation of redeclaring the 1709 /// built-in. 1710 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1711 Scope *S, bool ForRedeclaration, 1712 SourceLocation Loc) { 1713 LookupPredefedObjCSuperType(*this, S, II); 1714 1715 ASTContext::GetBuiltinTypeError Error; 1716 QualType R = Context.GetBuiltinType(ID, Error); 1717 if (Error) { 1718 if (ForRedeclaration) 1719 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1720 << getHeaderName(Error) 1721 << Context.BuiltinInfo.GetName(ID); 1722 return nullptr; 1723 } 1724 1725 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1726 Diag(Loc, diag::ext_implicit_lib_function_decl) 1727 << Context.BuiltinInfo.GetName(ID) 1728 << R; 1729 if (Context.BuiltinInfo.getHeaderName(ID) && 1730 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1731 Diag(Loc, diag::note_include_header_or_declare) 1732 << Context.BuiltinInfo.getHeaderName(ID) 1733 << Context.BuiltinInfo.GetName(ID); 1734 } 1735 1736 DeclContext *Parent = Context.getTranslationUnitDecl(); 1737 if (getLangOpts().CPlusPlus) { 1738 LinkageSpecDecl *CLinkageDecl = 1739 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1740 LinkageSpecDecl::lang_c, false); 1741 CLinkageDecl->setImplicit(); 1742 Parent->addDecl(CLinkageDecl); 1743 Parent = CLinkageDecl; 1744 } 1745 1746 FunctionDecl *New = FunctionDecl::Create(Context, 1747 Parent, 1748 Loc, Loc, II, R, /*TInfo=*/nullptr, 1749 SC_Extern, 1750 false, 1751 /*hasPrototype=*/true); 1752 New->setImplicit(); 1753 1754 // Create Decl objects for each parameter, adding them to the 1755 // FunctionDecl. 1756 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1757 SmallVector<ParmVarDecl*, 16> Params; 1758 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1759 ParmVarDecl *parm = 1760 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1761 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1762 SC_None, nullptr); 1763 parm->setScopeInfo(0, i); 1764 Params.push_back(parm); 1765 } 1766 New->setParams(Params); 1767 } 1768 1769 AddKnownFunctionAttributes(New); 1770 RegisterLocallyScopedExternCDecl(New, S); 1771 1772 // TUScope is the translation-unit scope to insert this function into. 1773 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1774 // relate Scopes to DeclContexts, and probably eliminate CurContext 1775 // entirely, but we're not there yet. 1776 DeclContext *SavedContext = CurContext; 1777 CurContext = Parent; 1778 PushOnScopeChains(New, TUScope); 1779 CurContext = SavedContext; 1780 return New; 1781 } 1782 1783 /// \brief Filter out any previous declarations that the given declaration 1784 /// should not consider because they are not permitted to conflict, e.g., 1785 /// because they come from hidden sub-modules and do not refer to the same 1786 /// entity. 1787 static void filterNonConflictingPreviousDecls(ASTContext &context, 1788 NamedDecl *decl, 1789 LookupResult &previous){ 1790 // This is only interesting when modules are enabled. 1791 if (!context.getLangOpts().Modules) 1792 return; 1793 1794 // Empty sets are uninteresting. 1795 if (previous.empty()) 1796 return; 1797 1798 LookupResult::Filter filter = previous.makeFilter(); 1799 while (filter.hasNext()) { 1800 NamedDecl *old = filter.next(); 1801 1802 // Non-hidden declarations are never ignored. 1803 if (!old->isHidden()) 1804 continue; 1805 1806 if (!old->isExternallyVisible()) 1807 filter.erase(); 1808 } 1809 1810 filter.done(); 1811 } 1812 1813 /// Typedef declarations don't have linkage, but they still denote the same 1814 /// entity if their types are the same. 1815 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1816 /// isSameEntity. 1817 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context, 1818 TypedefNameDecl *Decl, 1819 LookupResult &Previous) { 1820 // This is only interesting when modules are enabled. 1821 if (!Context.getLangOpts().Modules) 1822 return; 1823 1824 // Empty sets are uninteresting. 1825 if (Previous.empty()) 1826 return; 1827 1828 LookupResult::Filter Filter = Previous.makeFilter(); 1829 while (Filter.hasNext()) { 1830 NamedDecl *Old = Filter.next(); 1831 1832 // Non-hidden declarations are never ignored. 1833 if (!Old->isHidden()) 1834 continue; 1835 1836 // Declarations of the same entity are not ignored, even if they have 1837 // different linkages. 1838 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) 1839 if (Context.hasSameType(OldTD->getUnderlyingType(), 1840 Decl->getUnderlyingType())) 1841 continue; 1842 1843 if (!Old->isExternallyVisible()) 1844 Filter.erase(); 1845 } 1846 1847 Filter.done(); 1848 } 1849 1850 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1851 QualType OldType; 1852 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1853 OldType = OldTypedef->getUnderlyingType(); 1854 else 1855 OldType = Context.getTypeDeclType(Old); 1856 QualType NewType = New->getUnderlyingType(); 1857 1858 if (NewType->isVariablyModifiedType()) { 1859 // Must not redefine a typedef with a variably-modified type. 1860 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1861 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1862 << Kind << NewType; 1863 if (Old->getLocation().isValid()) 1864 Diag(Old->getLocation(), diag::note_previous_definition); 1865 New->setInvalidDecl(); 1866 return true; 1867 } 1868 1869 if (OldType != NewType && 1870 !OldType->isDependentType() && 1871 !NewType->isDependentType() && 1872 !Context.hasSameType(OldType, NewType)) { 1873 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1874 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1875 << Kind << NewType << OldType; 1876 if (Old->getLocation().isValid()) 1877 Diag(Old->getLocation(), diag::note_previous_definition); 1878 New->setInvalidDecl(); 1879 return true; 1880 } 1881 return false; 1882 } 1883 1884 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1885 /// same name and scope as a previous declaration 'Old'. Figure out 1886 /// how to resolve this situation, merging decls or emitting 1887 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1888 /// 1889 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1890 // If the new decl is known invalid already, don't bother doing any 1891 // merging checks. 1892 if (New->isInvalidDecl()) return; 1893 1894 // Allow multiple definitions for ObjC built-in typedefs. 1895 // FIXME: Verify the underlying types are equivalent! 1896 if (getLangOpts().ObjC1) { 1897 const IdentifierInfo *TypeID = New->getIdentifier(); 1898 switch (TypeID->getLength()) { 1899 default: break; 1900 case 2: 1901 { 1902 if (!TypeID->isStr("id")) 1903 break; 1904 QualType T = New->getUnderlyingType(); 1905 if (!T->isPointerType()) 1906 break; 1907 if (!T->isVoidPointerType()) { 1908 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1909 if (!PT->isStructureType()) 1910 break; 1911 } 1912 Context.setObjCIdRedefinitionType(T); 1913 // Install the built-in type for 'id', ignoring the current definition. 1914 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1915 return; 1916 } 1917 case 5: 1918 if (!TypeID->isStr("Class")) 1919 break; 1920 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1921 // Install the built-in type for 'Class', ignoring the current definition. 1922 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1923 return; 1924 case 3: 1925 if (!TypeID->isStr("SEL")) 1926 break; 1927 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1928 // Install the built-in type for 'SEL', ignoring the current definition. 1929 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1930 return; 1931 } 1932 // Fall through - the typedef name was not a builtin type. 1933 } 1934 1935 // Verify the old decl was also a type. 1936 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1937 if (!Old) { 1938 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1939 << New->getDeclName(); 1940 1941 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1942 if (OldD->getLocation().isValid()) 1943 Diag(OldD->getLocation(), diag::note_previous_definition); 1944 1945 return New->setInvalidDecl(); 1946 } 1947 1948 // If the old declaration is invalid, just give up here. 1949 if (Old->isInvalidDecl()) 1950 return New->setInvalidDecl(); 1951 1952 // If the typedef types are not identical, reject them in all languages and 1953 // with any extensions enabled. 1954 if (isIncompatibleTypedef(Old, New)) 1955 return; 1956 1957 // The types match. Link up the redeclaration chain and merge attributes if 1958 // the old declaration was a typedef. 1959 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1960 New->setPreviousDecl(Typedef); 1961 mergeDeclAttributes(New, Old); 1962 } 1963 1964 if (getLangOpts().MicrosoftExt) 1965 return; 1966 1967 if (getLangOpts().CPlusPlus) { 1968 // C++ [dcl.typedef]p2: 1969 // In a given non-class scope, a typedef specifier can be used to 1970 // redefine the name of any type declared in that scope to refer 1971 // to the type to which it already refers. 1972 if (!isa<CXXRecordDecl>(CurContext)) 1973 return; 1974 1975 // C++0x [dcl.typedef]p4: 1976 // In a given class scope, a typedef specifier can be used to redefine 1977 // any class-name declared in that scope that is not also a typedef-name 1978 // to refer to the type to which it already refers. 1979 // 1980 // This wording came in via DR424, which was a correction to the 1981 // wording in DR56, which accidentally banned code like: 1982 // 1983 // struct S { 1984 // typedef struct A { } A; 1985 // }; 1986 // 1987 // in the C++03 standard. We implement the C++0x semantics, which 1988 // allow the above but disallow 1989 // 1990 // struct S { 1991 // typedef int I; 1992 // typedef int I; 1993 // }; 1994 // 1995 // since that was the intent of DR56. 1996 if (!isa<TypedefNameDecl>(Old)) 1997 return; 1998 1999 Diag(New->getLocation(), diag::err_redefinition) 2000 << New->getDeclName(); 2001 Diag(Old->getLocation(), diag::note_previous_definition); 2002 return New->setInvalidDecl(); 2003 } 2004 2005 // Modules always permit redefinition of typedefs, as does C11. 2006 if (getLangOpts().Modules || getLangOpts().C11) 2007 return; 2008 2009 // If we have a redefinition of a typedef in C, emit a warning. This warning 2010 // is normally mapped to an error, but can be controlled with 2011 // -Wtypedef-redefinition. If either the original or the redefinition is 2012 // in a system header, don't emit this for compatibility with GCC. 2013 if (getDiagnostics().getSuppressSystemWarnings() && 2014 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2015 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2016 return; 2017 2018 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2019 << New->getDeclName(); 2020 Diag(Old->getLocation(), diag::note_previous_definition); 2021 return; 2022 } 2023 2024 /// DeclhasAttr - returns true if decl Declaration already has the target 2025 /// attribute. 2026 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2027 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2028 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2029 for (const auto *i : D->attrs()) 2030 if (i->getKind() == A->getKind()) { 2031 if (Ann) { 2032 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2033 return true; 2034 continue; 2035 } 2036 // FIXME: Don't hardcode this check 2037 if (OA && isa<OwnershipAttr>(i)) 2038 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2039 return true; 2040 } 2041 2042 return false; 2043 } 2044 2045 static bool isAttributeTargetADefinition(Decl *D) { 2046 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2047 return VD->isThisDeclarationADefinition(); 2048 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2049 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2050 return true; 2051 } 2052 2053 /// Merge alignment attributes from \p Old to \p New, taking into account the 2054 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2055 /// 2056 /// \return \c true if any attributes were added to \p New. 2057 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2058 // Look for alignas attributes on Old, and pick out whichever attribute 2059 // specifies the strictest alignment requirement. 2060 AlignedAttr *OldAlignasAttr = nullptr; 2061 AlignedAttr *OldStrictestAlignAttr = nullptr; 2062 unsigned OldAlign = 0; 2063 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2064 // FIXME: We have no way of representing inherited dependent alignments 2065 // in a case like: 2066 // template<int A, int B> struct alignas(A) X; 2067 // template<int A, int B> struct alignas(B) X {}; 2068 // For now, we just ignore any alignas attributes which are not on the 2069 // definition in such a case. 2070 if (I->isAlignmentDependent()) 2071 return false; 2072 2073 if (I->isAlignas()) 2074 OldAlignasAttr = I; 2075 2076 unsigned Align = I->getAlignment(S.Context); 2077 if (Align > OldAlign) { 2078 OldAlign = Align; 2079 OldStrictestAlignAttr = I; 2080 } 2081 } 2082 2083 // Look for alignas attributes on New. 2084 AlignedAttr *NewAlignasAttr = nullptr; 2085 unsigned NewAlign = 0; 2086 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2087 if (I->isAlignmentDependent()) 2088 return false; 2089 2090 if (I->isAlignas()) 2091 NewAlignasAttr = I; 2092 2093 unsigned Align = I->getAlignment(S.Context); 2094 if (Align > NewAlign) 2095 NewAlign = Align; 2096 } 2097 2098 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2099 // Both declarations have 'alignas' attributes. We require them to match. 2100 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2101 // fall short. (If two declarations both have alignas, they must both match 2102 // every definition, and so must match each other if there is a definition.) 2103 2104 // If either declaration only contains 'alignas(0)' specifiers, then it 2105 // specifies the natural alignment for the type. 2106 if (OldAlign == 0 || NewAlign == 0) { 2107 QualType Ty; 2108 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2109 Ty = VD->getType(); 2110 else 2111 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2112 2113 if (OldAlign == 0) 2114 OldAlign = S.Context.getTypeAlign(Ty); 2115 if (NewAlign == 0) 2116 NewAlign = S.Context.getTypeAlign(Ty); 2117 } 2118 2119 if (OldAlign != NewAlign) { 2120 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2121 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2122 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2123 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2124 } 2125 } 2126 2127 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2128 // C++11 [dcl.align]p6: 2129 // if any declaration of an entity has an alignment-specifier, 2130 // every defining declaration of that entity shall specify an 2131 // equivalent alignment. 2132 // C11 6.7.5/7: 2133 // If the definition of an object does not have an alignment 2134 // specifier, any other declaration of that object shall also 2135 // have no alignment specifier. 2136 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2137 << OldAlignasAttr; 2138 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2139 << OldAlignasAttr; 2140 } 2141 2142 bool AnyAdded = false; 2143 2144 // Ensure we have an attribute representing the strictest alignment. 2145 if (OldAlign > NewAlign) { 2146 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2147 Clone->setInherited(true); 2148 New->addAttr(Clone); 2149 AnyAdded = true; 2150 } 2151 2152 // Ensure we have an alignas attribute if the old declaration had one. 2153 if (OldAlignasAttr && !NewAlignasAttr && 2154 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2155 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2156 Clone->setInherited(true); 2157 New->addAttr(Clone); 2158 AnyAdded = true; 2159 } 2160 2161 return AnyAdded; 2162 } 2163 2164 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2165 const InheritableAttr *Attr, bool Override) { 2166 InheritableAttr *NewAttr = nullptr; 2167 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2168 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2169 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2170 AA->getIntroduced(), AA->getDeprecated(), 2171 AA->getObsoleted(), AA->getUnavailable(), 2172 AA->getMessage(), Override, 2173 AttrSpellingListIndex); 2174 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2175 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2176 AttrSpellingListIndex); 2177 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2178 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2179 AttrSpellingListIndex); 2180 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2181 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2182 AttrSpellingListIndex); 2183 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2184 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2185 AttrSpellingListIndex); 2186 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2187 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2188 FA->getFormatIdx(), FA->getFirstArg(), 2189 AttrSpellingListIndex); 2190 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2191 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2192 AttrSpellingListIndex); 2193 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2194 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2195 AttrSpellingListIndex, 2196 IA->getSemanticSpelling()); 2197 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2198 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2199 &S.Context.Idents.get(AA->getSpelling()), 2200 AttrSpellingListIndex); 2201 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2202 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2203 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2204 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2205 else if (isa<AlignedAttr>(Attr)) 2206 // AlignedAttrs are handled separately, because we need to handle all 2207 // such attributes on a declaration at the same time. 2208 NewAttr = nullptr; 2209 else if (isa<DeprecatedAttr>(Attr) && Override) 2210 NewAttr = nullptr; 2211 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2212 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2213 2214 if (NewAttr) { 2215 NewAttr->setInherited(true); 2216 D->addAttr(NewAttr); 2217 return true; 2218 } 2219 2220 return false; 2221 } 2222 2223 static const Decl *getDefinition(const Decl *D) { 2224 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2225 return TD->getDefinition(); 2226 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2227 const VarDecl *Def = VD->getDefinition(); 2228 if (Def) 2229 return Def; 2230 return VD->getActingDefinition(); 2231 } 2232 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2233 const FunctionDecl* Def; 2234 if (FD->isDefined(Def)) 2235 return Def; 2236 } 2237 return nullptr; 2238 } 2239 2240 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2241 for (const auto *Attribute : D->attrs()) 2242 if (Attribute->getKind() == Kind) 2243 return true; 2244 return false; 2245 } 2246 2247 /// checkNewAttributesAfterDef - If we already have a definition, check that 2248 /// there are no new attributes in this declaration. 2249 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2250 if (!New->hasAttrs()) 2251 return; 2252 2253 const Decl *Def = getDefinition(Old); 2254 if (!Def || Def == New) 2255 return; 2256 2257 AttrVec &NewAttributes = New->getAttrs(); 2258 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2259 const Attr *NewAttribute = NewAttributes[I]; 2260 2261 if (isa<AliasAttr>(NewAttribute)) { 2262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2263 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2264 else { 2265 VarDecl *VD = cast<VarDecl>(New); 2266 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2267 VarDecl::TentativeDefinition 2268 ? diag::err_alias_after_tentative 2269 : diag::err_redefinition; 2270 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2271 S.Diag(Def->getLocation(), diag::note_previous_definition); 2272 VD->setInvalidDecl(); 2273 } 2274 ++I; 2275 continue; 2276 } 2277 2278 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2279 // Tentative definitions are only interesting for the alias check above. 2280 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2281 ++I; 2282 continue; 2283 } 2284 } 2285 2286 if (hasAttribute(Def, NewAttribute->getKind())) { 2287 ++I; 2288 continue; // regular attr merging will take care of validating this. 2289 } 2290 2291 if (isa<C11NoReturnAttr>(NewAttribute)) { 2292 // C's _Noreturn is allowed to be added to a function after it is defined. 2293 ++I; 2294 continue; 2295 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2296 if (AA->isAlignas()) { 2297 // C++11 [dcl.align]p6: 2298 // if any declaration of an entity has an alignment-specifier, 2299 // every defining declaration of that entity shall specify an 2300 // equivalent alignment. 2301 // C11 6.7.5/7: 2302 // If the definition of an object does not have an alignment 2303 // specifier, any other declaration of that object shall also 2304 // have no alignment specifier. 2305 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2306 << AA; 2307 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2308 << AA; 2309 NewAttributes.erase(NewAttributes.begin() + I); 2310 --E; 2311 continue; 2312 } 2313 } 2314 2315 S.Diag(NewAttribute->getLocation(), 2316 diag::warn_attribute_precede_definition); 2317 S.Diag(Def->getLocation(), diag::note_previous_definition); 2318 NewAttributes.erase(NewAttributes.begin() + I); 2319 --E; 2320 } 2321 } 2322 2323 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2324 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2325 AvailabilityMergeKind AMK) { 2326 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2327 UsedAttr *NewAttr = OldAttr->clone(Context); 2328 NewAttr->setInherited(true); 2329 New->addAttr(NewAttr); 2330 } 2331 2332 if (!Old->hasAttrs() && !New->hasAttrs()) 2333 return; 2334 2335 // attributes declared post-definition are currently ignored 2336 checkNewAttributesAfterDef(*this, New, Old); 2337 2338 if (!Old->hasAttrs()) 2339 return; 2340 2341 bool foundAny = New->hasAttrs(); 2342 2343 // Ensure that any moving of objects within the allocated map is done before 2344 // we process them. 2345 if (!foundAny) New->setAttrs(AttrVec()); 2346 2347 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2348 bool Override = false; 2349 // Ignore deprecated/unavailable/availability attributes if requested. 2350 if (isa<DeprecatedAttr>(I) || 2351 isa<UnavailableAttr>(I) || 2352 isa<AvailabilityAttr>(I)) { 2353 switch (AMK) { 2354 case AMK_None: 2355 continue; 2356 2357 case AMK_Redeclaration: 2358 break; 2359 2360 case AMK_Override: 2361 Override = true; 2362 break; 2363 } 2364 } 2365 2366 // Already handled. 2367 if (isa<UsedAttr>(I)) 2368 continue; 2369 2370 if (mergeDeclAttribute(*this, New, I, Override)) 2371 foundAny = true; 2372 } 2373 2374 if (mergeAlignedAttrs(*this, New, Old)) 2375 foundAny = true; 2376 2377 if (!foundAny) New->dropAttrs(); 2378 } 2379 2380 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2381 /// to the new one. 2382 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2383 const ParmVarDecl *oldDecl, 2384 Sema &S) { 2385 // C++11 [dcl.attr.depend]p2: 2386 // The first declaration of a function shall specify the 2387 // carries_dependency attribute for its declarator-id if any declaration 2388 // of the function specifies the carries_dependency attribute. 2389 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2390 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2391 S.Diag(CDA->getLocation(), 2392 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2393 // Find the first declaration of the parameter. 2394 // FIXME: Should we build redeclaration chains for function parameters? 2395 const FunctionDecl *FirstFD = 2396 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2397 const ParmVarDecl *FirstVD = 2398 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2399 S.Diag(FirstVD->getLocation(), 2400 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2401 } 2402 2403 if (!oldDecl->hasAttrs()) 2404 return; 2405 2406 bool foundAny = newDecl->hasAttrs(); 2407 2408 // Ensure that any moving of objects within the allocated map is 2409 // done before we process them. 2410 if (!foundAny) newDecl->setAttrs(AttrVec()); 2411 2412 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2413 if (!DeclHasAttr(newDecl, I)) { 2414 InheritableAttr *newAttr = 2415 cast<InheritableParamAttr>(I->clone(S.Context)); 2416 newAttr->setInherited(true); 2417 newDecl->addAttr(newAttr); 2418 foundAny = true; 2419 } 2420 } 2421 2422 if (!foundAny) newDecl->dropAttrs(); 2423 } 2424 2425 namespace { 2426 2427 /// Used in MergeFunctionDecl to keep track of function parameters in 2428 /// C. 2429 struct GNUCompatibleParamWarning { 2430 ParmVarDecl *OldParm; 2431 ParmVarDecl *NewParm; 2432 QualType PromotedType; 2433 }; 2434 2435 } 2436 2437 /// getSpecialMember - get the special member enum for a method. 2438 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2439 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2440 if (Ctor->isDefaultConstructor()) 2441 return Sema::CXXDefaultConstructor; 2442 2443 if (Ctor->isCopyConstructor()) 2444 return Sema::CXXCopyConstructor; 2445 2446 if (Ctor->isMoveConstructor()) 2447 return Sema::CXXMoveConstructor; 2448 } else if (isa<CXXDestructorDecl>(MD)) { 2449 return Sema::CXXDestructor; 2450 } else if (MD->isCopyAssignmentOperator()) { 2451 return Sema::CXXCopyAssignment; 2452 } else if (MD->isMoveAssignmentOperator()) { 2453 return Sema::CXXMoveAssignment; 2454 } 2455 2456 return Sema::CXXInvalid; 2457 } 2458 2459 // Determine whether the previous declaration was a definition, implicit 2460 // declaration, or a declaration. 2461 template <typename T> 2462 static std::pair<diag::kind, SourceLocation> 2463 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2464 diag::kind PrevDiag; 2465 SourceLocation OldLocation = Old->getLocation(); 2466 if (Old->isThisDeclarationADefinition()) 2467 PrevDiag = diag::note_previous_definition; 2468 else if (Old->isImplicit()) { 2469 PrevDiag = diag::note_previous_implicit_declaration; 2470 if (OldLocation.isInvalid()) 2471 OldLocation = New->getLocation(); 2472 } else 2473 PrevDiag = diag::note_previous_declaration; 2474 return std::make_pair(PrevDiag, OldLocation); 2475 } 2476 2477 /// canRedefineFunction - checks if a function can be redefined. Currently, 2478 /// only extern inline functions can be redefined, and even then only in 2479 /// GNU89 mode. 2480 static bool canRedefineFunction(const FunctionDecl *FD, 2481 const LangOptions& LangOpts) { 2482 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2483 !LangOpts.CPlusPlus && 2484 FD->isInlineSpecified() && 2485 FD->getStorageClass() == SC_Extern); 2486 } 2487 2488 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2489 const AttributedType *AT = T->getAs<AttributedType>(); 2490 while (AT && !AT->isCallingConv()) 2491 AT = AT->getModifiedType()->getAs<AttributedType>(); 2492 return AT; 2493 } 2494 2495 template <typename T> 2496 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2497 const DeclContext *DC = Old->getDeclContext(); 2498 if (DC->isRecord()) 2499 return false; 2500 2501 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2502 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2503 return true; 2504 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2505 return true; 2506 return false; 2507 } 2508 2509 /// MergeFunctionDecl - We just parsed a function 'New' from 2510 /// declarator D which has the same name and scope as a previous 2511 /// declaration 'Old'. Figure out how to resolve this situation, 2512 /// merging decls or emitting diagnostics as appropriate. 2513 /// 2514 /// In C++, New and Old must be declarations that are not 2515 /// overloaded. Use IsOverload to determine whether New and Old are 2516 /// overloaded, and to select the Old declaration that New should be 2517 /// merged with. 2518 /// 2519 /// Returns true if there was an error, false otherwise. 2520 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2521 Scope *S, bool MergeTypeWithOld) { 2522 // Verify the old decl was also a function. 2523 FunctionDecl *Old = OldD->getAsFunction(); 2524 if (!Old) { 2525 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2526 if (New->getFriendObjectKind()) { 2527 Diag(New->getLocation(), diag::err_using_decl_friend); 2528 Diag(Shadow->getTargetDecl()->getLocation(), 2529 diag::note_using_decl_target); 2530 Diag(Shadow->getUsingDecl()->getLocation(), 2531 diag::note_using_decl) << 0; 2532 return true; 2533 } 2534 2535 // C++11 [namespace.udecl]p14: 2536 // If a function declaration in namespace scope or block scope has the 2537 // same name and the same parameter-type-list as a function introduced 2538 // by a using-declaration, and the declarations do not declare the same 2539 // function, the program is ill-formed. 2540 2541 // Check whether the two declarations might declare the same function. 2542 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2543 if (Old && 2544 !Old->getDeclContext()->getRedeclContext()->Equals( 2545 New->getDeclContext()->getRedeclContext()) && 2546 !(Old->isExternC() && New->isExternC())) 2547 Old = nullptr; 2548 2549 if (!Old) { 2550 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2551 Diag(Shadow->getTargetDecl()->getLocation(), 2552 diag::note_using_decl_target); 2553 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2554 return true; 2555 } 2556 OldD = Old; 2557 } else { 2558 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2559 << New->getDeclName(); 2560 Diag(OldD->getLocation(), diag::note_previous_definition); 2561 return true; 2562 } 2563 } 2564 2565 // If the old declaration is invalid, just give up here. 2566 if (Old->isInvalidDecl()) 2567 return true; 2568 2569 diag::kind PrevDiag; 2570 SourceLocation OldLocation; 2571 std::tie(PrevDiag, OldLocation) = 2572 getNoteDiagForInvalidRedeclaration(Old, New); 2573 2574 // Don't complain about this if we're in GNU89 mode and the old function 2575 // is an extern inline function. 2576 // Don't complain about specializations. They are not supposed to have 2577 // storage classes. 2578 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2579 New->getStorageClass() == SC_Static && 2580 Old->hasExternalFormalLinkage() && 2581 !New->getTemplateSpecializationInfo() && 2582 !canRedefineFunction(Old, getLangOpts())) { 2583 if (getLangOpts().MicrosoftExt) { 2584 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2585 Diag(OldLocation, PrevDiag); 2586 } else { 2587 Diag(New->getLocation(), diag::err_static_non_static) << New; 2588 Diag(OldLocation, PrevDiag); 2589 return true; 2590 } 2591 } 2592 2593 2594 // If a function is first declared with a calling convention, but is later 2595 // declared or defined without one, all following decls assume the calling 2596 // convention of the first. 2597 // 2598 // It's OK if a function is first declared without a calling convention, 2599 // but is later declared or defined with the default calling convention. 2600 // 2601 // To test if either decl has an explicit calling convention, we look for 2602 // AttributedType sugar nodes on the type as written. If they are missing or 2603 // were canonicalized away, we assume the calling convention was implicit. 2604 // 2605 // Note also that we DO NOT return at this point, because we still have 2606 // other tests to run. 2607 QualType OldQType = Context.getCanonicalType(Old->getType()); 2608 QualType NewQType = Context.getCanonicalType(New->getType()); 2609 const FunctionType *OldType = cast<FunctionType>(OldQType); 2610 const FunctionType *NewType = cast<FunctionType>(NewQType); 2611 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2612 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2613 bool RequiresAdjustment = false; 2614 2615 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2616 FunctionDecl *First = Old->getFirstDecl(); 2617 const FunctionType *FT = 2618 First->getType().getCanonicalType()->castAs<FunctionType>(); 2619 FunctionType::ExtInfo FI = FT->getExtInfo(); 2620 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2621 if (!NewCCExplicit) { 2622 // Inherit the CC from the previous declaration if it was specified 2623 // there but not here. 2624 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2625 RequiresAdjustment = true; 2626 } else { 2627 // Calling conventions aren't compatible, so complain. 2628 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2629 Diag(New->getLocation(), diag::err_cconv_change) 2630 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2631 << !FirstCCExplicit 2632 << (!FirstCCExplicit ? "" : 2633 FunctionType::getNameForCallConv(FI.getCC())); 2634 2635 // Put the note on the first decl, since it is the one that matters. 2636 Diag(First->getLocation(), diag::note_previous_declaration); 2637 return true; 2638 } 2639 } 2640 2641 // FIXME: diagnose the other way around? 2642 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2643 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2644 RequiresAdjustment = true; 2645 } 2646 2647 // Merge regparm attribute. 2648 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2649 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2650 if (NewTypeInfo.getHasRegParm()) { 2651 Diag(New->getLocation(), diag::err_regparm_mismatch) 2652 << NewType->getRegParmType() 2653 << OldType->getRegParmType(); 2654 Diag(OldLocation, diag::note_previous_declaration); 2655 return true; 2656 } 2657 2658 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2659 RequiresAdjustment = true; 2660 } 2661 2662 // Merge ns_returns_retained attribute. 2663 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2664 if (NewTypeInfo.getProducesResult()) { 2665 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2666 Diag(OldLocation, diag::note_previous_declaration); 2667 return true; 2668 } 2669 2670 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2671 RequiresAdjustment = true; 2672 } 2673 2674 if (RequiresAdjustment) { 2675 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2676 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2677 New->setType(QualType(AdjustedType, 0)); 2678 NewQType = Context.getCanonicalType(New->getType()); 2679 NewType = cast<FunctionType>(NewQType); 2680 } 2681 2682 // If this redeclaration makes the function inline, we may need to add it to 2683 // UndefinedButUsed. 2684 if (!Old->isInlined() && New->isInlined() && 2685 !New->hasAttr<GNUInlineAttr>() && 2686 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2687 Old->isUsed(false) && 2688 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2689 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2690 SourceLocation())); 2691 2692 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2693 // about it. 2694 if (New->hasAttr<GNUInlineAttr>() && 2695 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2696 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2697 } 2698 2699 if (getLangOpts().CPlusPlus) { 2700 // (C++98 13.1p2): 2701 // Certain function declarations cannot be overloaded: 2702 // -- Function declarations that differ only in the return type 2703 // cannot be overloaded. 2704 2705 // Go back to the type source info to compare the declared return types, 2706 // per C++1y [dcl.type.auto]p13: 2707 // Redeclarations or specializations of a function or function template 2708 // with a declared return type that uses a placeholder type shall also 2709 // use that placeholder, not a deduced type. 2710 QualType OldDeclaredReturnType = 2711 (Old->getTypeSourceInfo() 2712 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2713 : OldType)->getReturnType(); 2714 QualType NewDeclaredReturnType = 2715 (New->getTypeSourceInfo() 2716 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2717 : NewType)->getReturnType(); 2718 QualType ResQT; 2719 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2720 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2721 New->isLocalExternDecl())) { 2722 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2723 OldDeclaredReturnType->isObjCObjectPointerType()) 2724 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2725 if (ResQT.isNull()) { 2726 if (New->isCXXClassMember() && New->isOutOfLine()) 2727 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2728 << New << New->getReturnTypeSourceRange(); 2729 else 2730 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2731 << New->getReturnTypeSourceRange(); 2732 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2733 << Old->getReturnTypeSourceRange(); 2734 return true; 2735 } 2736 else 2737 NewQType = ResQT; 2738 } 2739 2740 QualType OldReturnType = OldType->getReturnType(); 2741 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2742 if (OldReturnType != NewReturnType) { 2743 // If this function has a deduced return type and has already been 2744 // defined, copy the deduced value from the old declaration. 2745 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2746 if (OldAT && OldAT->isDeduced()) { 2747 New->setType( 2748 SubstAutoType(New->getType(), 2749 OldAT->isDependentType() ? Context.DependentTy 2750 : OldAT->getDeducedType())); 2751 NewQType = Context.getCanonicalType( 2752 SubstAutoType(NewQType, 2753 OldAT->isDependentType() ? Context.DependentTy 2754 : OldAT->getDeducedType())); 2755 } 2756 } 2757 2758 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2759 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2760 if (OldMethod && NewMethod) { 2761 // Preserve triviality. 2762 NewMethod->setTrivial(OldMethod->isTrivial()); 2763 2764 // MSVC allows explicit template specialization at class scope: 2765 // 2 CXXMethodDecls referring to the same function will be injected. 2766 // We don't want a redeclaration error. 2767 bool IsClassScopeExplicitSpecialization = 2768 OldMethod->isFunctionTemplateSpecialization() && 2769 NewMethod->isFunctionTemplateSpecialization(); 2770 bool isFriend = NewMethod->getFriendObjectKind(); 2771 2772 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2773 !IsClassScopeExplicitSpecialization) { 2774 // -- Member function declarations with the same name and the 2775 // same parameter types cannot be overloaded if any of them 2776 // is a static member function declaration. 2777 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2778 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2779 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2780 return true; 2781 } 2782 2783 // C++ [class.mem]p1: 2784 // [...] A member shall not be declared twice in the 2785 // member-specification, except that a nested class or member 2786 // class template can be declared and then later defined. 2787 if (ActiveTemplateInstantiations.empty()) { 2788 unsigned NewDiag; 2789 if (isa<CXXConstructorDecl>(OldMethod)) 2790 NewDiag = diag::err_constructor_redeclared; 2791 else if (isa<CXXDestructorDecl>(NewMethod)) 2792 NewDiag = diag::err_destructor_redeclared; 2793 else if (isa<CXXConversionDecl>(NewMethod)) 2794 NewDiag = diag::err_conv_function_redeclared; 2795 else 2796 NewDiag = diag::err_member_redeclared; 2797 2798 Diag(New->getLocation(), NewDiag); 2799 } else { 2800 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2801 << New << New->getType(); 2802 } 2803 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2804 return true; 2805 2806 // Complain if this is an explicit declaration of a special 2807 // member that was initially declared implicitly. 2808 // 2809 // As an exception, it's okay to befriend such methods in order 2810 // to permit the implicit constructor/destructor/operator calls. 2811 } else if (OldMethod->isImplicit()) { 2812 if (isFriend) { 2813 NewMethod->setImplicit(); 2814 } else { 2815 Diag(NewMethod->getLocation(), 2816 diag::err_definition_of_implicitly_declared_member) 2817 << New << getSpecialMember(OldMethod); 2818 return true; 2819 } 2820 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2821 Diag(NewMethod->getLocation(), 2822 diag::err_definition_of_explicitly_defaulted_member) 2823 << getSpecialMember(OldMethod); 2824 return true; 2825 } 2826 } 2827 2828 // C++11 [dcl.attr.noreturn]p1: 2829 // The first declaration of a function shall specify the noreturn 2830 // attribute if any declaration of that function specifies the noreturn 2831 // attribute. 2832 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2833 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2834 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2835 Diag(Old->getFirstDecl()->getLocation(), 2836 diag::note_noreturn_missing_first_decl); 2837 } 2838 2839 // C++11 [dcl.attr.depend]p2: 2840 // The first declaration of a function shall specify the 2841 // carries_dependency attribute for its declarator-id if any declaration 2842 // of the function specifies the carries_dependency attribute. 2843 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2844 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2845 Diag(CDA->getLocation(), 2846 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2847 Diag(Old->getFirstDecl()->getLocation(), 2848 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2849 } 2850 2851 // (C++98 8.3.5p3): 2852 // All declarations for a function shall agree exactly in both the 2853 // return type and the parameter-type-list. 2854 // We also want to respect all the extended bits except noreturn. 2855 2856 // noreturn should now match unless the old type info didn't have it. 2857 QualType OldQTypeForComparison = OldQType; 2858 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2859 assert(OldQType == QualType(OldType, 0)); 2860 const FunctionType *OldTypeForComparison 2861 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2862 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2863 assert(OldQTypeForComparison.isCanonical()); 2864 } 2865 2866 if (haveIncompatibleLanguageLinkages(Old, New)) { 2867 // As a special case, retain the language linkage from previous 2868 // declarations of a friend function as an extension. 2869 // 2870 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2871 // and is useful because there's otherwise no way to specify language 2872 // linkage within class scope. 2873 // 2874 // Check cautiously as the friend object kind isn't yet complete. 2875 if (New->getFriendObjectKind() != Decl::FOK_None) { 2876 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2877 Diag(OldLocation, PrevDiag); 2878 } else { 2879 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2880 Diag(OldLocation, PrevDiag); 2881 return true; 2882 } 2883 } 2884 2885 if (OldQTypeForComparison == NewQType) 2886 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2887 2888 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2889 New->isLocalExternDecl()) { 2890 // It's OK if we couldn't merge types for a local function declaraton 2891 // if either the old or new type is dependent. We'll merge the types 2892 // when we instantiate the function. 2893 return false; 2894 } 2895 2896 // Fall through for conflicting redeclarations and redefinitions. 2897 } 2898 2899 // C: Function types need to be compatible, not identical. This handles 2900 // duplicate function decls like "void f(int); void f(enum X);" properly. 2901 if (!getLangOpts().CPlusPlus && 2902 Context.typesAreCompatible(OldQType, NewQType)) { 2903 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2904 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2905 const FunctionProtoType *OldProto = nullptr; 2906 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2907 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2908 // The old declaration provided a function prototype, but the 2909 // new declaration does not. Merge in the prototype. 2910 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2911 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2912 NewQType = 2913 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2914 OldProto->getExtProtoInfo()); 2915 New->setType(NewQType); 2916 New->setHasInheritedPrototype(); 2917 2918 // Synthesize parameters with the same types. 2919 SmallVector<ParmVarDecl*, 16> Params; 2920 for (const auto &ParamType : OldProto->param_types()) { 2921 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2922 SourceLocation(), nullptr, 2923 ParamType, /*TInfo=*/nullptr, 2924 SC_None, nullptr); 2925 Param->setScopeInfo(0, Params.size()); 2926 Param->setImplicit(); 2927 Params.push_back(Param); 2928 } 2929 2930 New->setParams(Params); 2931 } 2932 2933 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2934 } 2935 2936 // GNU C permits a K&R definition to follow a prototype declaration 2937 // if the declared types of the parameters in the K&R definition 2938 // match the types in the prototype declaration, even when the 2939 // promoted types of the parameters from the K&R definition differ 2940 // from the types in the prototype. GCC then keeps the types from 2941 // the prototype. 2942 // 2943 // If a variadic prototype is followed by a non-variadic K&R definition, 2944 // the K&R definition becomes variadic. This is sort of an edge case, but 2945 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2946 // C99 6.9.1p8. 2947 if (!getLangOpts().CPlusPlus && 2948 Old->hasPrototype() && !New->hasPrototype() && 2949 New->getType()->getAs<FunctionProtoType>() && 2950 Old->getNumParams() == New->getNumParams()) { 2951 SmallVector<QualType, 16> ArgTypes; 2952 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2953 const FunctionProtoType *OldProto 2954 = Old->getType()->getAs<FunctionProtoType>(); 2955 const FunctionProtoType *NewProto 2956 = New->getType()->getAs<FunctionProtoType>(); 2957 2958 // Determine whether this is the GNU C extension. 2959 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2960 NewProto->getReturnType()); 2961 bool LooseCompatible = !MergedReturn.isNull(); 2962 for (unsigned Idx = 0, End = Old->getNumParams(); 2963 LooseCompatible && Idx != End; ++Idx) { 2964 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2965 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2966 if (Context.typesAreCompatible(OldParm->getType(), 2967 NewProto->getParamType(Idx))) { 2968 ArgTypes.push_back(NewParm->getType()); 2969 } else if (Context.typesAreCompatible(OldParm->getType(), 2970 NewParm->getType(), 2971 /*CompareUnqualified=*/true)) { 2972 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2973 NewProto->getParamType(Idx) }; 2974 Warnings.push_back(Warn); 2975 ArgTypes.push_back(NewParm->getType()); 2976 } else 2977 LooseCompatible = false; 2978 } 2979 2980 if (LooseCompatible) { 2981 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2982 Diag(Warnings[Warn].NewParm->getLocation(), 2983 diag::ext_param_promoted_not_compatible_with_prototype) 2984 << Warnings[Warn].PromotedType 2985 << Warnings[Warn].OldParm->getType(); 2986 if (Warnings[Warn].OldParm->getLocation().isValid()) 2987 Diag(Warnings[Warn].OldParm->getLocation(), 2988 diag::note_previous_declaration); 2989 } 2990 2991 if (MergeTypeWithOld) 2992 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2993 OldProto->getExtProtoInfo())); 2994 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2995 } 2996 2997 // Fall through to diagnose conflicting types. 2998 } 2999 3000 // A function that has already been declared has been redeclared or 3001 // defined with a different type; show an appropriate diagnostic. 3002 3003 // If the previous declaration was an implicitly-generated builtin 3004 // declaration, then at the very least we should use a specialized note. 3005 unsigned BuiltinID; 3006 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3007 // If it's actually a library-defined builtin function like 'malloc' 3008 // or 'printf', just warn about the incompatible redeclaration. 3009 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3010 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3011 Diag(OldLocation, diag::note_previous_builtin_declaration) 3012 << Old << Old->getType(); 3013 3014 // If this is a global redeclaration, just forget hereafter 3015 // about the "builtin-ness" of the function. 3016 // 3017 // Doing this for local extern declarations is problematic. If 3018 // the builtin declaration remains visible, a second invalid 3019 // local declaration will produce a hard error; if it doesn't 3020 // remain visible, a single bogus local redeclaration (which is 3021 // actually only a warning) could break all the downstream code. 3022 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3023 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 3024 3025 return false; 3026 } 3027 3028 PrevDiag = diag::note_previous_builtin_declaration; 3029 } 3030 3031 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3032 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3033 return true; 3034 } 3035 3036 /// \brief Completes the merge of two function declarations that are 3037 /// known to be compatible. 3038 /// 3039 /// This routine handles the merging of attributes and other 3040 /// properties of function declarations from the old declaration to 3041 /// the new declaration, once we know that New is in fact a 3042 /// redeclaration of Old. 3043 /// 3044 /// \returns false 3045 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3046 Scope *S, bool MergeTypeWithOld) { 3047 // Merge the attributes 3048 mergeDeclAttributes(New, Old); 3049 3050 // Merge "pure" flag. 3051 if (Old->isPure()) 3052 New->setPure(); 3053 3054 // Merge "used" flag. 3055 if (Old->getMostRecentDecl()->isUsed(false)) 3056 New->setIsUsed(); 3057 3058 // Merge attributes from the parameters. These can mismatch with K&R 3059 // declarations. 3060 if (New->getNumParams() == Old->getNumParams()) 3061 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 3062 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 3063 *this); 3064 3065 if (getLangOpts().CPlusPlus) 3066 return MergeCXXFunctionDecl(New, Old, S); 3067 3068 // Merge the function types so the we get the composite types for the return 3069 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3070 // was visible. 3071 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3072 if (!Merged.isNull() && MergeTypeWithOld) 3073 New->setType(Merged); 3074 3075 return false; 3076 } 3077 3078 3079 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3080 ObjCMethodDecl *oldMethod) { 3081 3082 // Merge the attributes, including deprecated/unavailable 3083 AvailabilityMergeKind MergeKind = 3084 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3085 : AMK_Override; 3086 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3087 3088 // Merge attributes from the parameters. 3089 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3090 oe = oldMethod->param_end(); 3091 for (ObjCMethodDecl::param_iterator 3092 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3093 ni != ne && oi != oe; ++ni, ++oi) 3094 mergeParamDeclAttributes(*ni, *oi, *this); 3095 3096 CheckObjCMethodOverride(newMethod, oldMethod); 3097 } 3098 3099 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3100 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3101 /// emitting diagnostics as appropriate. 3102 /// 3103 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3104 /// to here in AddInitializerToDecl. We can't check them before the initializer 3105 /// is attached. 3106 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3107 bool MergeTypeWithOld) { 3108 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3109 return; 3110 3111 QualType MergedT; 3112 if (getLangOpts().CPlusPlus) { 3113 if (New->getType()->isUndeducedType()) { 3114 // We don't know what the new type is until the initializer is attached. 3115 return; 3116 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3117 // These could still be something that needs exception specs checked. 3118 return MergeVarDeclExceptionSpecs(New, Old); 3119 } 3120 // C++ [basic.link]p10: 3121 // [...] the types specified by all declarations referring to a given 3122 // object or function shall be identical, except that declarations for an 3123 // array object can specify array types that differ by the presence or 3124 // absence of a major array bound (8.3.4). 3125 else if (Old->getType()->isIncompleteArrayType() && 3126 New->getType()->isArrayType()) { 3127 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3128 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3129 if (Context.hasSameType(OldArray->getElementType(), 3130 NewArray->getElementType())) 3131 MergedT = New->getType(); 3132 } else if (Old->getType()->isArrayType() && 3133 New->getType()->isIncompleteArrayType()) { 3134 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3135 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3136 if (Context.hasSameType(OldArray->getElementType(), 3137 NewArray->getElementType())) 3138 MergedT = Old->getType(); 3139 } else if (New->getType()->isObjCObjectPointerType() && 3140 Old->getType()->isObjCObjectPointerType()) { 3141 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3142 Old->getType()); 3143 } 3144 } else { 3145 // C 6.2.7p2: 3146 // All declarations that refer to the same object or function shall have 3147 // compatible type. 3148 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3149 } 3150 if (MergedT.isNull()) { 3151 // It's OK if we couldn't merge types if either type is dependent, for a 3152 // block-scope variable. In other cases (static data members of class 3153 // templates, variable templates, ...), we require the types to be 3154 // equivalent. 3155 // FIXME: The C++ standard doesn't say anything about this. 3156 if ((New->getType()->isDependentType() || 3157 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3158 // If the old type was dependent, we can't merge with it, so the new type 3159 // becomes dependent for now. We'll reproduce the original type when we 3160 // instantiate the TypeSourceInfo for the variable. 3161 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3162 New->setType(Context.DependentTy); 3163 return; 3164 } 3165 3166 // FIXME: Even if this merging succeeds, some other non-visible declaration 3167 // of this variable might have an incompatible type. For instance: 3168 // 3169 // extern int arr[]; 3170 // void f() { extern int arr[2]; } 3171 // void g() { extern int arr[3]; } 3172 // 3173 // Neither C nor C++ requires a diagnostic for this, but we should still try 3174 // to diagnose it. 3175 Diag(New->getLocation(), diag::err_redefinition_different_type) 3176 << New->getDeclName() << New->getType() << Old->getType(); 3177 Diag(Old->getLocation(), diag::note_previous_definition); 3178 return New->setInvalidDecl(); 3179 } 3180 3181 // Don't actually update the type on the new declaration if the old 3182 // declaration was an extern declaration in a different scope. 3183 if (MergeTypeWithOld) 3184 New->setType(MergedT); 3185 } 3186 3187 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3188 LookupResult &Previous) { 3189 // C11 6.2.7p4: 3190 // For an identifier with internal or external linkage declared 3191 // in a scope in which a prior declaration of that identifier is 3192 // visible, if the prior declaration specifies internal or 3193 // external linkage, the type of the identifier at the later 3194 // declaration becomes the composite type. 3195 // 3196 // If the variable isn't visible, we do not merge with its type. 3197 if (Previous.isShadowed()) 3198 return false; 3199 3200 if (S.getLangOpts().CPlusPlus) { 3201 // C++11 [dcl.array]p3: 3202 // If there is a preceding declaration of the entity in the same 3203 // scope in which the bound was specified, an omitted array bound 3204 // is taken to be the same as in that earlier declaration. 3205 return NewVD->isPreviousDeclInSameBlockScope() || 3206 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3207 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3208 } else { 3209 // If the old declaration was function-local, don't merge with its 3210 // type unless we're in the same function. 3211 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3212 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3213 } 3214 } 3215 3216 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3217 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3218 /// situation, merging decls or emitting diagnostics as appropriate. 3219 /// 3220 /// Tentative definition rules (C99 6.9.2p2) are checked by 3221 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3222 /// definitions here, since the initializer hasn't been attached. 3223 /// 3224 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3225 // If the new decl is already invalid, don't do any other checking. 3226 if (New->isInvalidDecl()) 3227 return; 3228 3229 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3230 3231 // Verify the old decl was also a variable or variable template. 3232 VarDecl *Old = nullptr; 3233 VarTemplateDecl *OldTemplate = nullptr; 3234 if (Previous.isSingleResult()) { 3235 if (NewTemplate) { 3236 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3237 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3238 } else 3239 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3240 } 3241 if (!Old) { 3242 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3243 << New->getDeclName(); 3244 Diag(Previous.getRepresentativeDecl()->getLocation(), 3245 diag::note_previous_definition); 3246 return New->setInvalidDecl(); 3247 } 3248 3249 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3250 return; 3251 3252 // Ensure the template parameters are compatible. 3253 if (NewTemplate && 3254 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3255 OldTemplate->getTemplateParameters(), 3256 /*Complain=*/true, TPL_TemplateMatch)) 3257 return; 3258 3259 // C++ [class.mem]p1: 3260 // A member shall not be declared twice in the member-specification [...] 3261 // 3262 // Here, we need only consider static data members. 3263 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3264 Diag(New->getLocation(), diag::err_duplicate_member) 3265 << New->getIdentifier(); 3266 Diag(Old->getLocation(), diag::note_previous_declaration); 3267 New->setInvalidDecl(); 3268 } 3269 3270 mergeDeclAttributes(New, Old); 3271 // Warn if an already-declared variable is made a weak_import in a subsequent 3272 // declaration 3273 if (New->hasAttr<WeakImportAttr>() && 3274 Old->getStorageClass() == SC_None && 3275 !Old->hasAttr<WeakImportAttr>()) { 3276 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3277 Diag(Old->getLocation(), diag::note_previous_definition); 3278 // Remove weak_import attribute on new declaration. 3279 New->dropAttr<WeakImportAttr>(); 3280 } 3281 3282 // Merge the types. 3283 VarDecl *MostRecent = Old->getMostRecentDecl(); 3284 if (MostRecent != Old) { 3285 MergeVarDeclTypes(New, MostRecent, 3286 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3287 if (New->isInvalidDecl()) 3288 return; 3289 } 3290 3291 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3292 if (New->isInvalidDecl()) 3293 return; 3294 3295 diag::kind PrevDiag; 3296 SourceLocation OldLocation; 3297 std::tie(PrevDiag, OldLocation) = 3298 getNoteDiagForInvalidRedeclaration(Old, New); 3299 3300 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3301 if (New->getStorageClass() == SC_Static && 3302 !New->isStaticDataMember() && 3303 Old->hasExternalFormalLinkage()) { 3304 if (getLangOpts().MicrosoftExt) { 3305 Diag(New->getLocation(), diag::ext_static_non_static) 3306 << New->getDeclName(); 3307 Diag(OldLocation, PrevDiag); 3308 } else { 3309 Diag(New->getLocation(), diag::err_static_non_static) 3310 << New->getDeclName(); 3311 Diag(OldLocation, PrevDiag); 3312 return New->setInvalidDecl(); 3313 } 3314 } 3315 // C99 6.2.2p4: 3316 // For an identifier declared with the storage-class specifier 3317 // extern in a scope in which a prior declaration of that 3318 // identifier is visible,23) if the prior declaration specifies 3319 // internal or external linkage, the linkage of the identifier at 3320 // the later declaration is the same as the linkage specified at 3321 // the prior declaration. If no prior declaration is visible, or 3322 // if the prior declaration specifies no linkage, then the 3323 // identifier has external linkage. 3324 if (New->hasExternalStorage() && Old->hasLinkage()) 3325 /* Okay */; 3326 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3327 !New->isStaticDataMember() && 3328 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3329 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3330 Diag(OldLocation, PrevDiag); 3331 return New->setInvalidDecl(); 3332 } 3333 3334 // Check if extern is followed by non-extern and vice-versa. 3335 if (New->hasExternalStorage() && 3336 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3337 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3338 Diag(OldLocation, PrevDiag); 3339 return New->setInvalidDecl(); 3340 } 3341 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3342 !New->hasExternalStorage()) { 3343 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3344 Diag(OldLocation, PrevDiag); 3345 return New->setInvalidDecl(); 3346 } 3347 3348 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3349 3350 // FIXME: The test for external storage here seems wrong? We still 3351 // need to check for mismatches. 3352 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3353 // Don't complain about out-of-line definitions of static members. 3354 !(Old->getLexicalDeclContext()->isRecord() && 3355 !New->getLexicalDeclContext()->isRecord())) { 3356 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3357 Diag(OldLocation, PrevDiag); 3358 return New->setInvalidDecl(); 3359 } 3360 3361 if (New->getTLSKind() != Old->getTLSKind()) { 3362 if (!Old->getTLSKind()) { 3363 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3364 Diag(OldLocation, PrevDiag); 3365 } else if (!New->getTLSKind()) { 3366 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3367 Diag(OldLocation, PrevDiag); 3368 } else { 3369 // Do not allow redeclaration to change the variable between requiring 3370 // static and dynamic initialization. 3371 // FIXME: GCC allows this, but uses the TLS keyword on the first 3372 // declaration to determine the kind. Do we need to be compatible here? 3373 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3374 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3375 Diag(OldLocation, PrevDiag); 3376 } 3377 } 3378 3379 // C++ doesn't have tentative definitions, so go right ahead and check here. 3380 const VarDecl *Def; 3381 if (getLangOpts().CPlusPlus && 3382 New->isThisDeclarationADefinition() == VarDecl::Definition && 3383 (Def = Old->getDefinition())) { 3384 Diag(New->getLocation(), diag::err_redefinition) << New; 3385 Diag(Def->getLocation(), diag::note_previous_definition); 3386 New->setInvalidDecl(); 3387 return; 3388 } 3389 3390 if (haveIncompatibleLanguageLinkages(Old, New)) { 3391 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3392 Diag(OldLocation, PrevDiag); 3393 New->setInvalidDecl(); 3394 return; 3395 } 3396 3397 // Merge "used" flag. 3398 if (Old->getMostRecentDecl()->isUsed(false)) 3399 New->setIsUsed(); 3400 3401 // Keep a chain of previous declarations. 3402 New->setPreviousDecl(Old); 3403 if (NewTemplate) 3404 NewTemplate->setPreviousDecl(OldTemplate); 3405 3406 // Inherit access appropriately. 3407 New->setAccess(Old->getAccess()); 3408 if (NewTemplate) 3409 NewTemplate->setAccess(New->getAccess()); 3410 } 3411 3412 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3413 /// no declarator (e.g. "struct foo;") is parsed. 3414 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3415 DeclSpec &DS) { 3416 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3417 } 3418 3419 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3420 if (!S.Context.getLangOpts().CPlusPlus) 3421 return; 3422 3423 if (isa<CXXRecordDecl>(Tag->getParent())) { 3424 // If this tag is the direct child of a class, number it if 3425 // it is anonymous. 3426 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3427 return; 3428 MangleNumberingContext &MCtx = 3429 S.Context.getManglingNumberContext(Tag->getParent()); 3430 S.Context.setManglingNumber( 3431 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3432 return; 3433 } 3434 3435 // If this tag isn't a direct child of a class, number it if it is local. 3436 Decl *ManglingContextDecl; 3437 if (MangleNumberingContext *MCtx = 3438 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3439 ManglingContextDecl)) { 3440 S.Context.setManglingNumber( 3441 Tag, 3442 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3443 } 3444 } 3445 3446 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3447 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3448 /// parameters to cope with template friend declarations. 3449 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3450 DeclSpec &DS, 3451 MultiTemplateParamsArg TemplateParams, 3452 bool IsExplicitInstantiation) { 3453 Decl *TagD = nullptr; 3454 TagDecl *Tag = nullptr; 3455 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3456 DS.getTypeSpecType() == DeclSpec::TST_struct || 3457 DS.getTypeSpecType() == DeclSpec::TST_interface || 3458 DS.getTypeSpecType() == DeclSpec::TST_union || 3459 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3460 TagD = DS.getRepAsDecl(); 3461 3462 if (!TagD) // We probably had an error 3463 return nullptr; 3464 3465 // Note that the above type specs guarantee that the 3466 // type rep is a Decl, whereas in many of the others 3467 // it's a Type. 3468 if (isa<TagDecl>(TagD)) 3469 Tag = cast<TagDecl>(TagD); 3470 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3471 Tag = CTD->getTemplatedDecl(); 3472 } 3473 3474 if (Tag) { 3475 HandleTagNumbering(*this, Tag, S); 3476 Tag->setFreeStanding(); 3477 if (Tag->isInvalidDecl()) 3478 return Tag; 3479 } 3480 3481 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3482 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3483 // or incomplete types shall not be restrict-qualified." 3484 if (TypeQuals & DeclSpec::TQ_restrict) 3485 Diag(DS.getRestrictSpecLoc(), 3486 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3487 << DS.getSourceRange(); 3488 } 3489 3490 if (DS.isConstexprSpecified()) { 3491 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3492 // and definitions of functions and variables. 3493 if (Tag) 3494 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3495 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3496 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3497 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3498 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3499 else 3500 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3501 // Don't emit warnings after this error. 3502 return TagD; 3503 } 3504 3505 DiagnoseFunctionSpecifiers(DS); 3506 3507 if (DS.isFriendSpecified()) { 3508 // If we're dealing with a decl but not a TagDecl, assume that 3509 // whatever routines created it handled the friendship aspect. 3510 if (TagD && !Tag) 3511 return nullptr; 3512 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3513 } 3514 3515 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3516 bool IsExplicitSpecialization = 3517 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3518 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3519 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3520 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3521 // nested-name-specifier unless it is an explicit instantiation 3522 // or an explicit specialization. 3523 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3524 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3525 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3526 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3527 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3528 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3529 << SS.getRange(); 3530 return nullptr; 3531 } 3532 3533 // Track whether this decl-specifier declares anything. 3534 bool DeclaresAnything = true; 3535 3536 // Handle anonymous struct definitions. 3537 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3538 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3539 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3540 if (getLangOpts().CPlusPlus || 3541 Record->getDeclContext()->isRecord()) 3542 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3543 Context.getPrintingPolicy()); 3544 3545 DeclaresAnything = false; 3546 } 3547 } 3548 3549 // C11 6.7.2.1p2: 3550 // A struct-declaration that does not declare an anonymous structure or 3551 // anonymous union shall contain a struct-declarator-list. 3552 // 3553 // This rule also existed in C89 and C99; the grammar for struct-declaration 3554 // did not permit a struct-declaration without a struct-declarator-list. 3555 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3556 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3557 // Check for Microsoft C extension: anonymous struct/union member. 3558 // Handle 2 kinds of anonymous struct/union: 3559 // struct STRUCT; 3560 // union UNION; 3561 // and 3562 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3563 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3564 if ((Tag && Tag->getDeclName()) || 3565 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3566 RecordDecl *Record = nullptr; 3567 if (Tag) 3568 Record = dyn_cast<RecordDecl>(Tag); 3569 else if (const RecordType *RT = 3570 DS.getRepAsType().get()->getAsStructureType()) 3571 Record = RT->getDecl(); 3572 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3573 Record = UT->getDecl(); 3574 3575 if (Record && getLangOpts().MicrosoftExt) { 3576 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3577 << Record->isUnion() << DS.getSourceRange(); 3578 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3579 } 3580 3581 DeclaresAnything = false; 3582 } 3583 } 3584 3585 // Skip all the checks below if we have a type error. 3586 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3587 (TagD && TagD->isInvalidDecl())) 3588 return TagD; 3589 3590 if (getLangOpts().CPlusPlus && 3591 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3592 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3593 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3594 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3595 DeclaresAnything = false; 3596 3597 if (!DS.isMissingDeclaratorOk()) { 3598 // Customize diagnostic for a typedef missing a name. 3599 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3600 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3601 << DS.getSourceRange(); 3602 else 3603 DeclaresAnything = false; 3604 } 3605 3606 if (DS.isModulePrivateSpecified() && 3607 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3608 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3609 << Tag->getTagKind() 3610 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3611 3612 ActOnDocumentableDecl(TagD); 3613 3614 // C 6.7/2: 3615 // A declaration [...] shall declare at least a declarator [...], a tag, 3616 // or the members of an enumeration. 3617 // C++ [dcl.dcl]p3: 3618 // [If there are no declarators], and except for the declaration of an 3619 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3620 // names into the program, or shall redeclare a name introduced by a 3621 // previous declaration. 3622 if (!DeclaresAnything) { 3623 // In C, we allow this as a (popular) extension / bug. Don't bother 3624 // producing further diagnostics for redundant qualifiers after this. 3625 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3626 return TagD; 3627 } 3628 3629 // C++ [dcl.stc]p1: 3630 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3631 // init-declarator-list of the declaration shall not be empty. 3632 // C++ [dcl.fct.spec]p1: 3633 // If a cv-qualifier appears in a decl-specifier-seq, the 3634 // init-declarator-list of the declaration shall not be empty. 3635 // 3636 // Spurious qualifiers here appear to be valid in C. 3637 unsigned DiagID = diag::warn_standalone_specifier; 3638 if (getLangOpts().CPlusPlus) 3639 DiagID = diag::ext_standalone_specifier; 3640 3641 // Note that a linkage-specification sets a storage class, but 3642 // 'extern "C" struct foo;' is actually valid and not theoretically 3643 // useless. 3644 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3645 if (SCS == DeclSpec::SCS_mutable) 3646 // Since mutable is not a viable storage class specifier in C, there is 3647 // no reason to treat it as an extension. Instead, diagnose as an error. 3648 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3649 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3650 Diag(DS.getStorageClassSpecLoc(), DiagID) 3651 << DeclSpec::getSpecifierName(SCS); 3652 } 3653 3654 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3655 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3656 << DeclSpec::getSpecifierName(TSCS); 3657 if (DS.getTypeQualifiers()) { 3658 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3659 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3660 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3661 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3662 // Restrict is covered above. 3663 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3664 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3665 } 3666 3667 // Warn about ignored type attributes, for example: 3668 // __attribute__((aligned)) struct A; 3669 // Attributes should be placed after tag to apply to type declaration. 3670 if (!DS.getAttributes().empty()) { 3671 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3672 if (TypeSpecType == DeclSpec::TST_class || 3673 TypeSpecType == DeclSpec::TST_struct || 3674 TypeSpecType == DeclSpec::TST_interface || 3675 TypeSpecType == DeclSpec::TST_union || 3676 TypeSpecType == DeclSpec::TST_enum) { 3677 AttributeList* attrs = DS.getAttributes().getList(); 3678 while (attrs) { 3679 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3680 << attrs->getName() 3681 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3682 TypeSpecType == DeclSpec::TST_struct ? 1 : 3683 TypeSpecType == DeclSpec::TST_union ? 2 : 3684 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3685 attrs = attrs->getNext(); 3686 } 3687 } 3688 } 3689 3690 return TagD; 3691 } 3692 3693 /// We are trying to inject an anonymous member into the given scope; 3694 /// check if there's an existing declaration that can't be overloaded. 3695 /// 3696 /// \return true if this is a forbidden redeclaration 3697 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3698 Scope *S, 3699 DeclContext *Owner, 3700 DeclarationName Name, 3701 SourceLocation NameLoc, 3702 unsigned diagnostic) { 3703 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3704 Sema::ForRedeclaration); 3705 if (!SemaRef.LookupName(R, S)) return false; 3706 3707 if (R.getAsSingle<TagDecl>()) 3708 return false; 3709 3710 // Pick a representative declaration. 3711 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3712 assert(PrevDecl && "Expected a non-null Decl"); 3713 3714 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3715 return false; 3716 3717 SemaRef.Diag(NameLoc, diagnostic) << Name; 3718 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3719 3720 return true; 3721 } 3722 3723 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3724 /// anonymous struct or union AnonRecord into the owning context Owner 3725 /// and scope S. This routine will be invoked just after we realize 3726 /// that an unnamed union or struct is actually an anonymous union or 3727 /// struct, e.g., 3728 /// 3729 /// @code 3730 /// union { 3731 /// int i; 3732 /// float f; 3733 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3734 /// // f into the surrounding scope.x 3735 /// @endcode 3736 /// 3737 /// This routine is recursive, injecting the names of nested anonymous 3738 /// structs/unions into the owning context and scope as well. 3739 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3740 DeclContext *Owner, 3741 RecordDecl *AnonRecord, 3742 AccessSpecifier AS, 3743 SmallVectorImpl<NamedDecl *> &Chaining, 3744 bool MSAnonStruct) { 3745 unsigned diagKind 3746 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3747 : diag::err_anonymous_struct_member_redecl; 3748 3749 bool Invalid = false; 3750 3751 // Look every FieldDecl and IndirectFieldDecl with a name. 3752 for (auto *D : AnonRecord->decls()) { 3753 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3754 cast<NamedDecl>(D)->getDeclName()) { 3755 ValueDecl *VD = cast<ValueDecl>(D); 3756 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3757 VD->getLocation(), diagKind)) { 3758 // C++ [class.union]p2: 3759 // The names of the members of an anonymous union shall be 3760 // distinct from the names of any other entity in the 3761 // scope in which the anonymous union is declared. 3762 Invalid = true; 3763 } else { 3764 // C++ [class.union]p2: 3765 // For the purpose of name lookup, after the anonymous union 3766 // definition, the members of the anonymous union are 3767 // considered to have been defined in the scope in which the 3768 // anonymous union is declared. 3769 unsigned OldChainingSize = Chaining.size(); 3770 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3771 Chaining.append(IF->chain_begin(), IF->chain_end()); 3772 else 3773 Chaining.push_back(VD); 3774 3775 assert(Chaining.size() >= 2); 3776 NamedDecl **NamedChain = 3777 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3778 for (unsigned i = 0; i < Chaining.size(); i++) 3779 NamedChain[i] = Chaining[i]; 3780 3781 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 3782 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 3783 VD->getType(), NamedChain, Chaining.size()); 3784 3785 for (const auto *Attr : VD->attrs()) 3786 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 3787 3788 IndirectField->setAccess(AS); 3789 IndirectField->setImplicit(); 3790 SemaRef.PushOnScopeChains(IndirectField, S); 3791 3792 // That includes picking up the appropriate access specifier. 3793 if (AS != AS_none) IndirectField->setAccess(AS); 3794 3795 Chaining.resize(OldChainingSize); 3796 } 3797 } 3798 } 3799 3800 return Invalid; 3801 } 3802 3803 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3804 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3805 /// illegal input values are mapped to SC_None. 3806 static StorageClass 3807 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3808 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3809 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3810 "Parser allowed 'typedef' as storage class VarDecl."); 3811 switch (StorageClassSpec) { 3812 case DeclSpec::SCS_unspecified: return SC_None; 3813 case DeclSpec::SCS_extern: 3814 if (DS.isExternInLinkageSpec()) 3815 return SC_None; 3816 return SC_Extern; 3817 case DeclSpec::SCS_static: return SC_Static; 3818 case DeclSpec::SCS_auto: return SC_Auto; 3819 case DeclSpec::SCS_register: return SC_Register; 3820 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3821 // Illegal SCSs map to None: error reporting is up to the caller. 3822 case DeclSpec::SCS_mutable: // Fall through. 3823 case DeclSpec::SCS_typedef: return SC_None; 3824 } 3825 llvm_unreachable("unknown storage class specifier"); 3826 } 3827 3828 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3829 assert(Record->hasInClassInitializer()); 3830 3831 for (const auto *I : Record->decls()) { 3832 const auto *FD = dyn_cast<FieldDecl>(I); 3833 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3834 FD = IFD->getAnonField(); 3835 if (FD && FD->hasInClassInitializer()) 3836 return FD->getLocation(); 3837 } 3838 3839 llvm_unreachable("couldn't find in-class initializer"); 3840 } 3841 3842 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3843 SourceLocation DefaultInitLoc) { 3844 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3845 return; 3846 3847 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3848 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3849 } 3850 3851 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3852 CXXRecordDecl *AnonUnion) { 3853 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3854 return; 3855 3856 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3857 } 3858 3859 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3860 /// anonymous structure or union. Anonymous unions are a C++ feature 3861 /// (C++ [class.union]) and a C11 feature; anonymous structures 3862 /// are a C11 feature and GNU C++ extension. 3863 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3864 AccessSpecifier AS, 3865 RecordDecl *Record, 3866 const PrintingPolicy &Policy) { 3867 DeclContext *Owner = Record->getDeclContext(); 3868 3869 // Diagnose whether this anonymous struct/union is an extension. 3870 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3871 Diag(Record->getLocation(), diag::ext_anonymous_union); 3872 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3873 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3874 else if (!Record->isUnion() && !getLangOpts().C11) 3875 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3876 3877 // C and C++ require different kinds of checks for anonymous 3878 // structs/unions. 3879 bool Invalid = false; 3880 if (getLangOpts().CPlusPlus) { 3881 const char *PrevSpec = nullptr; 3882 unsigned DiagID; 3883 if (Record->isUnion()) { 3884 // C++ [class.union]p6: 3885 // Anonymous unions declared in a named namespace or in the 3886 // global namespace shall be declared static. 3887 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3888 (isa<TranslationUnitDecl>(Owner) || 3889 (isa<NamespaceDecl>(Owner) && 3890 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3891 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3892 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3893 3894 // Recover by adding 'static'. 3895 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3896 PrevSpec, DiagID, Policy); 3897 } 3898 // C++ [class.union]p6: 3899 // A storage class is not allowed in a declaration of an 3900 // anonymous union in a class scope. 3901 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3902 isa<RecordDecl>(Owner)) { 3903 Diag(DS.getStorageClassSpecLoc(), 3904 diag::err_anonymous_union_with_storage_spec) 3905 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3906 3907 // Recover by removing the storage specifier. 3908 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3909 SourceLocation(), 3910 PrevSpec, DiagID, Context.getPrintingPolicy()); 3911 } 3912 } 3913 3914 // Ignore const/volatile/restrict qualifiers. 3915 if (DS.getTypeQualifiers()) { 3916 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3917 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3918 << Record->isUnion() << "const" 3919 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3920 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3921 Diag(DS.getVolatileSpecLoc(), 3922 diag::ext_anonymous_struct_union_qualified) 3923 << Record->isUnion() << "volatile" 3924 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3925 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3926 Diag(DS.getRestrictSpecLoc(), 3927 diag::ext_anonymous_struct_union_qualified) 3928 << Record->isUnion() << "restrict" 3929 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3930 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3931 Diag(DS.getAtomicSpecLoc(), 3932 diag::ext_anonymous_struct_union_qualified) 3933 << Record->isUnion() << "_Atomic" 3934 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3935 3936 DS.ClearTypeQualifiers(); 3937 } 3938 3939 // C++ [class.union]p2: 3940 // The member-specification of an anonymous union shall only 3941 // define non-static data members. [Note: nested types and 3942 // functions cannot be declared within an anonymous union. ] 3943 for (auto *Mem : Record->decls()) { 3944 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3945 // C++ [class.union]p3: 3946 // An anonymous union shall not have private or protected 3947 // members (clause 11). 3948 assert(FD->getAccess() != AS_none); 3949 if (FD->getAccess() != AS_public) { 3950 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3951 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3952 Invalid = true; 3953 } 3954 3955 // C++ [class.union]p1 3956 // An object of a class with a non-trivial constructor, a non-trivial 3957 // copy constructor, a non-trivial destructor, or a non-trivial copy 3958 // assignment operator cannot be a member of a union, nor can an 3959 // array of such objects. 3960 if (CheckNontrivialField(FD)) 3961 Invalid = true; 3962 } else if (Mem->isImplicit()) { 3963 // Any implicit members are fine. 3964 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3965 // This is a type that showed up in an 3966 // elaborated-type-specifier inside the anonymous struct or 3967 // union, but which actually declares a type outside of the 3968 // anonymous struct or union. It's okay. 3969 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3970 if (!MemRecord->isAnonymousStructOrUnion() && 3971 MemRecord->getDeclName()) { 3972 // Visual C++ allows type definition in anonymous struct or union. 3973 if (getLangOpts().MicrosoftExt) 3974 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3975 << (int)Record->isUnion(); 3976 else { 3977 // This is a nested type declaration. 3978 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3979 << (int)Record->isUnion(); 3980 Invalid = true; 3981 } 3982 } else { 3983 // This is an anonymous type definition within another anonymous type. 3984 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3985 // not part of standard C++. 3986 Diag(MemRecord->getLocation(), 3987 diag::ext_anonymous_record_with_anonymous_type) 3988 << (int)Record->isUnion(); 3989 } 3990 } else if (isa<AccessSpecDecl>(Mem)) { 3991 // Any access specifier is fine. 3992 } else if (isa<StaticAssertDecl>(Mem)) { 3993 // In C++1z, static_assert declarations are also fine. 3994 } else { 3995 // We have something that isn't a non-static data 3996 // member. Complain about it. 3997 unsigned DK = diag::err_anonymous_record_bad_member; 3998 if (isa<TypeDecl>(Mem)) 3999 DK = diag::err_anonymous_record_with_type; 4000 else if (isa<FunctionDecl>(Mem)) 4001 DK = diag::err_anonymous_record_with_function; 4002 else if (isa<VarDecl>(Mem)) 4003 DK = diag::err_anonymous_record_with_static; 4004 4005 // Visual C++ allows type definition in anonymous struct or union. 4006 if (getLangOpts().MicrosoftExt && 4007 DK == diag::err_anonymous_record_with_type) 4008 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4009 << (int)Record->isUnion(); 4010 else { 4011 Diag(Mem->getLocation(), DK) 4012 << (int)Record->isUnion(); 4013 Invalid = true; 4014 } 4015 } 4016 } 4017 4018 // C++11 [class.union]p8 (DR1460): 4019 // At most one variant member of a union may have a 4020 // brace-or-equal-initializer. 4021 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4022 Owner->isRecord()) 4023 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4024 cast<CXXRecordDecl>(Record)); 4025 } 4026 4027 if (!Record->isUnion() && !Owner->isRecord()) { 4028 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4029 << (int)getLangOpts().CPlusPlus; 4030 Invalid = true; 4031 } 4032 4033 // Mock up a declarator. 4034 Declarator Dc(DS, Declarator::MemberContext); 4035 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4036 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4037 4038 // Create a declaration for this anonymous struct/union. 4039 NamedDecl *Anon = nullptr; 4040 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4041 Anon = FieldDecl::Create(Context, OwningClass, 4042 DS.getLocStart(), 4043 Record->getLocation(), 4044 /*IdentifierInfo=*/nullptr, 4045 Context.getTypeDeclType(Record), 4046 TInfo, 4047 /*BitWidth=*/nullptr, /*Mutable=*/false, 4048 /*InitStyle=*/ICIS_NoInit); 4049 Anon->setAccess(AS); 4050 if (getLangOpts().CPlusPlus) 4051 FieldCollector->Add(cast<FieldDecl>(Anon)); 4052 } else { 4053 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4054 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4055 if (SCSpec == DeclSpec::SCS_mutable) { 4056 // mutable can only appear on non-static class members, so it's always 4057 // an error here 4058 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4059 Invalid = true; 4060 SC = SC_None; 4061 } 4062 4063 Anon = VarDecl::Create(Context, Owner, 4064 DS.getLocStart(), 4065 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4066 Context.getTypeDeclType(Record), 4067 TInfo, SC); 4068 4069 // Default-initialize the implicit variable. This initialization will be 4070 // trivial in almost all cases, except if a union member has an in-class 4071 // initializer: 4072 // union { int n = 0; }; 4073 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4074 } 4075 Anon->setImplicit(); 4076 4077 // Mark this as an anonymous struct/union type. 4078 Record->setAnonymousStructOrUnion(true); 4079 4080 // Add the anonymous struct/union object to the current 4081 // context. We'll be referencing this object when we refer to one of 4082 // its members. 4083 Owner->addDecl(Anon); 4084 4085 // Inject the members of the anonymous struct/union into the owning 4086 // context and into the identifier resolver chain for name lookup 4087 // purposes. 4088 SmallVector<NamedDecl*, 2> Chain; 4089 Chain.push_back(Anon); 4090 4091 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 4092 Chain, false)) 4093 Invalid = true; 4094 4095 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4096 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4097 Decl *ManglingContextDecl; 4098 if (MangleNumberingContext *MCtx = 4099 getCurrentMangleNumberContext(NewVD->getDeclContext(), 4100 ManglingContextDecl)) { 4101 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 4102 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4103 } 4104 } 4105 } 4106 4107 if (Invalid) 4108 Anon->setInvalidDecl(); 4109 4110 return Anon; 4111 } 4112 4113 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4114 /// Microsoft C anonymous structure. 4115 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4116 /// Example: 4117 /// 4118 /// struct A { int a; }; 4119 /// struct B { struct A; int b; }; 4120 /// 4121 /// void foo() { 4122 /// B var; 4123 /// var.a = 3; 4124 /// } 4125 /// 4126 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4127 RecordDecl *Record) { 4128 assert(Record && "expected a record!"); 4129 4130 // Mock up a declarator. 4131 Declarator Dc(DS, Declarator::TypeNameContext); 4132 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4133 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4134 4135 auto *ParentDecl = cast<RecordDecl>(CurContext); 4136 QualType RecTy = Context.getTypeDeclType(Record); 4137 4138 // Create a declaration for this anonymous struct. 4139 NamedDecl *Anon = FieldDecl::Create(Context, 4140 ParentDecl, 4141 DS.getLocStart(), 4142 DS.getLocStart(), 4143 /*IdentifierInfo=*/nullptr, 4144 RecTy, 4145 TInfo, 4146 /*BitWidth=*/nullptr, /*Mutable=*/false, 4147 /*InitStyle=*/ICIS_NoInit); 4148 Anon->setImplicit(); 4149 4150 // Add the anonymous struct object to the current context. 4151 CurContext->addDecl(Anon); 4152 4153 // Inject the members of the anonymous struct into the current 4154 // context and into the identifier resolver chain for name lookup 4155 // purposes. 4156 SmallVector<NamedDecl*, 2> Chain; 4157 Chain.push_back(Anon); 4158 4159 RecordDecl *RecordDef = Record->getDefinition(); 4160 if (RequireCompleteType(Anon->getLocation(), RecTy, 4161 diag::err_field_incomplete) || 4162 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4163 AS_none, Chain, true)) { 4164 Anon->setInvalidDecl(); 4165 ParentDecl->setInvalidDecl(); 4166 } 4167 4168 return Anon; 4169 } 4170 4171 /// GetNameForDeclarator - Determine the full declaration name for the 4172 /// given Declarator. 4173 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4174 return GetNameFromUnqualifiedId(D.getName()); 4175 } 4176 4177 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4178 DeclarationNameInfo 4179 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4180 DeclarationNameInfo NameInfo; 4181 NameInfo.setLoc(Name.StartLocation); 4182 4183 switch (Name.getKind()) { 4184 4185 case UnqualifiedId::IK_ImplicitSelfParam: 4186 case UnqualifiedId::IK_Identifier: 4187 NameInfo.setName(Name.Identifier); 4188 NameInfo.setLoc(Name.StartLocation); 4189 return NameInfo; 4190 4191 case UnqualifiedId::IK_OperatorFunctionId: 4192 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4193 Name.OperatorFunctionId.Operator)); 4194 NameInfo.setLoc(Name.StartLocation); 4195 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4196 = Name.OperatorFunctionId.SymbolLocations[0]; 4197 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4198 = Name.EndLocation.getRawEncoding(); 4199 return NameInfo; 4200 4201 case UnqualifiedId::IK_LiteralOperatorId: 4202 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4203 Name.Identifier)); 4204 NameInfo.setLoc(Name.StartLocation); 4205 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4206 return NameInfo; 4207 4208 case UnqualifiedId::IK_ConversionFunctionId: { 4209 TypeSourceInfo *TInfo; 4210 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4211 if (Ty.isNull()) 4212 return DeclarationNameInfo(); 4213 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4214 Context.getCanonicalType(Ty))); 4215 NameInfo.setLoc(Name.StartLocation); 4216 NameInfo.setNamedTypeInfo(TInfo); 4217 return NameInfo; 4218 } 4219 4220 case UnqualifiedId::IK_ConstructorName: { 4221 TypeSourceInfo *TInfo; 4222 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4223 if (Ty.isNull()) 4224 return DeclarationNameInfo(); 4225 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4226 Context.getCanonicalType(Ty))); 4227 NameInfo.setLoc(Name.StartLocation); 4228 NameInfo.setNamedTypeInfo(TInfo); 4229 return NameInfo; 4230 } 4231 4232 case UnqualifiedId::IK_ConstructorTemplateId: { 4233 // In well-formed code, we can only have a constructor 4234 // template-id that refers to the current context, so go there 4235 // to find the actual type being constructed. 4236 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4237 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4238 return DeclarationNameInfo(); 4239 4240 // Determine the type of the class being constructed. 4241 QualType CurClassType = Context.getTypeDeclType(CurClass); 4242 4243 // FIXME: Check two things: that the template-id names the same type as 4244 // CurClassType, and that the template-id does not occur when the name 4245 // was qualified. 4246 4247 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4248 Context.getCanonicalType(CurClassType))); 4249 NameInfo.setLoc(Name.StartLocation); 4250 // FIXME: should we retrieve TypeSourceInfo? 4251 NameInfo.setNamedTypeInfo(nullptr); 4252 return NameInfo; 4253 } 4254 4255 case UnqualifiedId::IK_DestructorName: { 4256 TypeSourceInfo *TInfo; 4257 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4258 if (Ty.isNull()) 4259 return DeclarationNameInfo(); 4260 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4261 Context.getCanonicalType(Ty))); 4262 NameInfo.setLoc(Name.StartLocation); 4263 NameInfo.setNamedTypeInfo(TInfo); 4264 return NameInfo; 4265 } 4266 4267 case UnqualifiedId::IK_TemplateId: { 4268 TemplateName TName = Name.TemplateId->Template.get(); 4269 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4270 return Context.getNameForTemplate(TName, TNameLoc); 4271 } 4272 4273 } // switch (Name.getKind()) 4274 4275 llvm_unreachable("Unknown name kind"); 4276 } 4277 4278 static QualType getCoreType(QualType Ty) { 4279 do { 4280 if (Ty->isPointerType() || Ty->isReferenceType()) 4281 Ty = Ty->getPointeeType(); 4282 else if (Ty->isArrayType()) 4283 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4284 else 4285 return Ty.withoutLocalFastQualifiers(); 4286 } while (true); 4287 } 4288 4289 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4290 /// and Definition have "nearly" matching parameters. This heuristic is 4291 /// used to improve diagnostics in the case where an out-of-line function 4292 /// definition doesn't match any declaration within the class or namespace. 4293 /// Also sets Params to the list of indices to the parameters that differ 4294 /// between the declaration and the definition. If hasSimilarParameters 4295 /// returns true and Params is empty, then all of the parameters match. 4296 static bool hasSimilarParameters(ASTContext &Context, 4297 FunctionDecl *Declaration, 4298 FunctionDecl *Definition, 4299 SmallVectorImpl<unsigned> &Params) { 4300 Params.clear(); 4301 if (Declaration->param_size() != Definition->param_size()) 4302 return false; 4303 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4304 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4305 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4306 4307 // The parameter types are identical 4308 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4309 continue; 4310 4311 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4312 QualType DefParamBaseTy = getCoreType(DefParamTy); 4313 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4314 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4315 4316 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4317 (DeclTyName && DeclTyName == DefTyName)) 4318 Params.push_back(Idx); 4319 else // The two parameters aren't even close 4320 return false; 4321 } 4322 4323 return true; 4324 } 4325 4326 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4327 /// declarator needs to be rebuilt in the current instantiation. 4328 /// Any bits of declarator which appear before the name are valid for 4329 /// consideration here. That's specifically the type in the decl spec 4330 /// and the base type in any member-pointer chunks. 4331 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4332 DeclarationName Name) { 4333 // The types we specifically need to rebuild are: 4334 // - typenames, typeofs, and decltypes 4335 // - types which will become injected class names 4336 // Of course, we also need to rebuild any type referencing such a 4337 // type. It's safest to just say "dependent", but we call out a 4338 // few cases here. 4339 4340 DeclSpec &DS = D.getMutableDeclSpec(); 4341 switch (DS.getTypeSpecType()) { 4342 case DeclSpec::TST_typename: 4343 case DeclSpec::TST_typeofType: 4344 case DeclSpec::TST_underlyingType: 4345 case DeclSpec::TST_atomic: { 4346 // Grab the type from the parser. 4347 TypeSourceInfo *TSI = nullptr; 4348 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4349 if (T.isNull() || !T->isDependentType()) break; 4350 4351 // Make sure there's a type source info. This isn't really much 4352 // of a waste; most dependent types should have type source info 4353 // attached already. 4354 if (!TSI) 4355 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4356 4357 // Rebuild the type in the current instantiation. 4358 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4359 if (!TSI) return true; 4360 4361 // Store the new type back in the decl spec. 4362 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4363 DS.UpdateTypeRep(LocType); 4364 break; 4365 } 4366 4367 case DeclSpec::TST_decltype: 4368 case DeclSpec::TST_typeofExpr: { 4369 Expr *E = DS.getRepAsExpr(); 4370 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4371 if (Result.isInvalid()) return true; 4372 DS.UpdateExprRep(Result.get()); 4373 break; 4374 } 4375 4376 default: 4377 // Nothing to do for these decl specs. 4378 break; 4379 } 4380 4381 // It doesn't matter what order we do this in. 4382 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4383 DeclaratorChunk &Chunk = D.getTypeObject(I); 4384 4385 // The only type information in the declarator which can come 4386 // before the declaration name is the base type of a member 4387 // pointer. 4388 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4389 continue; 4390 4391 // Rebuild the scope specifier in-place. 4392 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4393 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4394 return true; 4395 } 4396 4397 return false; 4398 } 4399 4400 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4401 D.setFunctionDefinitionKind(FDK_Declaration); 4402 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4403 4404 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4405 Dcl && Dcl->getDeclContext()->isFileContext()) 4406 Dcl->setTopLevelDeclInObjCContainer(); 4407 4408 return Dcl; 4409 } 4410 4411 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4412 /// If T is the name of a class, then each of the following shall have a 4413 /// name different from T: 4414 /// - every static data member of class T; 4415 /// - every member function of class T 4416 /// - every member of class T that is itself a type; 4417 /// \returns true if the declaration name violates these rules. 4418 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4419 DeclarationNameInfo NameInfo) { 4420 DeclarationName Name = NameInfo.getName(); 4421 4422 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4423 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4424 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4425 return true; 4426 } 4427 4428 return false; 4429 } 4430 4431 /// \brief Diagnose a declaration whose declarator-id has the given 4432 /// nested-name-specifier. 4433 /// 4434 /// \param SS The nested-name-specifier of the declarator-id. 4435 /// 4436 /// \param DC The declaration context to which the nested-name-specifier 4437 /// resolves. 4438 /// 4439 /// \param Name The name of the entity being declared. 4440 /// 4441 /// \param Loc The location of the name of the entity being declared. 4442 /// 4443 /// \returns true if we cannot safely recover from this error, false otherwise. 4444 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4445 DeclarationName Name, 4446 SourceLocation Loc) { 4447 DeclContext *Cur = CurContext; 4448 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4449 Cur = Cur->getParent(); 4450 4451 // If the user provided a superfluous scope specifier that refers back to the 4452 // class in which the entity is already declared, diagnose and ignore it. 4453 // 4454 // class X { 4455 // void X::f(); 4456 // }; 4457 // 4458 // Note, it was once ill-formed to give redundant qualification in all 4459 // contexts, but that rule was removed by DR482. 4460 if (Cur->Equals(DC)) { 4461 if (Cur->isRecord()) { 4462 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4463 : diag::err_member_extra_qualification) 4464 << Name << FixItHint::CreateRemoval(SS.getRange()); 4465 SS.clear(); 4466 } else { 4467 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4468 } 4469 return false; 4470 } 4471 4472 // Check whether the qualifying scope encloses the scope of the original 4473 // declaration. 4474 if (!Cur->Encloses(DC)) { 4475 if (Cur->isRecord()) 4476 Diag(Loc, diag::err_member_qualification) 4477 << Name << SS.getRange(); 4478 else if (isa<TranslationUnitDecl>(DC)) 4479 Diag(Loc, diag::err_invalid_declarator_global_scope) 4480 << Name << SS.getRange(); 4481 else if (isa<FunctionDecl>(Cur)) 4482 Diag(Loc, diag::err_invalid_declarator_in_function) 4483 << Name << SS.getRange(); 4484 else if (isa<BlockDecl>(Cur)) 4485 Diag(Loc, diag::err_invalid_declarator_in_block) 4486 << Name << SS.getRange(); 4487 else 4488 Diag(Loc, diag::err_invalid_declarator_scope) 4489 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4490 4491 return true; 4492 } 4493 4494 if (Cur->isRecord()) { 4495 // Cannot qualify members within a class. 4496 Diag(Loc, diag::err_member_qualification) 4497 << Name << SS.getRange(); 4498 SS.clear(); 4499 4500 // C++ constructors and destructors with incorrect scopes can break 4501 // our AST invariants by having the wrong underlying types. If 4502 // that's the case, then drop this declaration entirely. 4503 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4504 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4505 !Context.hasSameType(Name.getCXXNameType(), 4506 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4507 return true; 4508 4509 return false; 4510 } 4511 4512 // C++11 [dcl.meaning]p1: 4513 // [...] "The nested-name-specifier of the qualified declarator-id shall 4514 // not begin with a decltype-specifer" 4515 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4516 while (SpecLoc.getPrefix()) 4517 SpecLoc = SpecLoc.getPrefix(); 4518 if (dyn_cast_or_null<DecltypeType>( 4519 SpecLoc.getNestedNameSpecifier()->getAsType())) 4520 Diag(Loc, diag::err_decltype_in_declarator) 4521 << SpecLoc.getTypeLoc().getSourceRange(); 4522 4523 return false; 4524 } 4525 4526 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4527 MultiTemplateParamsArg TemplateParamLists) { 4528 // TODO: consider using NameInfo for diagnostic. 4529 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4530 DeclarationName Name = NameInfo.getName(); 4531 4532 // All of these full declarators require an identifier. If it doesn't have 4533 // one, the ParsedFreeStandingDeclSpec action should be used. 4534 if (!Name) { 4535 if (!D.isInvalidType()) // Reject this if we think it is valid. 4536 Diag(D.getDeclSpec().getLocStart(), 4537 diag::err_declarator_need_ident) 4538 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4539 return nullptr; 4540 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4541 return nullptr; 4542 4543 // The scope passed in may not be a decl scope. Zip up the scope tree until 4544 // we find one that is. 4545 while ((S->getFlags() & Scope::DeclScope) == 0 || 4546 (S->getFlags() & Scope::TemplateParamScope) != 0) 4547 S = S->getParent(); 4548 4549 DeclContext *DC = CurContext; 4550 if (D.getCXXScopeSpec().isInvalid()) 4551 D.setInvalidType(); 4552 else if (D.getCXXScopeSpec().isSet()) { 4553 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4554 UPPC_DeclarationQualifier)) 4555 return nullptr; 4556 4557 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4558 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4559 if (!DC || isa<EnumDecl>(DC)) { 4560 // If we could not compute the declaration context, it's because the 4561 // declaration context is dependent but does not refer to a class, 4562 // class template, or class template partial specialization. Complain 4563 // and return early, to avoid the coming semantic disaster. 4564 Diag(D.getIdentifierLoc(), 4565 diag::err_template_qualified_declarator_no_match) 4566 << D.getCXXScopeSpec().getScopeRep() 4567 << D.getCXXScopeSpec().getRange(); 4568 return nullptr; 4569 } 4570 bool IsDependentContext = DC->isDependentContext(); 4571 4572 if (!IsDependentContext && 4573 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4574 return nullptr; 4575 4576 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4577 Diag(D.getIdentifierLoc(), 4578 diag::err_member_def_undefined_record) 4579 << Name << DC << D.getCXXScopeSpec().getRange(); 4580 D.setInvalidType(); 4581 } else if (!D.getDeclSpec().isFriendSpecified()) { 4582 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4583 Name, D.getIdentifierLoc())) { 4584 if (DC->isRecord()) 4585 return nullptr; 4586 4587 D.setInvalidType(); 4588 } 4589 } 4590 4591 // Check whether we need to rebuild the type of the given 4592 // declaration in the current instantiation. 4593 if (EnteringContext && IsDependentContext && 4594 TemplateParamLists.size() != 0) { 4595 ContextRAII SavedContext(*this, DC); 4596 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4597 D.setInvalidType(); 4598 } 4599 } 4600 4601 if (DiagnoseClassNameShadow(DC, NameInfo)) 4602 // If this is a typedef, we'll end up spewing multiple diagnostics. 4603 // Just return early; it's safer. 4604 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4605 return nullptr; 4606 4607 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4608 QualType R = TInfo->getType(); 4609 4610 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4611 UPPC_DeclarationType)) 4612 D.setInvalidType(); 4613 4614 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4615 ForRedeclaration); 4616 4617 // See if this is a redefinition of a variable in the same scope. 4618 if (!D.getCXXScopeSpec().isSet()) { 4619 bool IsLinkageLookup = false; 4620 bool CreateBuiltins = false; 4621 4622 // If the declaration we're planning to build will be a function 4623 // or object with linkage, then look for another declaration with 4624 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4625 // 4626 // If the declaration we're planning to build will be declared with 4627 // external linkage in the translation unit, create any builtin with 4628 // the same name. 4629 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4630 /* Do nothing*/; 4631 else if (CurContext->isFunctionOrMethod() && 4632 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4633 R->isFunctionType())) { 4634 IsLinkageLookup = true; 4635 CreateBuiltins = 4636 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4637 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4638 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4639 CreateBuiltins = true; 4640 4641 if (IsLinkageLookup) 4642 Previous.clear(LookupRedeclarationWithLinkage); 4643 4644 LookupName(Previous, S, CreateBuiltins); 4645 } else { // Something like "int foo::x;" 4646 LookupQualifiedName(Previous, DC); 4647 4648 // C++ [dcl.meaning]p1: 4649 // When the declarator-id is qualified, the declaration shall refer to a 4650 // previously declared member of the class or namespace to which the 4651 // qualifier refers (or, in the case of a namespace, of an element of the 4652 // inline namespace set of that namespace (7.3.1)) or to a specialization 4653 // thereof; [...] 4654 // 4655 // Note that we already checked the context above, and that we do not have 4656 // enough information to make sure that Previous contains the declaration 4657 // we want to match. For example, given: 4658 // 4659 // class X { 4660 // void f(); 4661 // void f(float); 4662 // }; 4663 // 4664 // void X::f(int) { } // ill-formed 4665 // 4666 // In this case, Previous will point to the overload set 4667 // containing the two f's declared in X, but neither of them 4668 // matches. 4669 4670 // C++ [dcl.meaning]p1: 4671 // [...] the member shall not merely have been introduced by a 4672 // using-declaration in the scope of the class or namespace nominated by 4673 // the nested-name-specifier of the declarator-id. 4674 RemoveUsingDecls(Previous); 4675 } 4676 4677 if (Previous.isSingleResult() && 4678 Previous.getFoundDecl()->isTemplateParameter()) { 4679 // Maybe we will complain about the shadowed template parameter. 4680 if (!D.isInvalidType()) 4681 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4682 Previous.getFoundDecl()); 4683 4684 // Just pretend that we didn't see the previous declaration. 4685 Previous.clear(); 4686 } 4687 4688 // In C++, the previous declaration we find might be a tag type 4689 // (class or enum). In this case, the new declaration will hide the 4690 // tag type. Note that this does does not apply if we're declaring a 4691 // typedef (C++ [dcl.typedef]p4). 4692 if (Previous.isSingleTagDecl() && 4693 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4694 Previous.clear(); 4695 4696 // Check that there are no default arguments other than in the parameters 4697 // of a function declaration (C++ only). 4698 if (getLangOpts().CPlusPlus) 4699 CheckExtraCXXDefaultArguments(D); 4700 4701 NamedDecl *New; 4702 4703 bool AddToScope = true; 4704 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4705 if (TemplateParamLists.size()) { 4706 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4707 return nullptr; 4708 } 4709 4710 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4711 } else if (R->isFunctionType()) { 4712 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4713 TemplateParamLists, 4714 AddToScope); 4715 } else { 4716 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4717 AddToScope); 4718 } 4719 4720 if (!New) 4721 return nullptr; 4722 4723 // If this has an identifier and is not an invalid redeclaration or 4724 // function template specialization, add it to the scope stack. 4725 if (New->getDeclName() && AddToScope && 4726 !(D.isRedeclaration() && New->isInvalidDecl())) { 4727 // Only make a locally-scoped extern declaration visible if it is the first 4728 // declaration of this entity. Qualified lookup for such an entity should 4729 // only find this declaration if there is no visible declaration of it. 4730 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4731 PushOnScopeChains(New, S, AddToContext); 4732 if (!AddToContext) 4733 CurContext->addHiddenDecl(New); 4734 } 4735 4736 return New; 4737 } 4738 4739 /// Helper method to turn variable array types into constant array 4740 /// types in certain situations which would otherwise be errors (for 4741 /// GCC compatibility). 4742 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4743 ASTContext &Context, 4744 bool &SizeIsNegative, 4745 llvm::APSInt &Oversized) { 4746 // This method tries to turn a variable array into a constant 4747 // array even when the size isn't an ICE. This is necessary 4748 // for compatibility with code that depends on gcc's buggy 4749 // constant expression folding, like struct {char x[(int)(char*)2];} 4750 SizeIsNegative = false; 4751 Oversized = 0; 4752 4753 if (T->isDependentType()) 4754 return QualType(); 4755 4756 QualifierCollector Qs; 4757 const Type *Ty = Qs.strip(T); 4758 4759 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4760 QualType Pointee = PTy->getPointeeType(); 4761 QualType FixedType = 4762 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4763 Oversized); 4764 if (FixedType.isNull()) return FixedType; 4765 FixedType = Context.getPointerType(FixedType); 4766 return Qs.apply(Context, FixedType); 4767 } 4768 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4769 QualType Inner = PTy->getInnerType(); 4770 QualType FixedType = 4771 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4772 Oversized); 4773 if (FixedType.isNull()) return FixedType; 4774 FixedType = Context.getParenType(FixedType); 4775 return Qs.apply(Context, FixedType); 4776 } 4777 4778 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4779 if (!VLATy) 4780 return QualType(); 4781 // FIXME: We should probably handle this case 4782 if (VLATy->getElementType()->isVariablyModifiedType()) 4783 return QualType(); 4784 4785 llvm::APSInt Res; 4786 if (!VLATy->getSizeExpr() || 4787 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4788 return QualType(); 4789 4790 // Check whether the array size is negative. 4791 if (Res.isSigned() && Res.isNegative()) { 4792 SizeIsNegative = true; 4793 return QualType(); 4794 } 4795 4796 // Check whether the array is too large to be addressed. 4797 unsigned ActiveSizeBits 4798 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4799 Res); 4800 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4801 Oversized = Res; 4802 return QualType(); 4803 } 4804 4805 return Context.getConstantArrayType(VLATy->getElementType(), 4806 Res, ArrayType::Normal, 0); 4807 } 4808 4809 static void 4810 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4811 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4812 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4813 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4814 DstPTL.getPointeeLoc()); 4815 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4816 return; 4817 } 4818 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4819 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4820 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4821 DstPTL.getInnerLoc()); 4822 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4823 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4824 return; 4825 } 4826 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4827 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4828 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4829 TypeLoc DstElemTL = DstATL.getElementLoc(); 4830 DstElemTL.initializeFullCopy(SrcElemTL); 4831 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4832 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4833 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4834 } 4835 4836 /// Helper method to turn variable array types into constant array 4837 /// types in certain situations which would otherwise be errors (for 4838 /// GCC compatibility). 4839 static TypeSourceInfo* 4840 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4841 ASTContext &Context, 4842 bool &SizeIsNegative, 4843 llvm::APSInt &Oversized) { 4844 QualType FixedTy 4845 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4846 SizeIsNegative, Oversized); 4847 if (FixedTy.isNull()) 4848 return nullptr; 4849 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4850 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4851 FixedTInfo->getTypeLoc()); 4852 return FixedTInfo; 4853 } 4854 4855 /// \brief Register the given locally-scoped extern "C" declaration so 4856 /// that it can be found later for redeclarations. We include any extern "C" 4857 /// declaration that is not visible in the translation unit here, not just 4858 /// function-scope declarations. 4859 void 4860 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4861 if (!getLangOpts().CPlusPlus && 4862 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4863 // Don't need to track declarations in the TU in C. 4864 return; 4865 4866 // Note that we have a locally-scoped external with this name. 4867 // FIXME: There can be multiple such declarations if they are functions marked 4868 // __attribute__((overloadable)) declared in function scope in C. 4869 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4870 } 4871 4872 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4873 if (ExternalSource) { 4874 // Load locally-scoped external decls from the external source. 4875 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4876 SmallVector<NamedDecl *, 4> Decls; 4877 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4878 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4879 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4880 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4881 if (Pos == LocallyScopedExternCDecls.end()) 4882 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4883 } 4884 } 4885 4886 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4887 return D ? D->getMostRecentDecl() : nullptr; 4888 } 4889 4890 /// \brief Diagnose function specifiers on a declaration of an identifier that 4891 /// does not identify a function. 4892 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4893 // FIXME: We should probably indicate the identifier in question to avoid 4894 // confusion for constructs like "inline int a(), b;" 4895 if (DS.isInlineSpecified()) 4896 Diag(DS.getInlineSpecLoc(), 4897 diag::err_inline_non_function); 4898 4899 if (DS.isVirtualSpecified()) 4900 Diag(DS.getVirtualSpecLoc(), 4901 diag::err_virtual_non_function); 4902 4903 if (DS.isExplicitSpecified()) 4904 Diag(DS.getExplicitSpecLoc(), 4905 diag::err_explicit_non_function); 4906 4907 if (DS.isNoreturnSpecified()) 4908 Diag(DS.getNoreturnSpecLoc(), 4909 diag::err_noreturn_non_function); 4910 } 4911 4912 NamedDecl* 4913 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4914 TypeSourceInfo *TInfo, LookupResult &Previous) { 4915 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4916 if (D.getCXXScopeSpec().isSet()) { 4917 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4918 << D.getCXXScopeSpec().getRange(); 4919 D.setInvalidType(); 4920 // Pretend we didn't see the scope specifier. 4921 DC = CurContext; 4922 Previous.clear(); 4923 } 4924 4925 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4926 4927 if (D.getDeclSpec().isConstexprSpecified()) 4928 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4929 << 1; 4930 4931 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4932 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4933 << D.getName().getSourceRange(); 4934 return nullptr; 4935 } 4936 4937 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4938 if (!NewTD) return nullptr; 4939 4940 // Handle attributes prior to checking for duplicates in MergeVarDecl 4941 ProcessDeclAttributes(S, NewTD, D); 4942 4943 CheckTypedefForVariablyModifiedType(S, NewTD); 4944 4945 bool Redeclaration = D.isRedeclaration(); 4946 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4947 D.setRedeclaration(Redeclaration); 4948 return ND; 4949 } 4950 4951 void 4952 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4953 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4954 // then it shall have block scope. 4955 // Note that variably modified types must be fixed before merging the decl so 4956 // that redeclarations will match. 4957 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4958 QualType T = TInfo->getType(); 4959 if (T->isVariablyModifiedType()) { 4960 getCurFunction()->setHasBranchProtectedScope(); 4961 4962 if (S->getFnParent() == nullptr) { 4963 bool SizeIsNegative; 4964 llvm::APSInt Oversized; 4965 TypeSourceInfo *FixedTInfo = 4966 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4967 SizeIsNegative, 4968 Oversized); 4969 if (FixedTInfo) { 4970 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4971 NewTD->setTypeSourceInfo(FixedTInfo); 4972 } else { 4973 if (SizeIsNegative) 4974 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4975 else if (T->isVariableArrayType()) 4976 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4977 else if (Oversized.getBoolValue()) 4978 Diag(NewTD->getLocation(), diag::err_array_too_large) 4979 << Oversized.toString(10); 4980 else 4981 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4982 NewTD->setInvalidDecl(); 4983 } 4984 } 4985 } 4986 } 4987 4988 4989 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4990 /// declares a typedef-name, either using the 'typedef' type specifier or via 4991 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4992 NamedDecl* 4993 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4994 LookupResult &Previous, bool &Redeclaration) { 4995 // Merge the decl with the existing one if appropriate. If the decl is 4996 // in an outer scope, it isn't the same thing. 4997 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4998 /*AllowInlineNamespace*/false); 4999 filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous); 5000 if (!Previous.empty()) { 5001 Redeclaration = true; 5002 MergeTypedefNameDecl(NewTD, Previous); 5003 } 5004 5005 // If this is the C FILE type, notify the AST context. 5006 if (IdentifierInfo *II = NewTD->getIdentifier()) 5007 if (!NewTD->isInvalidDecl() && 5008 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5009 if (II->isStr("FILE")) 5010 Context.setFILEDecl(NewTD); 5011 else if (II->isStr("jmp_buf")) 5012 Context.setjmp_bufDecl(NewTD); 5013 else if (II->isStr("sigjmp_buf")) 5014 Context.setsigjmp_bufDecl(NewTD); 5015 else if (II->isStr("ucontext_t")) 5016 Context.setucontext_tDecl(NewTD); 5017 } 5018 5019 return NewTD; 5020 } 5021 5022 /// \brief Determines whether the given declaration is an out-of-scope 5023 /// previous declaration. 5024 /// 5025 /// This routine should be invoked when name lookup has found a 5026 /// previous declaration (PrevDecl) that is not in the scope where a 5027 /// new declaration by the same name is being introduced. If the new 5028 /// declaration occurs in a local scope, previous declarations with 5029 /// linkage may still be considered previous declarations (C99 5030 /// 6.2.2p4-5, C++ [basic.link]p6). 5031 /// 5032 /// \param PrevDecl the previous declaration found by name 5033 /// lookup 5034 /// 5035 /// \param DC the context in which the new declaration is being 5036 /// declared. 5037 /// 5038 /// \returns true if PrevDecl is an out-of-scope previous declaration 5039 /// for a new delcaration with the same name. 5040 static bool 5041 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5042 ASTContext &Context) { 5043 if (!PrevDecl) 5044 return false; 5045 5046 if (!PrevDecl->hasLinkage()) 5047 return false; 5048 5049 if (Context.getLangOpts().CPlusPlus) { 5050 // C++ [basic.link]p6: 5051 // If there is a visible declaration of an entity with linkage 5052 // having the same name and type, ignoring entities declared 5053 // outside the innermost enclosing namespace scope, the block 5054 // scope declaration declares that same entity and receives the 5055 // linkage of the previous declaration. 5056 DeclContext *OuterContext = DC->getRedeclContext(); 5057 if (!OuterContext->isFunctionOrMethod()) 5058 // This rule only applies to block-scope declarations. 5059 return false; 5060 5061 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5062 if (PrevOuterContext->isRecord()) 5063 // We found a member function: ignore it. 5064 return false; 5065 5066 // Find the innermost enclosing namespace for the new and 5067 // previous declarations. 5068 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5069 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5070 5071 // The previous declaration is in a different namespace, so it 5072 // isn't the same function. 5073 if (!OuterContext->Equals(PrevOuterContext)) 5074 return false; 5075 } 5076 5077 return true; 5078 } 5079 5080 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5081 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5082 if (!SS.isSet()) return; 5083 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5084 } 5085 5086 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5087 QualType type = decl->getType(); 5088 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5089 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5090 // Various kinds of declaration aren't allowed to be __autoreleasing. 5091 unsigned kind = -1U; 5092 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5093 if (var->hasAttr<BlocksAttr>()) 5094 kind = 0; // __block 5095 else if (!var->hasLocalStorage()) 5096 kind = 1; // global 5097 } else if (isa<ObjCIvarDecl>(decl)) { 5098 kind = 3; // ivar 5099 } else if (isa<FieldDecl>(decl)) { 5100 kind = 2; // field 5101 } 5102 5103 if (kind != -1U) { 5104 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5105 << kind; 5106 } 5107 } else if (lifetime == Qualifiers::OCL_None) { 5108 // Try to infer lifetime. 5109 if (!type->isObjCLifetimeType()) 5110 return false; 5111 5112 lifetime = type->getObjCARCImplicitLifetime(); 5113 type = Context.getLifetimeQualifiedType(type, lifetime); 5114 decl->setType(type); 5115 } 5116 5117 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5118 // Thread-local variables cannot have lifetime. 5119 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5120 var->getTLSKind()) { 5121 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5122 << var->getType(); 5123 return true; 5124 } 5125 } 5126 5127 return false; 5128 } 5129 5130 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5131 // Ensure that an auto decl is deduced otherwise the checks below might cache 5132 // the wrong linkage. 5133 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5134 5135 // 'weak' only applies to declarations with external linkage. 5136 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5137 if (!ND.isExternallyVisible()) { 5138 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5139 ND.dropAttr<WeakAttr>(); 5140 } 5141 } 5142 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5143 if (ND.isExternallyVisible()) { 5144 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5145 ND.dropAttr<WeakRefAttr>(); 5146 ND.dropAttr<AliasAttr>(); 5147 } 5148 } 5149 5150 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5151 if (VD->hasInit()) { 5152 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5153 assert(VD->isThisDeclarationADefinition() && 5154 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5155 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD; 5156 VD->dropAttr<AliasAttr>(); 5157 } 5158 } 5159 } 5160 5161 // 'selectany' only applies to externally visible varable declarations. 5162 // It does not apply to functions. 5163 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5164 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5165 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 5166 ND.dropAttr<SelectAnyAttr>(); 5167 } 5168 } 5169 5170 // dll attributes require external linkage. 5171 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5172 if (!ND.isExternallyVisible()) { 5173 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5174 << &ND << Attr; 5175 ND.setInvalidDecl(); 5176 } 5177 } 5178 } 5179 5180 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5181 NamedDecl *NewDecl, 5182 bool IsSpecialization) { 5183 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5184 OldDecl = OldTD->getTemplatedDecl(); 5185 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5186 NewDecl = NewTD->getTemplatedDecl(); 5187 5188 if (!OldDecl || !NewDecl) 5189 return; 5190 5191 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5192 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5193 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5194 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5195 5196 // dllimport and dllexport are inheritable attributes so we have to exclude 5197 // inherited attribute instances. 5198 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5199 (NewExportAttr && !NewExportAttr->isInherited()); 5200 5201 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5202 // the only exception being explicit specializations. 5203 // Implicitly generated declarations are also excluded for now because there 5204 // is no other way to switch these to use dllimport or dllexport. 5205 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5206 5207 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5208 // If the declaration hasn't been used yet, allow with a warning for 5209 // free functions and global variables. 5210 bool JustWarn = false; 5211 if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) { 5212 auto *VD = dyn_cast<VarDecl>(OldDecl); 5213 if (VD && !VD->getDescribedVarTemplate()) 5214 JustWarn = true; 5215 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5216 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5217 JustWarn = true; 5218 } 5219 5220 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5221 : diag::err_attribute_dll_redeclaration; 5222 S.Diag(NewDecl->getLocation(), DiagID) 5223 << NewDecl 5224 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5225 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5226 if (!JustWarn) { 5227 NewDecl->setInvalidDecl(); 5228 return; 5229 } 5230 } 5231 5232 // A redeclaration is not allowed to drop a dllimport attribute, the only 5233 // exceptions being inline function definitions, local extern declarations, 5234 // and qualified friend declarations. 5235 // NB: MSVC converts such a declaration to dllexport. 5236 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5237 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5238 // Ignore static data because out-of-line definitions are diagnosed 5239 // separately. 5240 IsStaticDataMember = VD->isStaticDataMember(); 5241 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5242 IsInline = FD->isInlined(); 5243 IsQualifiedFriend = FD->getQualifier() && 5244 FD->getFriendObjectKind() == Decl::FOK_Declared; 5245 } 5246 5247 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5248 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5249 S.Diag(NewDecl->getLocation(), 5250 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5251 << NewDecl << OldImportAttr; 5252 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5253 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5254 OldDecl->dropAttr<DLLImportAttr>(); 5255 NewDecl->dropAttr<DLLImportAttr>(); 5256 } else if (IsInline && OldImportAttr && 5257 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5258 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5259 OldDecl->dropAttr<DLLImportAttr>(); 5260 NewDecl->dropAttr<DLLImportAttr>(); 5261 S.Diag(NewDecl->getLocation(), 5262 diag::warn_dllimport_dropped_from_inline_function) 5263 << NewDecl << OldImportAttr; 5264 } 5265 } 5266 5267 /// Given that we are within the definition of the given function, 5268 /// will that definition behave like C99's 'inline', where the 5269 /// definition is discarded except for optimization purposes? 5270 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5271 // Try to avoid calling GetGVALinkageForFunction. 5272 5273 // All cases of this require the 'inline' keyword. 5274 if (!FD->isInlined()) return false; 5275 5276 // This is only possible in C++ with the gnu_inline attribute. 5277 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5278 return false; 5279 5280 // Okay, go ahead and call the relatively-more-expensive function. 5281 5282 #ifndef NDEBUG 5283 // AST quite reasonably asserts that it's working on a function 5284 // definition. We don't really have a way to tell it that we're 5285 // currently defining the function, so just lie to it in +Asserts 5286 // builds. This is an awful hack. 5287 FD->setLazyBody(1); 5288 #endif 5289 5290 bool isC99Inline = 5291 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5292 5293 #ifndef NDEBUG 5294 FD->setLazyBody(0); 5295 #endif 5296 5297 return isC99Inline; 5298 } 5299 5300 /// Determine whether a variable is extern "C" prior to attaching 5301 /// an initializer. We can't just call isExternC() here, because that 5302 /// will also compute and cache whether the declaration is externally 5303 /// visible, which might change when we attach the initializer. 5304 /// 5305 /// This can only be used if the declaration is known to not be a 5306 /// redeclaration of an internal linkage declaration. 5307 /// 5308 /// For instance: 5309 /// 5310 /// auto x = []{}; 5311 /// 5312 /// Attaching the initializer here makes this declaration not externally 5313 /// visible, because its type has internal linkage. 5314 /// 5315 /// FIXME: This is a hack. 5316 template<typename T> 5317 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5318 if (S.getLangOpts().CPlusPlus) { 5319 // In C++, the overloadable attribute negates the effects of extern "C". 5320 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5321 return false; 5322 } 5323 return D->isExternC(); 5324 } 5325 5326 static bool shouldConsiderLinkage(const VarDecl *VD) { 5327 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5328 if (DC->isFunctionOrMethod()) 5329 return VD->hasExternalStorage(); 5330 if (DC->isFileContext()) 5331 return true; 5332 if (DC->isRecord()) 5333 return false; 5334 llvm_unreachable("Unexpected context"); 5335 } 5336 5337 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5338 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5339 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5340 return true; 5341 if (DC->isRecord()) 5342 return false; 5343 llvm_unreachable("Unexpected context"); 5344 } 5345 5346 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5347 AttributeList::Kind Kind) { 5348 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5349 if (L->getKind() == Kind) 5350 return true; 5351 return false; 5352 } 5353 5354 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5355 AttributeList::Kind Kind) { 5356 // Check decl attributes on the DeclSpec. 5357 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5358 return true; 5359 5360 // Walk the declarator structure, checking decl attributes that were in a type 5361 // position to the decl itself. 5362 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5363 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5364 return true; 5365 } 5366 5367 // Finally, check attributes on the decl itself. 5368 return hasParsedAttr(S, PD.getAttributes(), Kind); 5369 } 5370 5371 /// Adjust the \c DeclContext for a function or variable that might be a 5372 /// function-local external declaration. 5373 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5374 if (!DC->isFunctionOrMethod()) 5375 return false; 5376 5377 // If this is a local extern function or variable declared within a function 5378 // template, don't add it into the enclosing namespace scope until it is 5379 // instantiated; it might have a dependent type right now. 5380 if (DC->isDependentContext()) 5381 return true; 5382 5383 // C++11 [basic.link]p7: 5384 // When a block scope declaration of an entity with linkage is not found to 5385 // refer to some other declaration, then that entity is a member of the 5386 // innermost enclosing namespace. 5387 // 5388 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5389 // semantically-enclosing namespace, not a lexically-enclosing one. 5390 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5391 DC = DC->getParent(); 5392 return true; 5393 } 5394 5395 NamedDecl * 5396 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5397 TypeSourceInfo *TInfo, LookupResult &Previous, 5398 MultiTemplateParamsArg TemplateParamLists, 5399 bool &AddToScope) { 5400 QualType R = TInfo->getType(); 5401 DeclarationName Name = GetNameForDeclarator(D).getName(); 5402 5403 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5404 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5405 5406 // dllimport globals without explicit storage class are treated as extern. We 5407 // have to change the storage class this early to get the right DeclContext. 5408 if (SC == SC_None && !DC->isRecord() && 5409 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5410 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5411 SC = SC_Extern; 5412 5413 DeclContext *OriginalDC = DC; 5414 bool IsLocalExternDecl = SC == SC_Extern && 5415 adjustContextForLocalExternDecl(DC); 5416 5417 if (getLangOpts().OpenCL) { 5418 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5419 QualType NR = R; 5420 while (NR->isPointerType()) { 5421 if (NR->isFunctionPointerType()) { 5422 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5423 D.setInvalidType(); 5424 break; 5425 } 5426 NR = NR->getPointeeType(); 5427 } 5428 5429 if (!getOpenCLOptions().cl_khr_fp16) { 5430 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5431 // half array type (unless the cl_khr_fp16 extension is enabled). 5432 if (Context.getBaseElementType(R)->isHalfType()) { 5433 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5434 D.setInvalidType(); 5435 } 5436 } 5437 } 5438 5439 if (SCSpec == DeclSpec::SCS_mutable) { 5440 // mutable can only appear on non-static class members, so it's always 5441 // an error here 5442 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5443 D.setInvalidType(); 5444 SC = SC_None; 5445 } 5446 5447 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5448 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5449 D.getDeclSpec().getStorageClassSpecLoc())) { 5450 // In C++11, the 'register' storage class specifier is deprecated. 5451 // Suppress the warning in system macros, it's used in macros in some 5452 // popular C system headers, such as in glibc's htonl() macro. 5453 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5454 diag::warn_deprecated_register) 5455 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5456 } 5457 5458 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5459 if (!II) { 5460 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5461 << Name; 5462 return nullptr; 5463 } 5464 5465 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5466 5467 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5468 // C99 6.9p2: The storage-class specifiers auto and register shall not 5469 // appear in the declaration specifiers in an external declaration. 5470 // Global Register+Asm is a GNU extension we support. 5471 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5472 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5473 D.setInvalidType(); 5474 } 5475 } 5476 5477 if (getLangOpts().OpenCL) { 5478 // Set up the special work-group-local storage class for variables in the 5479 // OpenCL __local address space. 5480 if (R.getAddressSpace() == LangAS::opencl_local) { 5481 SC = SC_OpenCLWorkGroupLocal; 5482 } 5483 5484 // OpenCL v1.2 s6.9.b p4: 5485 // The sampler type cannot be used with the __local and __global address 5486 // space qualifiers. 5487 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5488 R.getAddressSpace() == LangAS::opencl_global)) { 5489 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5490 } 5491 5492 // OpenCL 1.2 spec, p6.9 r: 5493 // The event type cannot be used to declare a program scope variable. 5494 // The event type cannot be used with the __local, __constant and __global 5495 // address space qualifiers. 5496 if (R->isEventT()) { 5497 if (S->getParent() == nullptr) { 5498 Diag(D.getLocStart(), diag::err_event_t_global_var); 5499 D.setInvalidType(); 5500 } 5501 5502 if (R.getAddressSpace()) { 5503 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5504 D.setInvalidType(); 5505 } 5506 } 5507 } 5508 5509 bool IsExplicitSpecialization = false; 5510 bool IsVariableTemplateSpecialization = false; 5511 bool IsPartialSpecialization = false; 5512 bool IsVariableTemplate = false; 5513 VarDecl *NewVD = nullptr; 5514 VarTemplateDecl *NewTemplate = nullptr; 5515 TemplateParameterList *TemplateParams = nullptr; 5516 if (!getLangOpts().CPlusPlus) { 5517 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5518 D.getIdentifierLoc(), II, 5519 R, TInfo, SC); 5520 5521 if (D.isInvalidType()) 5522 NewVD->setInvalidDecl(); 5523 } else { 5524 bool Invalid = false; 5525 5526 if (DC->isRecord() && !CurContext->isRecord()) { 5527 // This is an out-of-line definition of a static data member. 5528 switch (SC) { 5529 case SC_None: 5530 break; 5531 case SC_Static: 5532 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5533 diag::err_static_out_of_line) 5534 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5535 break; 5536 case SC_Auto: 5537 case SC_Register: 5538 case SC_Extern: 5539 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5540 // to names of variables declared in a block or to function parameters. 5541 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5542 // of class members 5543 5544 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5545 diag::err_storage_class_for_static_member) 5546 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5547 break; 5548 case SC_PrivateExtern: 5549 llvm_unreachable("C storage class in c++!"); 5550 case SC_OpenCLWorkGroupLocal: 5551 llvm_unreachable("OpenCL storage class in c++!"); 5552 } 5553 } 5554 5555 if (SC == SC_Static && CurContext->isRecord()) { 5556 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5557 if (RD->isLocalClass()) 5558 Diag(D.getIdentifierLoc(), 5559 diag::err_static_data_member_not_allowed_in_local_class) 5560 << Name << RD->getDeclName(); 5561 5562 // C++98 [class.union]p1: If a union contains a static data member, 5563 // the program is ill-formed. C++11 drops this restriction. 5564 if (RD->isUnion()) 5565 Diag(D.getIdentifierLoc(), 5566 getLangOpts().CPlusPlus11 5567 ? diag::warn_cxx98_compat_static_data_member_in_union 5568 : diag::ext_static_data_member_in_union) << Name; 5569 // We conservatively disallow static data members in anonymous structs. 5570 else if (!RD->getDeclName()) 5571 Diag(D.getIdentifierLoc(), 5572 diag::err_static_data_member_not_allowed_in_anon_struct) 5573 << Name << RD->isUnion(); 5574 } 5575 } 5576 5577 // Match up the template parameter lists with the scope specifier, then 5578 // determine whether we have a template or a template specialization. 5579 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5580 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5581 D.getCXXScopeSpec(), 5582 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5583 ? D.getName().TemplateId 5584 : nullptr, 5585 TemplateParamLists, 5586 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5587 5588 if (TemplateParams) { 5589 if (!TemplateParams->size() && 5590 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5591 // There is an extraneous 'template<>' for this variable. Complain 5592 // about it, but allow the declaration of the variable. 5593 Diag(TemplateParams->getTemplateLoc(), 5594 diag::err_template_variable_noparams) 5595 << II 5596 << SourceRange(TemplateParams->getTemplateLoc(), 5597 TemplateParams->getRAngleLoc()); 5598 TemplateParams = nullptr; 5599 } else { 5600 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5601 // This is an explicit specialization or a partial specialization. 5602 // FIXME: Check that we can declare a specialization here. 5603 IsVariableTemplateSpecialization = true; 5604 IsPartialSpecialization = TemplateParams->size() > 0; 5605 } else { // if (TemplateParams->size() > 0) 5606 // This is a template declaration. 5607 IsVariableTemplate = true; 5608 5609 // Check that we can declare a template here. 5610 if (CheckTemplateDeclScope(S, TemplateParams)) 5611 return nullptr; 5612 5613 // Only C++1y supports variable templates (N3651). 5614 Diag(D.getIdentifierLoc(), 5615 getLangOpts().CPlusPlus14 5616 ? diag::warn_cxx11_compat_variable_template 5617 : diag::ext_variable_template); 5618 } 5619 } 5620 } else { 5621 assert( 5622 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 5623 "should have a 'template<>' for this decl"); 5624 } 5625 5626 if (IsVariableTemplateSpecialization) { 5627 SourceLocation TemplateKWLoc = 5628 TemplateParamLists.size() > 0 5629 ? TemplateParamLists[0]->getTemplateLoc() 5630 : SourceLocation(); 5631 DeclResult Res = ActOnVarTemplateSpecialization( 5632 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5633 IsPartialSpecialization); 5634 if (Res.isInvalid()) 5635 return nullptr; 5636 NewVD = cast<VarDecl>(Res.get()); 5637 AddToScope = false; 5638 } else 5639 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5640 D.getIdentifierLoc(), II, R, TInfo, SC); 5641 5642 // If this is supposed to be a variable template, create it as such. 5643 if (IsVariableTemplate) { 5644 NewTemplate = 5645 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5646 TemplateParams, NewVD); 5647 NewVD->setDescribedVarTemplate(NewTemplate); 5648 } 5649 5650 // If this decl has an auto type in need of deduction, make a note of the 5651 // Decl so we can diagnose uses of it in its own initializer. 5652 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5653 ParsingInitForAutoVars.insert(NewVD); 5654 5655 if (D.isInvalidType() || Invalid) { 5656 NewVD->setInvalidDecl(); 5657 if (NewTemplate) 5658 NewTemplate->setInvalidDecl(); 5659 } 5660 5661 SetNestedNameSpecifier(NewVD, D); 5662 5663 // If we have any template parameter lists that don't directly belong to 5664 // the variable (matching the scope specifier), store them. 5665 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5666 if (TemplateParamLists.size() > VDTemplateParamLists) 5667 NewVD->setTemplateParameterListsInfo( 5668 Context, TemplateParamLists.size() - VDTemplateParamLists, 5669 TemplateParamLists.data()); 5670 5671 if (D.getDeclSpec().isConstexprSpecified()) 5672 NewVD->setConstexpr(true); 5673 } 5674 5675 // Set the lexical context. If the declarator has a C++ scope specifier, the 5676 // lexical context will be different from the semantic context. 5677 NewVD->setLexicalDeclContext(CurContext); 5678 if (NewTemplate) 5679 NewTemplate->setLexicalDeclContext(CurContext); 5680 5681 if (IsLocalExternDecl) 5682 NewVD->setLocalExternDecl(); 5683 5684 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5685 // C++11 [dcl.stc]p4: 5686 // When thread_local is applied to a variable of block scope the 5687 // storage-class-specifier static is implied if it does not appear 5688 // explicitly. 5689 // Core issue: 'static' is not implied if the variable is declared 5690 // 'extern'. 5691 if (NewVD->hasLocalStorage() && 5692 (SCSpec != DeclSpec::SCS_unspecified || 5693 TSCS != DeclSpec::TSCS_thread_local || 5694 !DC->isFunctionOrMethod())) 5695 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5696 diag::err_thread_non_global) 5697 << DeclSpec::getSpecifierName(TSCS); 5698 else if (!Context.getTargetInfo().isTLSSupported()) 5699 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5700 diag::err_thread_unsupported); 5701 else 5702 NewVD->setTSCSpec(TSCS); 5703 } 5704 5705 // C99 6.7.4p3 5706 // An inline definition of a function with external linkage shall 5707 // not contain a definition of a modifiable object with static or 5708 // thread storage duration... 5709 // We only apply this when the function is required to be defined 5710 // elsewhere, i.e. when the function is not 'extern inline'. Note 5711 // that a local variable with thread storage duration still has to 5712 // be marked 'static'. Also note that it's possible to get these 5713 // semantics in C++ using __attribute__((gnu_inline)). 5714 if (SC == SC_Static && S->getFnParent() != nullptr && 5715 !NewVD->getType().isConstQualified()) { 5716 FunctionDecl *CurFD = getCurFunctionDecl(); 5717 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5718 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5719 diag::warn_static_local_in_extern_inline); 5720 MaybeSuggestAddingStaticToDecl(CurFD); 5721 } 5722 } 5723 5724 if (D.getDeclSpec().isModulePrivateSpecified()) { 5725 if (IsVariableTemplateSpecialization) 5726 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5727 << (IsPartialSpecialization ? 1 : 0) 5728 << FixItHint::CreateRemoval( 5729 D.getDeclSpec().getModulePrivateSpecLoc()); 5730 else if (IsExplicitSpecialization) 5731 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5732 << 2 5733 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5734 else if (NewVD->hasLocalStorage()) 5735 Diag(NewVD->getLocation(), diag::err_module_private_local) 5736 << 0 << NewVD->getDeclName() 5737 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5738 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5739 else { 5740 NewVD->setModulePrivate(); 5741 if (NewTemplate) 5742 NewTemplate->setModulePrivate(); 5743 } 5744 } 5745 5746 // Handle attributes prior to checking for duplicates in MergeVarDecl 5747 ProcessDeclAttributes(S, NewVD, D); 5748 5749 if (getLangOpts().CUDA) { 5750 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5751 // storage [duration]." 5752 if (SC == SC_None && S->getFnParent() != nullptr && 5753 (NewVD->hasAttr<CUDASharedAttr>() || 5754 NewVD->hasAttr<CUDAConstantAttr>())) { 5755 NewVD->setStorageClass(SC_Static); 5756 } 5757 } 5758 5759 // Ensure that dllimport globals without explicit storage class are treated as 5760 // extern. The storage class is set above using parsed attributes. Now we can 5761 // check the VarDecl itself. 5762 assert(!NewVD->hasAttr<DLLImportAttr>() || 5763 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5764 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5765 5766 // In auto-retain/release, infer strong retension for variables of 5767 // retainable type. 5768 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5769 NewVD->setInvalidDecl(); 5770 5771 // Handle GNU asm-label extension (encoded as an attribute). 5772 if (Expr *E = (Expr*)D.getAsmLabel()) { 5773 // The parser guarantees this is a string. 5774 StringLiteral *SE = cast<StringLiteral>(E); 5775 StringRef Label = SE->getString(); 5776 if (S->getFnParent() != nullptr) { 5777 switch (SC) { 5778 case SC_None: 5779 case SC_Auto: 5780 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5781 break; 5782 case SC_Register: 5783 // Local Named register 5784 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5785 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5786 break; 5787 case SC_Static: 5788 case SC_Extern: 5789 case SC_PrivateExtern: 5790 case SC_OpenCLWorkGroupLocal: 5791 break; 5792 } 5793 } else if (SC == SC_Register) { 5794 // Global Named register 5795 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5796 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5797 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5798 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5799 NewVD->setInvalidDecl(true); 5800 } 5801 } 5802 5803 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5804 Context, Label, 0)); 5805 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5806 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5807 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5808 if (I != ExtnameUndeclaredIdentifiers.end()) { 5809 NewVD->addAttr(I->second); 5810 ExtnameUndeclaredIdentifiers.erase(I); 5811 } 5812 } 5813 5814 // Diagnose shadowed variables before filtering for scope. 5815 if (D.getCXXScopeSpec().isEmpty()) 5816 CheckShadow(S, NewVD, Previous); 5817 5818 // Don't consider existing declarations that are in a different 5819 // scope and are out-of-semantic-context declarations (if the new 5820 // declaration has linkage). 5821 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5822 D.getCXXScopeSpec().isNotEmpty() || 5823 IsExplicitSpecialization || 5824 IsVariableTemplateSpecialization); 5825 5826 // Check whether the previous declaration is in the same block scope. This 5827 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5828 if (getLangOpts().CPlusPlus && 5829 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5830 NewVD->setPreviousDeclInSameBlockScope( 5831 Previous.isSingleResult() && !Previous.isShadowed() && 5832 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5833 5834 if (!getLangOpts().CPlusPlus) { 5835 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5836 } else { 5837 // If this is an explicit specialization of a static data member, check it. 5838 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5839 CheckMemberSpecialization(NewVD, Previous)) 5840 NewVD->setInvalidDecl(); 5841 5842 // Merge the decl with the existing one if appropriate. 5843 if (!Previous.empty()) { 5844 if (Previous.isSingleResult() && 5845 isa<FieldDecl>(Previous.getFoundDecl()) && 5846 D.getCXXScopeSpec().isSet()) { 5847 // The user tried to define a non-static data member 5848 // out-of-line (C++ [dcl.meaning]p1). 5849 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5850 << D.getCXXScopeSpec().getRange(); 5851 Previous.clear(); 5852 NewVD->setInvalidDecl(); 5853 } 5854 } else if (D.getCXXScopeSpec().isSet()) { 5855 // No previous declaration in the qualifying scope. 5856 Diag(D.getIdentifierLoc(), diag::err_no_member) 5857 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5858 << D.getCXXScopeSpec().getRange(); 5859 NewVD->setInvalidDecl(); 5860 } 5861 5862 if (!IsVariableTemplateSpecialization) 5863 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5864 5865 if (NewTemplate) { 5866 VarTemplateDecl *PrevVarTemplate = 5867 NewVD->getPreviousDecl() 5868 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5869 : nullptr; 5870 5871 // Check the template parameter list of this declaration, possibly 5872 // merging in the template parameter list from the previous variable 5873 // template declaration. 5874 if (CheckTemplateParameterList( 5875 TemplateParams, 5876 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5877 : nullptr, 5878 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5879 DC->isDependentContext()) 5880 ? TPC_ClassTemplateMember 5881 : TPC_VarTemplate)) 5882 NewVD->setInvalidDecl(); 5883 5884 // If we are providing an explicit specialization of a static variable 5885 // template, make a note of that. 5886 if (PrevVarTemplate && 5887 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5888 PrevVarTemplate->setMemberSpecialization(); 5889 } 5890 } 5891 5892 ProcessPragmaWeak(S, NewVD); 5893 5894 // If this is the first declaration of an extern C variable, update 5895 // the map of such variables. 5896 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5897 isIncompleteDeclExternC(*this, NewVD)) 5898 RegisterLocallyScopedExternCDecl(NewVD, S); 5899 5900 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5901 Decl *ManglingContextDecl; 5902 if (MangleNumberingContext *MCtx = 5903 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5904 ManglingContextDecl)) { 5905 Context.setManglingNumber( 5906 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5907 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5908 } 5909 } 5910 5911 if (D.isRedeclaration() && !Previous.empty()) { 5912 checkDLLAttributeRedeclaration( 5913 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5914 IsExplicitSpecialization); 5915 } 5916 5917 if (NewTemplate) { 5918 if (NewVD->isInvalidDecl()) 5919 NewTemplate->setInvalidDecl(); 5920 ActOnDocumentableDecl(NewTemplate); 5921 return NewTemplate; 5922 } 5923 5924 return NewVD; 5925 } 5926 5927 /// \brief Diagnose variable or built-in function shadowing. Implements 5928 /// -Wshadow. 5929 /// 5930 /// This method is called whenever a VarDecl is added to a "useful" 5931 /// scope. 5932 /// 5933 /// \param S the scope in which the shadowing name is being declared 5934 /// \param R the lookup of the name 5935 /// 5936 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5937 // Return if warning is ignored. 5938 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 5939 return; 5940 5941 // Don't diagnose declarations at file scope. 5942 if (D->hasGlobalStorage()) 5943 return; 5944 5945 DeclContext *NewDC = D->getDeclContext(); 5946 5947 // Only diagnose if we're shadowing an unambiguous field or variable. 5948 if (R.getResultKind() != LookupResult::Found) 5949 return; 5950 5951 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5952 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5953 return; 5954 5955 // Fields are not shadowed by variables in C++ static methods. 5956 if (isa<FieldDecl>(ShadowedDecl)) 5957 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5958 if (MD->isStatic()) 5959 return; 5960 5961 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5962 if (shadowedVar->isExternC()) { 5963 // For shadowing external vars, make sure that we point to the global 5964 // declaration, not a locally scoped extern declaration. 5965 for (auto I : shadowedVar->redecls()) 5966 if (I->isFileVarDecl()) { 5967 ShadowedDecl = I; 5968 break; 5969 } 5970 } 5971 5972 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5973 5974 // Only warn about certain kinds of shadowing for class members. 5975 if (NewDC && NewDC->isRecord()) { 5976 // In particular, don't warn about shadowing non-class members. 5977 if (!OldDC->isRecord()) 5978 return; 5979 5980 // TODO: should we warn about static data members shadowing 5981 // static data members from base classes? 5982 5983 // TODO: don't diagnose for inaccessible shadowed members. 5984 // This is hard to do perfectly because we might friend the 5985 // shadowing context, but that's just a false negative. 5986 } 5987 5988 // Determine what kind of declaration we're shadowing. 5989 unsigned Kind; 5990 if (isa<RecordDecl>(OldDC)) { 5991 if (isa<FieldDecl>(ShadowedDecl)) 5992 Kind = 3; // field 5993 else 5994 Kind = 2; // static data member 5995 } else if (OldDC->isFileContext()) 5996 Kind = 1; // global 5997 else 5998 Kind = 0; // local 5999 6000 DeclarationName Name = R.getLookupName(); 6001 6002 // Emit warning and note. 6003 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6004 return; 6005 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6006 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6007 } 6008 6009 /// \brief Check -Wshadow without the advantage of a previous lookup. 6010 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6011 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6012 return; 6013 6014 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6015 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6016 LookupName(R, S); 6017 CheckShadow(S, D, R); 6018 } 6019 6020 /// Check for conflict between this global or extern "C" declaration and 6021 /// previous global or extern "C" declarations. This is only used in C++. 6022 template<typename T> 6023 static bool checkGlobalOrExternCConflict( 6024 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6025 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6026 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6027 6028 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6029 // The common case: this global doesn't conflict with any extern "C" 6030 // declaration. 6031 return false; 6032 } 6033 6034 if (Prev) { 6035 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6036 // Both the old and new declarations have C language linkage. This is a 6037 // redeclaration. 6038 Previous.clear(); 6039 Previous.addDecl(Prev); 6040 return true; 6041 } 6042 6043 // This is a global, non-extern "C" declaration, and there is a previous 6044 // non-global extern "C" declaration. Diagnose if this is a variable 6045 // declaration. 6046 if (!isa<VarDecl>(ND)) 6047 return false; 6048 } else { 6049 // The declaration is extern "C". Check for any declaration in the 6050 // translation unit which might conflict. 6051 if (IsGlobal) { 6052 // We have already performed the lookup into the translation unit. 6053 IsGlobal = false; 6054 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6055 I != E; ++I) { 6056 if (isa<VarDecl>(*I)) { 6057 Prev = *I; 6058 break; 6059 } 6060 } 6061 } else { 6062 DeclContext::lookup_result R = 6063 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6064 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6065 I != E; ++I) { 6066 if (isa<VarDecl>(*I)) { 6067 Prev = *I; 6068 break; 6069 } 6070 // FIXME: If we have any other entity with this name in global scope, 6071 // the declaration is ill-formed, but that is a defect: it breaks the 6072 // 'stat' hack, for instance. Only variables can have mangled name 6073 // clashes with extern "C" declarations, so only they deserve a 6074 // diagnostic. 6075 } 6076 } 6077 6078 if (!Prev) 6079 return false; 6080 } 6081 6082 // Use the first declaration's location to ensure we point at something which 6083 // is lexically inside an extern "C" linkage-spec. 6084 assert(Prev && "should have found a previous declaration to diagnose"); 6085 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6086 Prev = FD->getFirstDecl(); 6087 else 6088 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6089 6090 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6091 << IsGlobal << ND; 6092 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6093 << IsGlobal; 6094 return false; 6095 } 6096 6097 /// Apply special rules for handling extern "C" declarations. Returns \c true 6098 /// if we have found that this is a redeclaration of some prior entity. 6099 /// 6100 /// Per C++ [dcl.link]p6: 6101 /// Two declarations [for a function or variable] with C language linkage 6102 /// with the same name that appear in different scopes refer to the same 6103 /// [entity]. An entity with C language linkage shall not be declared with 6104 /// the same name as an entity in global scope. 6105 template<typename T> 6106 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6107 LookupResult &Previous) { 6108 if (!S.getLangOpts().CPlusPlus) { 6109 // In C, when declaring a global variable, look for a corresponding 'extern' 6110 // variable declared in function scope. We don't need this in C++, because 6111 // we find local extern decls in the surrounding file-scope DeclContext. 6112 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6113 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6114 Previous.clear(); 6115 Previous.addDecl(Prev); 6116 return true; 6117 } 6118 } 6119 return false; 6120 } 6121 6122 // A declaration in the translation unit can conflict with an extern "C" 6123 // declaration. 6124 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6125 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6126 6127 // An extern "C" declaration can conflict with a declaration in the 6128 // translation unit or can be a redeclaration of an extern "C" declaration 6129 // in another scope. 6130 if (isIncompleteDeclExternC(S,ND)) 6131 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6132 6133 // Neither global nor extern "C": nothing to do. 6134 return false; 6135 } 6136 6137 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6138 // If the decl is already known invalid, don't check it. 6139 if (NewVD->isInvalidDecl()) 6140 return; 6141 6142 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6143 QualType T = TInfo->getType(); 6144 6145 // Defer checking an 'auto' type until its initializer is attached. 6146 if (T->isUndeducedType()) 6147 return; 6148 6149 if (NewVD->hasAttrs()) 6150 CheckAlignasUnderalignment(NewVD); 6151 6152 if (T->isObjCObjectType()) { 6153 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6154 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6155 T = Context.getObjCObjectPointerType(T); 6156 NewVD->setType(T); 6157 } 6158 6159 // Emit an error if an address space was applied to decl with local storage. 6160 // This includes arrays of objects with address space qualifiers, but not 6161 // automatic variables that point to other address spaces. 6162 // ISO/IEC TR 18037 S5.1.2 6163 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6164 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6165 NewVD->setInvalidDecl(); 6166 return; 6167 } 6168 6169 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6170 // __constant address space. 6171 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 6172 && T.getAddressSpace() != LangAS::opencl_constant 6173 && !T->isSamplerT()){ 6174 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 6175 NewVD->setInvalidDecl(); 6176 return; 6177 } 6178 6179 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6180 // scope. 6181 if ((getLangOpts().OpenCLVersion >= 120) 6182 && NewVD->isStaticLocal()) { 6183 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6184 NewVD->setInvalidDecl(); 6185 return; 6186 } 6187 6188 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6189 && !NewVD->hasAttr<BlocksAttr>()) { 6190 if (getLangOpts().getGC() != LangOptions::NonGC) 6191 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6192 else { 6193 assert(!getLangOpts().ObjCAutoRefCount); 6194 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6195 } 6196 } 6197 6198 bool isVM = T->isVariablyModifiedType(); 6199 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6200 NewVD->hasAttr<BlocksAttr>()) 6201 getCurFunction()->setHasBranchProtectedScope(); 6202 6203 if ((isVM && NewVD->hasLinkage()) || 6204 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6205 bool SizeIsNegative; 6206 llvm::APSInt Oversized; 6207 TypeSourceInfo *FixedTInfo = 6208 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6209 SizeIsNegative, Oversized); 6210 if (!FixedTInfo && T->isVariableArrayType()) { 6211 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6212 // FIXME: This won't give the correct result for 6213 // int a[10][n]; 6214 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6215 6216 if (NewVD->isFileVarDecl()) 6217 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6218 << SizeRange; 6219 else if (NewVD->isStaticLocal()) 6220 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6221 << SizeRange; 6222 else 6223 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6224 << SizeRange; 6225 NewVD->setInvalidDecl(); 6226 return; 6227 } 6228 6229 if (!FixedTInfo) { 6230 if (NewVD->isFileVarDecl()) 6231 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6232 else 6233 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6234 NewVD->setInvalidDecl(); 6235 return; 6236 } 6237 6238 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6239 NewVD->setType(FixedTInfo->getType()); 6240 NewVD->setTypeSourceInfo(FixedTInfo); 6241 } 6242 6243 if (T->isVoidType()) { 6244 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6245 // of objects and functions. 6246 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6247 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6248 << T; 6249 NewVD->setInvalidDecl(); 6250 return; 6251 } 6252 } 6253 6254 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6255 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6256 NewVD->setInvalidDecl(); 6257 return; 6258 } 6259 6260 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6261 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6262 NewVD->setInvalidDecl(); 6263 return; 6264 } 6265 6266 if (NewVD->isConstexpr() && !T->isDependentType() && 6267 RequireLiteralType(NewVD->getLocation(), T, 6268 diag::err_constexpr_var_non_literal)) { 6269 NewVD->setInvalidDecl(); 6270 return; 6271 } 6272 } 6273 6274 /// \brief Perform semantic checking on a newly-created variable 6275 /// declaration. 6276 /// 6277 /// This routine performs all of the type-checking required for a 6278 /// variable declaration once it has been built. It is used both to 6279 /// check variables after they have been parsed and their declarators 6280 /// have been translated into a declaration, and to check variables 6281 /// that have been instantiated from a template. 6282 /// 6283 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6284 /// 6285 /// Returns true if the variable declaration is a redeclaration. 6286 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6287 CheckVariableDeclarationType(NewVD); 6288 6289 // If the decl is already known invalid, don't check it. 6290 if (NewVD->isInvalidDecl()) 6291 return false; 6292 6293 // If we did not find anything by this name, look for a non-visible 6294 // extern "C" declaration with the same name. 6295 if (Previous.empty() && 6296 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6297 Previous.setShadowed(); 6298 6299 // Filter out any non-conflicting previous declarations. 6300 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 6301 6302 if (!Previous.empty()) { 6303 MergeVarDecl(NewVD, Previous); 6304 return true; 6305 } 6306 return false; 6307 } 6308 6309 /// \brief Data used with FindOverriddenMethod 6310 struct FindOverriddenMethodData { 6311 Sema *S; 6312 CXXMethodDecl *Method; 6313 }; 6314 6315 /// \brief Member lookup function that determines whether a given C++ 6316 /// method overrides a method in a base class, to be used with 6317 /// CXXRecordDecl::lookupInBases(). 6318 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6319 CXXBasePath &Path, 6320 void *UserData) { 6321 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6322 6323 FindOverriddenMethodData *Data 6324 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6325 6326 DeclarationName Name = Data->Method->getDeclName(); 6327 6328 // FIXME: Do we care about other names here too? 6329 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6330 // We really want to find the base class destructor here. 6331 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6332 CanQualType CT = Data->S->Context.getCanonicalType(T); 6333 6334 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6335 } 6336 6337 for (Path.Decls = BaseRecord->lookup(Name); 6338 !Path.Decls.empty(); 6339 Path.Decls = Path.Decls.slice(1)) { 6340 NamedDecl *D = Path.Decls.front(); 6341 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6342 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6343 return true; 6344 } 6345 } 6346 6347 return false; 6348 } 6349 6350 namespace { 6351 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6352 } 6353 /// \brief Report an error regarding overriding, along with any relevant 6354 /// overriden methods. 6355 /// 6356 /// \param DiagID the primary error to report. 6357 /// \param MD the overriding method. 6358 /// \param OEK which overrides to include as notes. 6359 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6360 OverrideErrorKind OEK = OEK_All) { 6361 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6362 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6363 E = MD->end_overridden_methods(); 6364 I != E; ++I) { 6365 // This check (& the OEK parameter) could be replaced by a predicate, but 6366 // without lambdas that would be overkill. This is still nicer than writing 6367 // out the diag loop 3 times. 6368 if ((OEK == OEK_All) || 6369 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6370 (OEK == OEK_Deleted && (*I)->isDeleted())) 6371 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6372 } 6373 } 6374 6375 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6376 /// and if so, check that it's a valid override and remember it. 6377 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6378 // Look for methods in base classes that this method might override. 6379 CXXBasePaths Paths; 6380 FindOverriddenMethodData Data; 6381 Data.Method = MD; 6382 Data.S = this; 6383 bool hasDeletedOverridenMethods = false; 6384 bool hasNonDeletedOverridenMethods = false; 6385 bool AddedAny = false; 6386 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6387 for (auto *I : Paths.found_decls()) { 6388 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6389 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6390 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6391 !CheckOverridingFunctionAttributes(MD, OldMD) && 6392 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6393 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6394 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6395 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6396 AddedAny = true; 6397 } 6398 } 6399 } 6400 } 6401 6402 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6403 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6404 } 6405 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6406 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6407 } 6408 6409 return AddedAny; 6410 } 6411 6412 namespace { 6413 // Struct for holding all of the extra arguments needed by 6414 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6415 struct ActOnFDArgs { 6416 Scope *S; 6417 Declarator &D; 6418 MultiTemplateParamsArg TemplateParamLists; 6419 bool AddToScope; 6420 }; 6421 } 6422 6423 namespace { 6424 6425 // Callback to only accept typo corrections that have a non-zero edit distance. 6426 // Also only accept corrections that have the same parent decl. 6427 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6428 public: 6429 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6430 CXXRecordDecl *Parent) 6431 : Context(Context), OriginalFD(TypoFD), 6432 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6433 6434 bool ValidateCandidate(const TypoCorrection &candidate) override { 6435 if (candidate.getEditDistance() == 0) 6436 return false; 6437 6438 SmallVector<unsigned, 1> MismatchedParams; 6439 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6440 CDeclEnd = candidate.end(); 6441 CDecl != CDeclEnd; ++CDecl) { 6442 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6443 6444 if (FD && !FD->hasBody() && 6445 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6446 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6447 CXXRecordDecl *Parent = MD->getParent(); 6448 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6449 return true; 6450 } else if (!ExpectedParent) { 6451 return true; 6452 } 6453 } 6454 } 6455 6456 return false; 6457 } 6458 6459 private: 6460 ASTContext &Context; 6461 FunctionDecl *OriginalFD; 6462 CXXRecordDecl *ExpectedParent; 6463 }; 6464 6465 } 6466 6467 /// \brief Generate diagnostics for an invalid function redeclaration. 6468 /// 6469 /// This routine handles generating the diagnostic messages for an invalid 6470 /// function redeclaration, including finding possible similar declarations 6471 /// or performing typo correction if there are no previous declarations with 6472 /// the same name. 6473 /// 6474 /// Returns a NamedDecl iff typo correction was performed and substituting in 6475 /// the new declaration name does not cause new errors. 6476 static NamedDecl *DiagnoseInvalidRedeclaration( 6477 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6478 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6479 DeclarationName Name = NewFD->getDeclName(); 6480 DeclContext *NewDC = NewFD->getDeclContext(); 6481 SmallVector<unsigned, 1> MismatchedParams; 6482 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6483 TypoCorrection Correction; 6484 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6485 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6486 : diag::err_member_decl_does_not_match; 6487 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6488 IsLocalFriend ? Sema::LookupLocalFriendName 6489 : Sema::LookupOrdinaryName, 6490 Sema::ForRedeclaration); 6491 6492 NewFD->setInvalidDecl(); 6493 if (IsLocalFriend) 6494 SemaRef.LookupName(Prev, S); 6495 else 6496 SemaRef.LookupQualifiedName(Prev, NewDC); 6497 assert(!Prev.isAmbiguous() && 6498 "Cannot have an ambiguity in previous-declaration lookup"); 6499 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6500 if (!Prev.empty()) { 6501 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6502 Func != FuncEnd; ++Func) { 6503 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6504 if (FD && 6505 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6506 // Add 1 to the index so that 0 can mean the mismatch didn't 6507 // involve a parameter 6508 unsigned ParamNum = 6509 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6510 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6511 } 6512 } 6513 // If the qualified name lookup yielded nothing, try typo correction 6514 } else if ((Correction = SemaRef.CorrectTypo( 6515 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6516 &ExtraArgs.D.getCXXScopeSpec(), 6517 llvm::make_unique<DifferentNameValidatorCCC>( 6518 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 6519 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6520 // Set up everything for the call to ActOnFunctionDeclarator 6521 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6522 ExtraArgs.D.getIdentifierLoc()); 6523 Previous.clear(); 6524 Previous.setLookupName(Correction.getCorrection()); 6525 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6526 CDeclEnd = Correction.end(); 6527 CDecl != CDeclEnd; ++CDecl) { 6528 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6529 if (FD && !FD->hasBody() && 6530 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6531 Previous.addDecl(FD); 6532 } 6533 } 6534 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6535 6536 NamedDecl *Result; 6537 // Retry building the function declaration with the new previous 6538 // declarations, and with errors suppressed. 6539 { 6540 // Trap errors. 6541 Sema::SFINAETrap Trap(SemaRef); 6542 6543 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6544 // pieces need to verify the typo-corrected C++ declaration and hopefully 6545 // eliminate the need for the parameter pack ExtraArgs. 6546 Result = SemaRef.ActOnFunctionDeclarator( 6547 ExtraArgs.S, ExtraArgs.D, 6548 Correction.getCorrectionDecl()->getDeclContext(), 6549 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6550 ExtraArgs.AddToScope); 6551 6552 if (Trap.hasErrorOccurred()) 6553 Result = nullptr; 6554 } 6555 6556 if (Result) { 6557 // Determine which correction we picked. 6558 Decl *Canonical = Result->getCanonicalDecl(); 6559 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6560 I != E; ++I) 6561 if ((*I)->getCanonicalDecl() == Canonical) 6562 Correction.setCorrectionDecl(*I); 6563 6564 SemaRef.diagnoseTypo( 6565 Correction, 6566 SemaRef.PDiag(IsLocalFriend 6567 ? diag::err_no_matching_local_friend_suggest 6568 : diag::err_member_decl_does_not_match_suggest) 6569 << Name << NewDC << IsDefinition); 6570 return Result; 6571 } 6572 6573 // Pretend the typo correction never occurred 6574 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6575 ExtraArgs.D.getIdentifierLoc()); 6576 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6577 Previous.clear(); 6578 Previous.setLookupName(Name); 6579 } 6580 6581 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6582 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6583 6584 bool NewFDisConst = false; 6585 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6586 NewFDisConst = NewMD->isConst(); 6587 6588 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6589 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6590 NearMatch != NearMatchEnd; ++NearMatch) { 6591 FunctionDecl *FD = NearMatch->first; 6592 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6593 bool FDisConst = MD && MD->isConst(); 6594 bool IsMember = MD || !IsLocalFriend; 6595 6596 // FIXME: These notes are poorly worded for the local friend case. 6597 if (unsigned Idx = NearMatch->second) { 6598 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6599 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6600 if (Loc.isInvalid()) Loc = FD->getLocation(); 6601 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6602 : diag::note_local_decl_close_param_match) 6603 << Idx << FDParam->getType() 6604 << NewFD->getParamDecl(Idx - 1)->getType(); 6605 } else if (FDisConst != NewFDisConst) { 6606 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6607 << NewFDisConst << FD->getSourceRange().getEnd(); 6608 } else 6609 SemaRef.Diag(FD->getLocation(), 6610 IsMember ? diag::note_member_def_close_match 6611 : diag::note_local_decl_close_match); 6612 } 6613 return nullptr; 6614 } 6615 6616 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 6617 switch (D.getDeclSpec().getStorageClassSpec()) { 6618 default: llvm_unreachable("Unknown storage class!"); 6619 case DeclSpec::SCS_auto: 6620 case DeclSpec::SCS_register: 6621 case DeclSpec::SCS_mutable: 6622 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6623 diag::err_typecheck_sclass_func); 6624 D.setInvalidType(); 6625 break; 6626 case DeclSpec::SCS_unspecified: break; 6627 case DeclSpec::SCS_extern: 6628 if (D.getDeclSpec().isExternInLinkageSpec()) 6629 return SC_None; 6630 return SC_Extern; 6631 case DeclSpec::SCS_static: { 6632 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6633 // C99 6.7.1p5: 6634 // The declaration of an identifier for a function that has 6635 // block scope shall have no explicit storage-class specifier 6636 // other than extern 6637 // See also (C++ [dcl.stc]p4). 6638 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6639 diag::err_static_block_func); 6640 break; 6641 } else 6642 return SC_Static; 6643 } 6644 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6645 } 6646 6647 // No explicit storage class has already been returned 6648 return SC_None; 6649 } 6650 6651 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6652 DeclContext *DC, QualType &R, 6653 TypeSourceInfo *TInfo, 6654 StorageClass SC, 6655 bool &IsVirtualOkay) { 6656 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6657 DeclarationName Name = NameInfo.getName(); 6658 6659 FunctionDecl *NewFD = nullptr; 6660 bool isInline = D.getDeclSpec().isInlineSpecified(); 6661 6662 if (!SemaRef.getLangOpts().CPlusPlus) { 6663 // Determine whether the function was written with a 6664 // prototype. This true when: 6665 // - there is a prototype in the declarator, or 6666 // - the type R of the function is some kind of typedef or other reference 6667 // to a type name (which eventually refers to a function type). 6668 bool HasPrototype = 6669 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6670 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6671 6672 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6673 D.getLocStart(), NameInfo, R, 6674 TInfo, SC, isInline, 6675 HasPrototype, false); 6676 if (D.isInvalidType()) 6677 NewFD->setInvalidDecl(); 6678 6679 return NewFD; 6680 } 6681 6682 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6683 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6684 6685 // Check that the return type is not an abstract class type. 6686 // For record types, this is done by the AbstractClassUsageDiagnoser once 6687 // the class has been completely parsed. 6688 if (!DC->isRecord() && 6689 SemaRef.RequireNonAbstractType( 6690 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6691 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6692 D.setInvalidType(); 6693 6694 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6695 // This is a C++ constructor declaration. 6696 assert(DC->isRecord() && 6697 "Constructors can only be declared in a member context"); 6698 6699 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6700 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6701 D.getLocStart(), NameInfo, 6702 R, TInfo, isExplicit, isInline, 6703 /*isImplicitlyDeclared=*/false, 6704 isConstexpr); 6705 6706 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6707 // This is a C++ destructor declaration. 6708 if (DC->isRecord()) { 6709 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6710 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6711 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6712 SemaRef.Context, Record, 6713 D.getLocStart(), 6714 NameInfo, R, TInfo, isInline, 6715 /*isImplicitlyDeclared=*/false); 6716 6717 // If the class is complete, then we now create the implicit exception 6718 // specification. If the class is incomplete or dependent, we can't do 6719 // it yet. 6720 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6721 Record->getDefinition() && !Record->isBeingDefined() && 6722 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6723 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6724 } 6725 6726 IsVirtualOkay = true; 6727 return NewDD; 6728 6729 } else { 6730 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6731 D.setInvalidType(); 6732 6733 // Create a FunctionDecl to satisfy the function definition parsing 6734 // code path. 6735 return FunctionDecl::Create(SemaRef.Context, DC, 6736 D.getLocStart(), 6737 D.getIdentifierLoc(), Name, R, TInfo, 6738 SC, isInline, 6739 /*hasPrototype=*/true, isConstexpr); 6740 } 6741 6742 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6743 if (!DC->isRecord()) { 6744 SemaRef.Diag(D.getIdentifierLoc(), 6745 diag::err_conv_function_not_member); 6746 return nullptr; 6747 } 6748 6749 SemaRef.CheckConversionDeclarator(D, R, SC); 6750 IsVirtualOkay = true; 6751 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6752 D.getLocStart(), NameInfo, 6753 R, TInfo, isInline, isExplicit, 6754 isConstexpr, SourceLocation()); 6755 6756 } else if (DC->isRecord()) { 6757 // If the name of the function is the same as the name of the record, 6758 // then this must be an invalid constructor that has a return type. 6759 // (The parser checks for a return type and makes the declarator a 6760 // constructor if it has no return type). 6761 if (Name.getAsIdentifierInfo() && 6762 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6763 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6764 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6765 << SourceRange(D.getIdentifierLoc()); 6766 return nullptr; 6767 } 6768 6769 // This is a C++ method declaration. 6770 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6771 cast<CXXRecordDecl>(DC), 6772 D.getLocStart(), NameInfo, R, 6773 TInfo, SC, isInline, 6774 isConstexpr, SourceLocation()); 6775 IsVirtualOkay = !Ret->isStatic(); 6776 return Ret; 6777 } else { 6778 bool isFriend = 6779 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 6780 if (!isFriend && SemaRef.CurContext->isRecord()) 6781 return nullptr; 6782 6783 // Determine whether the function was written with a 6784 // prototype. This true when: 6785 // - we're in C++ (where every function has a prototype), 6786 return FunctionDecl::Create(SemaRef.Context, DC, 6787 D.getLocStart(), 6788 NameInfo, R, TInfo, SC, isInline, 6789 true/*HasPrototype*/, isConstexpr); 6790 } 6791 } 6792 6793 enum OpenCLParamType { 6794 ValidKernelParam, 6795 PtrPtrKernelParam, 6796 PtrKernelParam, 6797 PrivatePtrKernelParam, 6798 InvalidKernelParam, 6799 RecordKernelParam 6800 }; 6801 6802 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6803 if (PT->isPointerType()) { 6804 QualType PointeeType = PT->getPointeeType(); 6805 if (PointeeType->isPointerType()) 6806 return PtrPtrKernelParam; 6807 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6808 : PtrKernelParam; 6809 } 6810 6811 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6812 // be used as builtin types. 6813 6814 if (PT->isImageType()) 6815 return PtrKernelParam; 6816 6817 if (PT->isBooleanType()) 6818 return InvalidKernelParam; 6819 6820 if (PT->isEventT()) 6821 return InvalidKernelParam; 6822 6823 if (PT->isHalfType()) 6824 return InvalidKernelParam; 6825 6826 if (PT->isRecordType()) 6827 return RecordKernelParam; 6828 6829 return ValidKernelParam; 6830 } 6831 6832 static void checkIsValidOpenCLKernelParameter( 6833 Sema &S, 6834 Declarator &D, 6835 ParmVarDecl *Param, 6836 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 6837 QualType PT = Param->getType(); 6838 6839 // Cache the valid types we encounter to avoid rechecking structs that are 6840 // used again 6841 if (ValidTypes.count(PT.getTypePtr())) 6842 return; 6843 6844 switch (getOpenCLKernelParameterType(PT)) { 6845 case PtrPtrKernelParam: 6846 // OpenCL v1.2 s6.9.a: 6847 // A kernel function argument cannot be declared as a 6848 // pointer to a pointer type. 6849 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6850 D.setInvalidType(); 6851 return; 6852 6853 case PrivatePtrKernelParam: 6854 // OpenCL v1.2 s6.9.a: 6855 // A kernel function argument cannot be declared as a 6856 // pointer to the private address space. 6857 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6858 D.setInvalidType(); 6859 return; 6860 6861 // OpenCL v1.2 s6.9.k: 6862 // Arguments to kernel functions in a program cannot be declared with the 6863 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6864 // uintptr_t or a struct and/or union that contain fields declared to be 6865 // one of these built-in scalar types. 6866 6867 case InvalidKernelParam: 6868 // OpenCL v1.2 s6.8 n: 6869 // A kernel function argument cannot be declared 6870 // of event_t type. 6871 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6872 D.setInvalidType(); 6873 return; 6874 6875 case PtrKernelParam: 6876 case ValidKernelParam: 6877 ValidTypes.insert(PT.getTypePtr()); 6878 return; 6879 6880 case RecordKernelParam: 6881 break; 6882 } 6883 6884 // Track nested structs we will inspect 6885 SmallVector<const Decl *, 4> VisitStack; 6886 6887 // Track where we are in the nested structs. Items will migrate from 6888 // VisitStack to HistoryStack as we do the DFS for bad field. 6889 SmallVector<const FieldDecl *, 4> HistoryStack; 6890 HistoryStack.push_back(nullptr); 6891 6892 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6893 VisitStack.push_back(PD); 6894 6895 assert(VisitStack.back() && "First decl null?"); 6896 6897 do { 6898 const Decl *Next = VisitStack.pop_back_val(); 6899 if (!Next) { 6900 assert(!HistoryStack.empty()); 6901 // Found a marker, we have gone up a level 6902 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6903 ValidTypes.insert(Hist->getType().getTypePtr()); 6904 6905 continue; 6906 } 6907 6908 // Adds everything except the original parameter declaration (which is not a 6909 // field itself) to the history stack. 6910 const RecordDecl *RD; 6911 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6912 HistoryStack.push_back(Field); 6913 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6914 } else { 6915 RD = cast<RecordDecl>(Next); 6916 } 6917 6918 // Add a null marker so we know when we've gone back up a level 6919 VisitStack.push_back(nullptr); 6920 6921 for (const auto *FD : RD->fields()) { 6922 QualType QT = FD->getType(); 6923 6924 if (ValidTypes.count(QT.getTypePtr())) 6925 continue; 6926 6927 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6928 if (ParamType == ValidKernelParam) 6929 continue; 6930 6931 if (ParamType == RecordKernelParam) { 6932 VisitStack.push_back(FD); 6933 continue; 6934 } 6935 6936 // OpenCL v1.2 s6.9.p: 6937 // Arguments to kernel functions that are declared to be a struct or union 6938 // do not allow OpenCL objects to be passed as elements of the struct or 6939 // union. 6940 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6941 ParamType == PrivatePtrKernelParam) { 6942 S.Diag(Param->getLocation(), 6943 diag::err_record_with_pointers_kernel_param) 6944 << PT->isUnionType() 6945 << PT; 6946 } else { 6947 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6948 } 6949 6950 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6951 << PD->getDeclName(); 6952 6953 // We have an error, now let's go back up through history and show where 6954 // the offending field came from 6955 for (ArrayRef<const FieldDecl *>::const_iterator 6956 I = HistoryStack.begin() + 1, 6957 E = HistoryStack.end(); 6958 I != E; ++I) { 6959 const FieldDecl *OuterField = *I; 6960 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6961 << OuterField->getType(); 6962 } 6963 6964 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6965 << QT->isPointerType() 6966 << QT; 6967 D.setInvalidType(); 6968 return; 6969 } 6970 } while (!VisitStack.empty()); 6971 } 6972 6973 NamedDecl* 6974 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6975 TypeSourceInfo *TInfo, LookupResult &Previous, 6976 MultiTemplateParamsArg TemplateParamLists, 6977 bool &AddToScope) { 6978 QualType R = TInfo->getType(); 6979 6980 assert(R.getTypePtr()->isFunctionType()); 6981 6982 // TODO: consider using NameInfo for diagnostic. 6983 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6984 DeclarationName Name = NameInfo.getName(); 6985 StorageClass SC = getFunctionStorageClass(*this, D); 6986 6987 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6988 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6989 diag::err_invalid_thread) 6990 << DeclSpec::getSpecifierName(TSCS); 6991 6992 if (D.isFirstDeclarationOfMember()) 6993 adjustMemberFunctionCC(R, D.isStaticMember()); 6994 6995 bool isFriend = false; 6996 FunctionTemplateDecl *FunctionTemplate = nullptr; 6997 bool isExplicitSpecialization = false; 6998 bool isFunctionTemplateSpecialization = false; 6999 7000 bool isDependentClassScopeExplicitSpecialization = false; 7001 bool HasExplicitTemplateArgs = false; 7002 TemplateArgumentListInfo TemplateArgs; 7003 7004 bool isVirtualOkay = false; 7005 7006 DeclContext *OriginalDC = DC; 7007 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7008 7009 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7010 isVirtualOkay); 7011 if (!NewFD) return nullptr; 7012 7013 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7014 NewFD->setTopLevelDeclInObjCContainer(); 7015 7016 // Set the lexical context. If this is a function-scope declaration, or has a 7017 // C++ scope specifier, or is the object of a friend declaration, the lexical 7018 // context will be different from the semantic context. 7019 NewFD->setLexicalDeclContext(CurContext); 7020 7021 if (IsLocalExternDecl) 7022 NewFD->setLocalExternDecl(); 7023 7024 if (getLangOpts().CPlusPlus) { 7025 bool isInline = D.getDeclSpec().isInlineSpecified(); 7026 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7027 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7028 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7029 isFriend = D.getDeclSpec().isFriendSpecified(); 7030 if (isFriend && !isInline && D.isFunctionDefinition()) { 7031 // C++ [class.friend]p5 7032 // A function can be defined in a friend declaration of a 7033 // class . . . . Such a function is implicitly inline. 7034 NewFD->setImplicitlyInline(); 7035 } 7036 7037 // If this is a method defined in an __interface, and is not a constructor 7038 // or an overloaded operator, then set the pure flag (isVirtual will already 7039 // return true). 7040 if (const CXXRecordDecl *Parent = 7041 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7042 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7043 NewFD->setPure(true); 7044 } 7045 7046 SetNestedNameSpecifier(NewFD, D); 7047 isExplicitSpecialization = false; 7048 isFunctionTemplateSpecialization = false; 7049 if (D.isInvalidType()) 7050 NewFD->setInvalidDecl(); 7051 7052 // Match up the template parameter lists with the scope specifier, then 7053 // determine whether we have a template or a template specialization. 7054 bool Invalid = false; 7055 if (TemplateParameterList *TemplateParams = 7056 MatchTemplateParametersToScopeSpecifier( 7057 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7058 D.getCXXScopeSpec(), 7059 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7060 ? D.getName().TemplateId 7061 : nullptr, 7062 TemplateParamLists, isFriend, isExplicitSpecialization, 7063 Invalid)) { 7064 if (TemplateParams->size() > 0) { 7065 // This is a function template 7066 7067 // Check that we can declare a template here. 7068 if (CheckTemplateDeclScope(S, TemplateParams)) 7069 NewFD->setInvalidDecl(); 7070 7071 // A destructor cannot be a template. 7072 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7073 Diag(NewFD->getLocation(), diag::err_destructor_template); 7074 NewFD->setInvalidDecl(); 7075 } 7076 7077 // If we're adding a template to a dependent context, we may need to 7078 // rebuilding some of the types used within the template parameter list, 7079 // now that we know what the current instantiation is. 7080 if (DC->isDependentContext()) { 7081 ContextRAII SavedContext(*this, DC); 7082 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7083 Invalid = true; 7084 } 7085 7086 7087 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7088 NewFD->getLocation(), 7089 Name, TemplateParams, 7090 NewFD); 7091 FunctionTemplate->setLexicalDeclContext(CurContext); 7092 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7093 7094 // For source fidelity, store the other template param lists. 7095 if (TemplateParamLists.size() > 1) { 7096 NewFD->setTemplateParameterListsInfo(Context, 7097 TemplateParamLists.size() - 1, 7098 TemplateParamLists.data()); 7099 } 7100 } else { 7101 // This is a function template specialization. 7102 isFunctionTemplateSpecialization = true; 7103 // For source fidelity, store all the template param lists. 7104 if (TemplateParamLists.size() > 0) 7105 NewFD->setTemplateParameterListsInfo(Context, 7106 TemplateParamLists.size(), 7107 TemplateParamLists.data()); 7108 7109 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7110 if (isFriend) { 7111 // We want to remove the "template<>", found here. 7112 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7113 7114 // If we remove the template<> and the name is not a 7115 // template-id, we're actually silently creating a problem: 7116 // the friend declaration will refer to an untemplated decl, 7117 // and clearly the user wants a template specialization. So 7118 // we need to insert '<>' after the name. 7119 SourceLocation InsertLoc; 7120 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7121 InsertLoc = D.getName().getSourceRange().getEnd(); 7122 InsertLoc = getLocForEndOfToken(InsertLoc); 7123 } 7124 7125 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7126 << Name << RemoveRange 7127 << FixItHint::CreateRemoval(RemoveRange) 7128 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7129 } 7130 } 7131 } 7132 else { 7133 // All template param lists were matched against the scope specifier: 7134 // this is NOT (an explicit specialization of) a template. 7135 if (TemplateParamLists.size() > 0) 7136 // For source fidelity, store all the template param lists. 7137 NewFD->setTemplateParameterListsInfo(Context, 7138 TemplateParamLists.size(), 7139 TemplateParamLists.data()); 7140 } 7141 7142 if (Invalid) { 7143 NewFD->setInvalidDecl(); 7144 if (FunctionTemplate) 7145 FunctionTemplate->setInvalidDecl(); 7146 } 7147 7148 // C++ [dcl.fct.spec]p5: 7149 // The virtual specifier shall only be used in declarations of 7150 // nonstatic class member functions that appear within a 7151 // member-specification of a class declaration; see 10.3. 7152 // 7153 if (isVirtual && !NewFD->isInvalidDecl()) { 7154 if (!isVirtualOkay) { 7155 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7156 diag::err_virtual_non_function); 7157 } else if (!CurContext->isRecord()) { 7158 // 'virtual' was specified outside of the class. 7159 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7160 diag::err_virtual_out_of_class) 7161 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7162 } else if (NewFD->getDescribedFunctionTemplate()) { 7163 // C++ [temp.mem]p3: 7164 // A member function template shall not be virtual. 7165 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7166 diag::err_virtual_member_function_template) 7167 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7168 } else { 7169 // Okay: Add virtual to the method. 7170 NewFD->setVirtualAsWritten(true); 7171 } 7172 7173 if (getLangOpts().CPlusPlus14 && 7174 NewFD->getReturnType()->isUndeducedType()) 7175 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7176 } 7177 7178 if (getLangOpts().CPlusPlus14 && 7179 (NewFD->isDependentContext() || 7180 (isFriend && CurContext->isDependentContext())) && 7181 NewFD->getReturnType()->isUndeducedType()) { 7182 // If the function template is referenced directly (for instance, as a 7183 // member of the current instantiation), pretend it has a dependent type. 7184 // This is not really justified by the standard, but is the only sane 7185 // thing to do. 7186 // FIXME: For a friend function, we have not marked the function as being 7187 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7188 const FunctionProtoType *FPT = 7189 NewFD->getType()->castAs<FunctionProtoType>(); 7190 QualType Result = 7191 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7192 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7193 FPT->getExtProtoInfo())); 7194 } 7195 7196 // C++ [dcl.fct.spec]p3: 7197 // The inline specifier shall not appear on a block scope function 7198 // declaration. 7199 if (isInline && !NewFD->isInvalidDecl()) { 7200 if (CurContext->isFunctionOrMethod()) { 7201 // 'inline' is not allowed on block scope function declaration. 7202 Diag(D.getDeclSpec().getInlineSpecLoc(), 7203 diag::err_inline_declaration_block_scope) << Name 7204 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7205 } 7206 } 7207 7208 // C++ [dcl.fct.spec]p6: 7209 // The explicit specifier shall be used only in the declaration of a 7210 // constructor or conversion function within its class definition; 7211 // see 12.3.1 and 12.3.2. 7212 if (isExplicit && !NewFD->isInvalidDecl()) { 7213 if (!CurContext->isRecord()) { 7214 // 'explicit' was specified outside of the class. 7215 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7216 diag::err_explicit_out_of_class) 7217 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7218 } else if (!isa<CXXConstructorDecl>(NewFD) && 7219 !isa<CXXConversionDecl>(NewFD)) { 7220 // 'explicit' was specified on a function that wasn't a constructor 7221 // or conversion function. 7222 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7223 diag::err_explicit_non_ctor_or_conv_function) 7224 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7225 } 7226 } 7227 7228 if (isConstexpr) { 7229 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7230 // are implicitly inline. 7231 NewFD->setImplicitlyInline(); 7232 7233 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7234 // be either constructors or to return a literal type. Therefore, 7235 // destructors cannot be declared constexpr. 7236 if (isa<CXXDestructorDecl>(NewFD)) 7237 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7238 } 7239 7240 // If __module_private__ was specified, mark the function accordingly. 7241 if (D.getDeclSpec().isModulePrivateSpecified()) { 7242 if (isFunctionTemplateSpecialization) { 7243 SourceLocation ModulePrivateLoc 7244 = D.getDeclSpec().getModulePrivateSpecLoc(); 7245 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7246 << 0 7247 << FixItHint::CreateRemoval(ModulePrivateLoc); 7248 } else { 7249 NewFD->setModulePrivate(); 7250 if (FunctionTemplate) 7251 FunctionTemplate->setModulePrivate(); 7252 } 7253 } 7254 7255 if (isFriend) { 7256 if (FunctionTemplate) { 7257 FunctionTemplate->setObjectOfFriendDecl(); 7258 FunctionTemplate->setAccess(AS_public); 7259 } 7260 NewFD->setObjectOfFriendDecl(); 7261 NewFD->setAccess(AS_public); 7262 } 7263 7264 // If a function is defined as defaulted or deleted, mark it as such now. 7265 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7266 // definition kind to FDK_Definition. 7267 switch (D.getFunctionDefinitionKind()) { 7268 case FDK_Declaration: 7269 case FDK_Definition: 7270 break; 7271 7272 case FDK_Defaulted: 7273 NewFD->setDefaulted(); 7274 break; 7275 7276 case FDK_Deleted: 7277 NewFD->setDeletedAsWritten(); 7278 break; 7279 } 7280 7281 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7282 D.isFunctionDefinition()) { 7283 // C++ [class.mfct]p2: 7284 // A member function may be defined (8.4) in its class definition, in 7285 // which case it is an inline member function (7.1.2) 7286 NewFD->setImplicitlyInline(); 7287 } 7288 7289 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7290 !CurContext->isRecord()) { 7291 // C++ [class.static]p1: 7292 // A data or function member of a class may be declared static 7293 // in a class definition, in which case it is a static member of 7294 // the class. 7295 7296 // Complain about the 'static' specifier if it's on an out-of-line 7297 // member function definition. 7298 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7299 diag::err_static_out_of_line) 7300 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7301 } 7302 7303 // C++11 [except.spec]p15: 7304 // A deallocation function with no exception-specification is treated 7305 // as if it were specified with noexcept(true). 7306 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7307 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7308 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7309 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7310 NewFD->setType(Context.getFunctionType( 7311 FPT->getReturnType(), FPT->getParamTypes(), 7312 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7313 } 7314 7315 // Filter out previous declarations that don't match the scope. 7316 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7317 D.getCXXScopeSpec().isNotEmpty() || 7318 isExplicitSpecialization || 7319 isFunctionTemplateSpecialization); 7320 7321 // Handle GNU asm-label extension (encoded as an attribute). 7322 if (Expr *E = (Expr*) D.getAsmLabel()) { 7323 // The parser guarantees this is a string. 7324 StringLiteral *SE = cast<StringLiteral>(E); 7325 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7326 SE->getString(), 0)); 7327 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7328 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7329 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7330 if (I != ExtnameUndeclaredIdentifiers.end()) { 7331 NewFD->addAttr(I->second); 7332 ExtnameUndeclaredIdentifiers.erase(I); 7333 } 7334 } 7335 7336 // Copy the parameter declarations from the declarator D to the function 7337 // declaration NewFD, if they are available. First scavenge them into Params. 7338 SmallVector<ParmVarDecl*, 16> Params; 7339 if (D.isFunctionDeclarator()) { 7340 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7341 7342 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7343 // function that takes no arguments, not a function that takes a 7344 // single void argument. 7345 // We let through "const void" here because Sema::GetTypeForDeclarator 7346 // already checks for that case. 7347 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7348 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7349 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7350 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7351 Param->setDeclContext(NewFD); 7352 Params.push_back(Param); 7353 7354 if (Param->isInvalidDecl()) 7355 NewFD->setInvalidDecl(); 7356 } 7357 } 7358 7359 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7360 // When we're declaring a function with a typedef, typeof, etc as in the 7361 // following example, we'll need to synthesize (unnamed) 7362 // parameters for use in the declaration. 7363 // 7364 // @code 7365 // typedef void fn(int); 7366 // fn f; 7367 // @endcode 7368 7369 // Synthesize a parameter for each argument type. 7370 for (const auto &AI : FT->param_types()) { 7371 ParmVarDecl *Param = 7372 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7373 Param->setScopeInfo(0, Params.size()); 7374 Params.push_back(Param); 7375 } 7376 } else { 7377 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7378 "Should not need args for typedef of non-prototype fn"); 7379 } 7380 7381 // Finally, we know we have the right number of parameters, install them. 7382 NewFD->setParams(Params); 7383 7384 // Find all anonymous symbols defined during the declaration of this function 7385 // and add to NewFD. This lets us track decls such 'enum Y' in: 7386 // 7387 // void f(enum Y {AA} x) {} 7388 // 7389 // which would otherwise incorrectly end up in the translation unit scope. 7390 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7391 DeclsInPrototypeScope.clear(); 7392 7393 if (D.getDeclSpec().isNoreturnSpecified()) 7394 NewFD->addAttr( 7395 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7396 Context, 0)); 7397 7398 // Functions returning a variably modified type violate C99 6.7.5.2p2 7399 // because all functions have linkage. 7400 if (!NewFD->isInvalidDecl() && 7401 NewFD->getReturnType()->isVariablyModifiedType()) { 7402 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7403 NewFD->setInvalidDecl(); 7404 } 7405 7406 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue && 7407 !NewFD->hasAttr<SectionAttr>()) { 7408 NewFD->addAttr( 7409 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7410 CodeSegStack.CurrentValue->getString(), 7411 CodeSegStack.CurrentPragmaLocation)); 7412 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7413 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 7414 ASTContext::PSF_Read, 7415 NewFD)) 7416 NewFD->dropAttr<SectionAttr>(); 7417 } 7418 7419 // Handle attributes. 7420 ProcessDeclAttributes(S, NewFD, D); 7421 7422 QualType RetType = NewFD->getReturnType(); 7423 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7424 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7425 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7426 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7427 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7428 // Attach WarnUnusedResult to functions returning types with that attribute. 7429 // Don't apply the attribute to that type's own non-static member functions 7430 // (to avoid warning on things like assignment operators) 7431 if (!MD || MD->getParent() != Ret) 7432 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7433 } 7434 7435 if (getLangOpts().OpenCL) { 7436 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7437 // type declaration will generate a compilation error. 7438 unsigned AddressSpace = RetType.getAddressSpace(); 7439 if (AddressSpace == LangAS::opencl_local || 7440 AddressSpace == LangAS::opencl_global || 7441 AddressSpace == LangAS::opencl_constant) { 7442 Diag(NewFD->getLocation(), 7443 diag::err_opencl_return_value_with_address_space); 7444 NewFD->setInvalidDecl(); 7445 } 7446 } 7447 7448 if (!getLangOpts().CPlusPlus) { 7449 // Perform semantic checking on the function declaration. 7450 bool isExplicitSpecialization=false; 7451 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7452 CheckMain(NewFD, D.getDeclSpec()); 7453 7454 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7455 CheckMSVCRTEntryPoint(NewFD); 7456 7457 if (!NewFD->isInvalidDecl()) 7458 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7459 isExplicitSpecialization)); 7460 else if (!Previous.empty()) 7461 // Recover gracefully from an invalid redeclaration. 7462 D.setRedeclaration(true); 7463 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7464 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7465 "previous declaration set still overloaded"); 7466 7467 // Diagnose no-prototype function declarations with calling conventions that 7468 // don't support variadic calls. Only do this in C and do it after merging 7469 // possibly prototyped redeclarations. 7470 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 7471 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 7472 CallingConv CC = FT->getExtInfo().getCC(); 7473 if (!supportsVariadicCall(CC)) { 7474 // Windows system headers sometimes accidentally use stdcall without 7475 // (void) parameters, so we relax this to a warning. 7476 int DiagID = 7477 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 7478 Diag(NewFD->getLocation(), DiagID) 7479 << FunctionType::getNameForCallConv(CC); 7480 } 7481 } 7482 } else { 7483 // C++11 [replacement.functions]p3: 7484 // The program's definitions shall not be specified as inline. 7485 // 7486 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7487 // 7488 // Suppress the diagnostic if the function is __attribute__((used)), since 7489 // that forces an external definition to be emitted. 7490 if (D.getDeclSpec().isInlineSpecified() && 7491 NewFD->isReplaceableGlobalAllocationFunction() && 7492 !NewFD->hasAttr<UsedAttr>()) 7493 Diag(D.getDeclSpec().getInlineSpecLoc(), 7494 diag::ext_operator_new_delete_declared_inline) 7495 << NewFD->getDeclName(); 7496 7497 // If the declarator is a template-id, translate the parser's template 7498 // argument list into our AST format. 7499 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7500 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7501 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7502 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7503 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7504 TemplateId->NumArgs); 7505 translateTemplateArguments(TemplateArgsPtr, 7506 TemplateArgs); 7507 7508 HasExplicitTemplateArgs = true; 7509 7510 if (NewFD->isInvalidDecl()) { 7511 HasExplicitTemplateArgs = false; 7512 } else if (FunctionTemplate) { 7513 // Function template with explicit template arguments. 7514 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7515 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7516 7517 HasExplicitTemplateArgs = false; 7518 } else { 7519 assert((isFunctionTemplateSpecialization || 7520 D.getDeclSpec().isFriendSpecified()) && 7521 "should have a 'template<>' for this decl"); 7522 // "friend void foo<>(int);" is an implicit specialization decl. 7523 isFunctionTemplateSpecialization = true; 7524 } 7525 } else if (isFriend && isFunctionTemplateSpecialization) { 7526 // This combination is only possible in a recovery case; the user 7527 // wrote something like: 7528 // template <> friend void foo(int); 7529 // which we're recovering from as if the user had written: 7530 // friend void foo<>(int); 7531 // Go ahead and fake up a template id. 7532 HasExplicitTemplateArgs = true; 7533 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7534 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7535 } 7536 7537 // If it's a friend (and only if it's a friend), it's possible 7538 // that either the specialized function type or the specialized 7539 // template is dependent, and therefore matching will fail. In 7540 // this case, don't check the specialization yet. 7541 bool InstantiationDependent = false; 7542 if (isFunctionTemplateSpecialization && isFriend && 7543 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7544 TemplateSpecializationType::anyDependentTemplateArguments( 7545 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7546 InstantiationDependent))) { 7547 assert(HasExplicitTemplateArgs && 7548 "friend function specialization without template args"); 7549 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7550 Previous)) 7551 NewFD->setInvalidDecl(); 7552 } else if (isFunctionTemplateSpecialization) { 7553 if (CurContext->isDependentContext() && CurContext->isRecord() 7554 && !isFriend) { 7555 isDependentClassScopeExplicitSpecialization = true; 7556 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7557 diag::ext_function_specialization_in_class : 7558 diag::err_function_specialization_in_class) 7559 << NewFD->getDeclName(); 7560 } else if (CheckFunctionTemplateSpecialization(NewFD, 7561 (HasExplicitTemplateArgs ? &TemplateArgs 7562 : nullptr), 7563 Previous)) 7564 NewFD->setInvalidDecl(); 7565 7566 // C++ [dcl.stc]p1: 7567 // A storage-class-specifier shall not be specified in an explicit 7568 // specialization (14.7.3) 7569 FunctionTemplateSpecializationInfo *Info = 7570 NewFD->getTemplateSpecializationInfo(); 7571 if (Info && SC != SC_None) { 7572 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7573 Diag(NewFD->getLocation(), 7574 diag::err_explicit_specialization_inconsistent_storage_class) 7575 << SC 7576 << FixItHint::CreateRemoval( 7577 D.getDeclSpec().getStorageClassSpecLoc()); 7578 7579 else 7580 Diag(NewFD->getLocation(), 7581 diag::ext_explicit_specialization_storage_class) 7582 << FixItHint::CreateRemoval( 7583 D.getDeclSpec().getStorageClassSpecLoc()); 7584 } 7585 7586 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7587 if (CheckMemberSpecialization(NewFD, Previous)) 7588 NewFD->setInvalidDecl(); 7589 } 7590 7591 // Perform semantic checking on the function declaration. 7592 if (!isDependentClassScopeExplicitSpecialization) { 7593 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7594 CheckMain(NewFD, D.getDeclSpec()); 7595 7596 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7597 CheckMSVCRTEntryPoint(NewFD); 7598 7599 if (!NewFD->isInvalidDecl()) 7600 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7601 isExplicitSpecialization)); 7602 else if (!Previous.empty()) 7603 // Recover gracefully from an invalid redeclaration. 7604 D.setRedeclaration(true); 7605 } 7606 7607 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7608 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7609 "previous declaration set still overloaded"); 7610 7611 NamedDecl *PrincipalDecl = (FunctionTemplate 7612 ? cast<NamedDecl>(FunctionTemplate) 7613 : NewFD); 7614 7615 if (isFriend && D.isRedeclaration()) { 7616 AccessSpecifier Access = AS_public; 7617 if (!NewFD->isInvalidDecl()) 7618 Access = NewFD->getPreviousDecl()->getAccess(); 7619 7620 NewFD->setAccess(Access); 7621 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7622 } 7623 7624 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7625 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7626 PrincipalDecl->setNonMemberOperator(); 7627 7628 // If we have a function template, check the template parameter 7629 // list. This will check and merge default template arguments. 7630 if (FunctionTemplate) { 7631 FunctionTemplateDecl *PrevTemplate = 7632 FunctionTemplate->getPreviousDecl(); 7633 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7634 PrevTemplate ? PrevTemplate->getTemplateParameters() 7635 : nullptr, 7636 D.getDeclSpec().isFriendSpecified() 7637 ? (D.isFunctionDefinition() 7638 ? TPC_FriendFunctionTemplateDefinition 7639 : TPC_FriendFunctionTemplate) 7640 : (D.getCXXScopeSpec().isSet() && 7641 DC && DC->isRecord() && 7642 DC->isDependentContext()) 7643 ? TPC_ClassTemplateMember 7644 : TPC_FunctionTemplate); 7645 } 7646 7647 if (NewFD->isInvalidDecl()) { 7648 // Ignore all the rest of this. 7649 } else if (!D.isRedeclaration()) { 7650 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7651 AddToScope }; 7652 // Fake up an access specifier if it's supposed to be a class member. 7653 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7654 NewFD->setAccess(AS_public); 7655 7656 // Qualified decls generally require a previous declaration. 7657 if (D.getCXXScopeSpec().isSet()) { 7658 // ...with the major exception of templated-scope or 7659 // dependent-scope friend declarations. 7660 7661 // TODO: we currently also suppress this check in dependent 7662 // contexts because (1) the parameter depth will be off when 7663 // matching friend templates and (2) we might actually be 7664 // selecting a friend based on a dependent factor. But there 7665 // are situations where these conditions don't apply and we 7666 // can actually do this check immediately. 7667 if (isFriend && 7668 (TemplateParamLists.size() || 7669 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7670 CurContext->isDependentContext())) { 7671 // ignore these 7672 } else { 7673 // The user tried to provide an out-of-line definition for a 7674 // function that is a member of a class or namespace, but there 7675 // was no such member function declared (C++ [class.mfct]p2, 7676 // C++ [namespace.memdef]p2). For example: 7677 // 7678 // class X { 7679 // void f() const; 7680 // }; 7681 // 7682 // void X::f() { } // ill-formed 7683 // 7684 // Complain about this problem, and attempt to suggest close 7685 // matches (e.g., those that differ only in cv-qualifiers and 7686 // whether the parameter types are references). 7687 7688 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7689 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7690 AddToScope = ExtraArgs.AddToScope; 7691 return Result; 7692 } 7693 } 7694 7695 // Unqualified local friend declarations are required to resolve 7696 // to something. 7697 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7698 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7699 *this, Previous, NewFD, ExtraArgs, true, S)) { 7700 AddToScope = ExtraArgs.AddToScope; 7701 return Result; 7702 } 7703 } 7704 7705 } else if (!D.isFunctionDefinition() && 7706 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7707 !isFriend && !isFunctionTemplateSpecialization && 7708 !isExplicitSpecialization) { 7709 // An out-of-line member function declaration must also be a 7710 // definition (C++ [class.mfct]p2). 7711 // Note that this is not the case for explicit specializations of 7712 // function templates or member functions of class templates, per 7713 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7714 // extension for compatibility with old SWIG code which likes to 7715 // generate them. 7716 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7717 << D.getCXXScopeSpec().getRange(); 7718 } 7719 } 7720 7721 ProcessPragmaWeak(S, NewFD); 7722 checkAttributesAfterMerging(*this, *NewFD); 7723 7724 AddKnownFunctionAttributes(NewFD); 7725 7726 if (NewFD->hasAttr<OverloadableAttr>() && 7727 !NewFD->getType()->getAs<FunctionProtoType>()) { 7728 Diag(NewFD->getLocation(), 7729 diag::err_attribute_overloadable_no_prototype) 7730 << NewFD; 7731 7732 // Turn this into a variadic function with no parameters. 7733 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7734 FunctionProtoType::ExtProtoInfo EPI( 7735 Context.getDefaultCallingConvention(true, false)); 7736 EPI.Variadic = true; 7737 EPI.ExtInfo = FT->getExtInfo(); 7738 7739 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7740 NewFD->setType(R); 7741 } 7742 7743 // If there's a #pragma GCC visibility in scope, and this isn't a class 7744 // member, set the visibility of this function. 7745 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7746 AddPushedVisibilityAttribute(NewFD); 7747 7748 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7749 // marking the function. 7750 AddCFAuditedAttribute(NewFD); 7751 7752 // If this is a function definition, check if we have to apply optnone due to 7753 // a pragma. 7754 if(D.isFunctionDefinition()) 7755 AddRangeBasedOptnone(NewFD); 7756 7757 // If this is the first declaration of an extern C variable, update 7758 // the map of such variables. 7759 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7760 isIncompleteDeclExternC(*this, NewFD)) 7761 RegisterLocallyScopedExternCDecl(NewFD, S); 7762 7763 // Set this FunctionDecl's range up to the right paren. 7764 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7765 7766 if (D.isRedeclaration() && !Previous.empty()) { 7767 checkDLLAttributeRedeclaration( 7768 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7769 isExplicitSpecialization || isFunctionTemplateSpecialization); 7770 } 7771 7772 if (getLangOpts().CPlusPlus) { 7773 if (FunctionTemplate) { 7774 if (NewFD->isInvalidDecl()) 7775 FunctionTemplate->setInvalidDecl(); 7776 return FunctionTemplate; 7777 } 7778 } 7779 7780 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7781 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7782 if ((getLangOpts().OpenCLVersion >= 120) 7783 && (SC == SC_Static)) { 7784 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7785 D.setInvalidType(); 7786 } 7787 7788 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7789 if (!NewFD->getReturnType()->isVoidType()) { 7790 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 7791 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 7792 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 7793 : FixItHint()); 7794 D.setInvalidType(); 7795 } 7796 7797 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7798 for (auto Param : NewFD->params()) 7799 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7800 } 7801 7802 MarkUnusedFileScopedDecl(NewFD); 7803 7804 if (getLangOpts().CUDA) 7805 if (IdentifierInfo *II = NewFD->getIdentifier()) 7806 if (!NewFD->isInvalidDecl() && 7807 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7808 if (II->isStr("cudaConfigureCall")) { 7809 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7810 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7811 7812 Context.setcudaConfigureCallDecl(NewFD); 7813 } 7814 } 7815 7816 // Here we have an function template explicit specialization at class scope. 7817 // The actually specialization will be postponed to template instatiation 7818 // time via the ClassScopeFunctionSpecializationDecl node. 7819 if (isDependentClassScopeExplicitSpecialization) { 7820 ClassScopeFunctionSpecializationDecl *NewSpec = 7821 ClassScopeFunctionSpecializationDecl::Create( 7822 Context, CurContext, SourceLocation(), 7823 cast<CXXMethodDecl>(NewFD), 7824 HasExplicitTemplateArgs, TemplateArgs); 7825 CurContext->addDecl(NewSpec); 7826 AddToScope = false; 7827 } 7828 7829 return NewFD; 7830 } 7831 7832 /// \brief Perform semantic checking of a new function declaration. 7833 /// 7834 /// Performs semantic analysis of the new function declaration 7835 /// NewFD. This routine performs all semantic checking that does not 7836 /// require the actual declarator involved in the declaration, and is 7837 /// used both for the declaration of functions as they are parsed 7838 /// (called via ActOnDeclarator) and for the declaration of functions 7839 /// that have been instantiated via C++ template instantiation (called 7840 /// via InstantiateDecl). 7841 /// 7842 /// \param IsExplicitSpecialization whether this new function declaration is 7843 /// an explicit specialization of the previous declaration. 7844 /// 7845 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7846 /// 7847 /// \returns true if the function declaration is a redeclaration. 7848 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7849 LookupResult &Previous, 7850 bool IsExplicitSpecialization) { 7851 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7852 "Variably modified return types are not handled here"); 7853 7854 // Determine whether the type of this function should be merged with 7855 // a previous visible declaration. This never happens for functions in C++, 7856 // and always happens in C if the previous declaration was visible. 7857 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7858 !Previous.isShadowed(); 7859 7860 // Filter out any non-conflicting previous declarations. 7861 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7862 7863 bool Redeclaration = false; 7864 NamedDecl *OldDecl = nullptr; 7865 7866 // Merge or overload the declaration with an existing declaration of 7867 // the same name, if appropriate. 7868 if (!Previous.empty()) { 7869 // Determine whether NewFD is an overload of PrevDecl or 7870 // a declaration that requires merging. If it's an overload, 7871 // there's no more work to do here; we'll just add the new 7872 // function to the scope. 7873 if (!AllowOverloadingOfFunction(Previous, Context)) { 7874 NamedDecl *Candidate = Previous.getFoundDecl(); 7875 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7876 Redeclaration = true; 7877 OldDecl = Candidate; 7878 } 7879 } else { 7880 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7881 /*NewIsUsingDecl*/ false)) { 7882 case Ovl_Match: 7883 Redeclaration = true; 7884 break; 7885 7886 case Ovl_NonFunction: 7887 Redeclaration = true; 7888 break; 7889 7890 case Ovl_Overload: 7891 Redeclaration = false; 7892 break; 7893 } 7894 7895 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7896 // If a function name is overloadable in C, then every function 7897 // with that name must be marked "overloadable". 7898 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7899 << Redeclaration << NewFD; 7900 NamedDecl *OverloadedDecl = nullptr; 7901 if (Redeclaration) 7902 OverloadedDecl = OldDecl; 7903 else if (!Previous.empty()) 7904 OverloadedDecl = Previous.getRepresentativeDecl(); 7905 if (OverloadedDecl) 7906 Diag(OverloadedDecl->getLocation(), 7907 diag::note_attribute_overloadable_prev_overload); 7908 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7909 } 7910 } 7911 } 7912 7913 // Check for a previous extern "C" declaration with this name. 7914 if (!Redeclaration && 7915 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7916 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7917 if (!Previous.empty()) { 7918 // This is an extern "C" declaration with the same name as a previous 7919 // declaration, and thus redeclares that entity... 7920 Redeclaration = true; 7921 OldDecl = Previous.getFoundDecl(); 7922 MergeTypeWithPrevious = false; 7923 7924 // ... except in the presence of __attribute__((overloadable)). 7925 if (OldDecl->hasAttr<OverloadableAttr>()) { 7926 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7927 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7928 << Redeclaration << NewFD; 7929 Diag(Previous.getFoundDecl()->getLocation(), 7930 diag::note_attribute_overloadable_prev_overload); 7931 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7932 } 7933 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7934 Redeclaration = false; 7935 OldDecl = nullptr; 7936 } 7937 } 7938 } 7939 } 7940 7941 // C++11 [dcl.constexpr]p8: 7942 // A constexpr specifier for a non-static member function that is not 7943 // a constructor declares that member function to be const. 7944 // 7945 // This needs to be delayed until we know whether this is an out-of-line 7946 // definition of a static member function. 7947 // 7948 // This rule is not present in C++1y, so we produce a backwards 7949 // compatibility warning whenever it happens in C++11. 7950 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7951 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 7952 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7953 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7954 CXXMethodDecl *OldMD = nullptr; 7955 if (OldDecl) 7956 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 7957 if (!OldMD || !OldMD->isStatic()) { 7958 const FunctionProtoType *FPT = 7959 MD->getType()->castAs<FunctionProtoType>(); 7960 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7961 EPI.TypeQuals |= Qualifiers::Const; 7962 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7963 FPT->getParamTypes(), EPI)); 7964 7965 // Warn that we did this, if we're not performing template instantiation. 7966 // In that case, we'll have warned already when the template was defined. 7967 if (ActiveTemplateInstantiations.empty()) { 7968 SourceLocation AddConstLoc; 7969 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7970 .IgnoreParens().getAs<FunctionTypeLoc>()) 7971 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 7972 7973 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 7974 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7975 } 7976 } 7977 } 7978 7979 if (Redeclaration) { 7980 // NewFD and OldDecl represent declarations that need to be 7981 // merged. 7982 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7983 NewFD->setInvalidDecl(); 7984 return Redeclaration; 7985 } 7986 7987 Previous.clear(); 7988 Previous.addDecl(OldDecl); 7989 7990 if (FunctionTemplateDecl *OldTemplateDecl 7991 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7992 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7993 FunctionTemplateDecl *NewTemplateDecl 7994 = NewFD->getDescribedFunctionTemplate(); 7995 assert(NewTemplateDecl && "Template/non-template mismatch"); 7996 if (CXXMethodDecl *Method 7997 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7998 Method->setAccess(OldTemplateDecl->getAccess()); 7999 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8000 } 8001 8002 // If this is an explicit specialization of a member that is a function 8003 // template, mark it as a member specialization. 8004 if (IsExplicitSpecialization && 8005 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8006 NewTemplateDecl->setMemberSpecialization(); 8007 assert(OldTemplateDecl->isMemberSpecialization()); 8008 } 8009 8010 } else { 8011 // This needs to happen first so that 'inline' propagates. 8012 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8013 8014 if (isa<CXXMethodDecl>(NewFD)) { 8015 // A valid redeclaration of a C++ method must be out-of-line, 8016 // but (unfortunately) it's not necessarily a definition 8017 // because of templates, which means that the previous 8018 // declaration is not necessarily from the class definition. 8019 8020 // For just setting the access, that doesn't matter. 8021 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 8022 NewFD->setAccess(oldMethod->getAccess()); 8023 8024 // Update the key-function state if necessary for this ABI. 8025 if (NewFD->isInlined() && 8026 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 8027 // setNonKeyFunction needs to work with the original 8028 // declaration from the class definition, and isVirtual() is 8029 // just faster in that case, so map back to that now. 8030 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 8031 if (oldMethod->isVirtual()) { 8032 Context.setNonKeyFunction(oldMethod); 8033 } 8034 } 8035 } 8036 } 8037 } 8038 8039 // Semantic checking for this function declaration (in isolation). 8040 8041 if (getLangOpts().CPlusPlus) { 8042 // C++-specific checks. 8043 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8044 CheckConstructor(Constructor); 8045 } else if (CXXDestructorDecl *Destructor = 8046 dyn_cast<CXXDestructorDecl>(NewFD)) { 8047 CXXRecordDecl *Record = Destructor->getParent(); 8048 QualType ClassType = Context.getTypeDeclType(Record); 8049 8050 // FIXME: Shouldn't we be able to perform this check even when the class 8051 // type is dependent? Both gcc and edg can handle that. 8052 if (!ClassType->isDependentType()) { 8053 DeclarationName Name 8054 = Context.DeclarationNames.getCXXDestructorName( 8055 Context.getCanonicalType(ClassType)); 8056 if (NewFD->getDeclName() != Name) { 8057 Diag(NewFD->getLocation(), diag::err_destructor_name); 8058 NewFD->setInvalidDecl(); 8059 return Redeclaration; 8060 } 8061 } 8062 } else if (CXXConversionDecl *Conversion 8063 = dyn_cast<CXXConversionDecl>(NewFD)) { 8064 ActOnConversionDeclarator(Conversion); 8065 } 8066 8067 // Find any virtual functions that this function overrides. 8068 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8069 if (!Method->isFunctionTemplateSpecialization() && 8070 !Method->getDescribedFunctionTemplate() && 8071 Method->isCanonicalDecl()) { 8072 if (AddOverriddenMethods(Method->getParent(), Method)) { 8073 // If the function was marked as "static", we have a problem. 8074 if (NewFD->getStorageClass() == SC_Static) { 8075 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8076 } 8077 } 8078 } 8079 8080 if (Method->isStatic()) 8081 checkThisInStaticMemberFunctionType(Method); 8082 } 8083 8084 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8085 if (NewFD->isOverloadedOperator() && 8086 CheckOverloadedOperatorDeclaration(NewFD)) { 8087 NewFD->setInvalidDecl(); 8088 return Redeclaration; 8089 } 8090 8091 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8092 if (NewFD->getLiteralIdentifier() && 8093 CheckLiteralOperatorDeclaration(NewFD)) { 8094 NewFD->setInvalidDecl(); 8095 return Redeclaration; 8096 } 8097 8098 // In C++, check default arguments now that we have merged decls. Unless 8099 // the lexical context is the class, because in this case this is done 8100 // during delayed parsing anyway. 8101 if (!CurContext->isRecord()) 8102 CheckCXXDefaultArguments(NewFD); 8103 8104 // If this function declares a builtin function, check the type of this 8105 // declaration against the expected type for the builtin. 8106 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8107 ASTContext::GetBuiltinTypeError Error; 8108 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8109 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8110 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8111 // The type of this function differs from the type of the builtin, 8112 // so forget about the builtin entirely. 8113 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 8114 } 8115 } 8116 8117 // If this function is declared as being extern "C", then check to see if 8118 // the function returns a UDT (class, struct, or union type) that is not C 8119 // compatible, and if it does, warn the user. 8120 // But, issue any diagnostic on the first declaration only. 8121 if (Previous.empty() && NewFD->isExternC()) { 8122 QualType R = NewFD->getReturnType(); 8123 if (R->isIncompleteType() && !R->isVoidType()) 8124 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8125 << NewFD << R; 8126 else if (!R.isPODType(Context) && !R->isVoidType() && 8127 !R->isObjCObjectPointerType()) 8128 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8129 } 8130 } 8131 return Redeclaration; 8132 } 8133 8134 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8135 // C++11 [basic.start.main]p3: 8136 // A program that [...] declares main to be inline, static or 8137 // constexpr is ill-formed. 8138 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8139 // appear in a declaration of main. 8140 // static main is not an error under C99, but we should warn about it. 8141 // We accept _Noreturn main as an extension. 8142 if (FD->getStorageClass() == SC_Static) 8143 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8144 ? diag::err_static_main : diag::warn_static_main) 8145 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8146 if (FD->isInlineSpecified()) 8147 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8148 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8149 if (DS.isNoreturnSpecified()) { 8150 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8151 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8152 Diag(NoreturnLoc, diag::ext_noreturn_main); 8153 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8154 << FixItHint::CreateRemoval(NoreturnRange); 8155 } 8156 if (FD->isConstexpr()) { 8157 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8158 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8159 FD->setConstexpr(false); 8160 } 8161 8162 if (getLangOpts().OpenCL) { 8163 Diag(FD->getLocation(), diag::err_opencl_no_main) 8164 << FD->hasAttr<OpenCLKernelAttr>(); 8165 FD->setInvalidDecl(); 8166 return; 8167 } 8168 8169 QualType T = FD->getType(); 8170 assert(T->isFunctionType() && "function decl is not of function type"); 8171 const FunctionType* FT = T->castAs<FunctionType>(); 8172 8173 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8174 // In C with GNU extensions we allow main() to have non-integer return 8175 // type, but we should warn about the extension, and we disable the 8176 // implicit-return-zero rule. 8177 8178 // GCC in C mode accepts qualified 'int'. 8179 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8180 FD->setHasImplicitReturnZero(true); 8181 else { 8182 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8183 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8184 if (RTRange.isValid()) 8185 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8186 << FixItHint::CreateReplacement(RTRange, "int"); 8187 } 8188 } else { 8189 // In C and C++, main magically returns 0 if you fall off the end; 8190 // set the flag which tells us that. 8191 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8192 8193 // All the standards say that main() should return 'int'. 8194 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8195 FD->setHasImplicitReturnZero(true); 8196 else { 8197 // Otherwise, this is just a flat-out error. 8198 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8199 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8200 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8201 : FixItHint()); 8202 FD->setInvalidDecl(true); 8203 } 8204 } 8205 8206 // Treat protoless main() as nullary. 8207 if (isa<FunctionNoProtoType>(FT)) return; 8208 8209 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8210 unsigned nparams = FTP->getNumParams(); 8211 assert(FD->getNumParams() == nparams); 8212 8213 bool HasExtraParameters = (nparams > 3); 8214 8215 // Darwin passes an undocumented fourth argument of type char**. If 8216 // other platforms start sprouting these, the logic below will start 8217 // getting shifty. 8218 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8219 HasExtraParameters = false; 8220 8221 if (HasExtraParameters) { 8222 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8223 FD->setInvalidDecl(true); 8224 nparams = 3; 8225 } 8226 8227 // FIXME: a lot of the following diagnostics would be improved 8228 // if we had some location information about types. 8229 8230 QualType CharPP = 8231 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8232 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8233 8234 for (unsigned i = 0; i < nparams; ++i) { 8235 QualType AT = FTP->getParamType(i); 8236 8237 bool mismatch = true; 8238 8239 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8240 mismatch = false; 8241 else if (Expected[i] == CharPP) { 8242 // As an extension, the following forms are okay: 8243 // char const ** 8244 // char const * const * 8245 // char * const * 8246 8247 QualifierCollector qs; 8248 const PointerType* PT; 8249 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8250 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8251 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8252 Context.CharTy)) { 8253 qs.removeConst(); 8254 mismatch = !qs.empty(); 8255 } 8256 } 8257 8258 if (mismatch) { 8259 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8260 // TODO: suggest replacing given type with expected type 8261 FD->setInvalidDecl(true); 8262 } 8263 } 8264 8265 if (nparams == 1 && !FD->isInvalidDecl()) { 8266 Diag(FD->getLocation(), diag::warn_main_one_arg); 8267 } 8268 8269 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8270 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8271 FD->setInvalidDecl(); 8272 } 8273 } 8274 8275 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8276 QualType T = FD->getType(); 8277 assert(T->isFunctionType() && "function decl is not of function type"); 8278 const FunctionType *FT = T->castAs<FunctionType>(); 8279 8280 // Set an implicit return of 'zero' if the function can return some integral, 8281 // enumeration, pointer or nullptr type. 8282 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8283 FT->getReturnType()->isAnyPointerType() || 8284 FT->getReturnType()->isNullPtrType()) 8285 // DllMain is exempt because a return value of zero means it failed. 8286 if (FD->getName() != "DllMain") 8287 FD->setHasImplicitReturnZero(true); 8288 8289 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8290 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8291 FD->setInvalidDecl(); 8292 } 8293 } 8294 8295 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8296 // FIXME: Need strict checking. In C89, we need to check for 8297 // any assignment, increment, decrement, function-calls, or 8298 // commas outside of a sizeof. In C99, it's the same list, 8299 // except that the aforementioned are allowed in unevaluated 8300 // expressions. Everything else falls under the 8301 // "may accept other forms of constant expressions" exception. 8302 // (We never end up here for C++, so the constant expression 8303 // rules there don't matter.) 8304 const Expr *Culprit; 8305 if (Init->isConstantInitializer(Context, false, &Culprit)) 8306 return false; 8307 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8308 << Culprit->getSourceRange(); 8309 return true; 8310 } 8311 8312 namespace { 8313 // Visits an initialization expression to see if OrigDecl is evaluated in 8314 // its own initialization and throws a warning if it does. 8315 class SelfReferenceChecker 8316 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8317 Sema &S; 8318 Decl *OrigDecl; 8319 bool isRecordType; 8320 bool isPODType; 8321 bool isReferenceType; 8322 8323 bool isInitList; 8324 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8325 public: 8326 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8327 8328 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8329 S(S), OrigDecl(OrigDecl) { 8330 isPODType = false; 8331 isRecordType = false; 8332 isReferenceType = false; 8333 isInitList = false; 8334 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8335 isPODType = VD->getType().isPODType(S.Context); 8336 isRecordType = VD->getType()->isRecordType(); 8337 isReferenceType = VD->getType()->isReferenceType(); 8338 } 8339 } 8340 8341 // For most expressions, just call the visitor. For initializer lists, 8342 // track the index of the field being initialized since fields are 8343 // initialized in order allowing use of previously initialized fields. 8344 void CheckExpr(Expr *E) { 8345 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8346 if (!InitList) { 8347 Visit(E); 8348 return; 8349 } 8350 8351 // Track and increment the index here. 8352 isInitList = true; 8353 InitFieldIndex.push_back(0); 8354 for (auto Child : InitList->children()) { 8355 CheckExpr(cast<Expr>(Child)); 8356 ++InitFieldIndex.back(); 8357 } 8358 InitFieldIndex.pop_back(); 8359 } 8360 8361 // Returns true if MemberExpr is checked and no futher checking is needed. 8362 // Returns false if additional checking is required. 8363 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8364 llvm::SmallVector<FieldDecl*, 4> Fields; 8365 Expr *Base = E; 8366 bool ReferenceField = false; 8367 8368 // Get the field memebers used. 8369 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8370 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8371 if (!FD) 8372 return false; 8373 Fields.push_back(FD); 8374 if (FD->getType()->isReferenceType()) 8375 ReferenceField = true; 8376 Base = ME->getBase()->IgnoreParenImpCasts(); 8377 } 8378 8379 // Keep checking only if the base Decl is the same. 8380 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8381 if (!DRE || DRE->getDecl() != OrigDecl) 8382 return false; 8383 8384 // A reference field can be bound to an unininitialized field. 8385 if (CheckReference && !ReferenceField) 8386 return true; 8387 8388 // Convert FieldDecls to their index number. 8389 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8390 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) { 8391 UsedFieldIndex.push_back((*I)->getFieldIndex()); 8392 } 8393 8394 // See if a warning is needed by checking the first difference in index 8395 // numbers. If field being used has index less than the field being 8396 // initialized, then the use is safe. 8397 for (auto UsedIter = UsedFieldIndex.begin(), 8398 UsedEnd = UsedFieldIndex.end(), 8399 OrigIter = InitFieldIndex.begin(), 8400 OrigEnd = InitFieldIndex.end(); 8401 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8402 if (*UsedIter < *OrigIter) 8403 return true; 8404 if (*UsedIter > *OrigIter) 8405 break; 8406 } 8407 8408 // TODO: Add a different warning which will print the field names. 8409 HandleDeclRefExpr(DRE); 8410 return true; 8411 } 8412 8413 // For most expressions, the cast is directly above the DeclRefExpr. 8414 // For conditional operators, the cast can be outside the conditional 8415 // operator if both expressions are DeclRefExpr's. 8416 void HandleValue(Expr *E) { 8417 E = E->IgnoreParens(); 8418 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8419 HandleDeclRefExpr(DRE); 8420 return; 8421 } 8422 8423 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8424 Visit(CO->getCond()); 8425 HandleValue(CO->getTrueExpr()); 8426 HandleValue(CO->getFalseExpr()); 8427 return; 8428 } 8429 8430 if (BinaryConditionalOperator *BCO = 8431 dyn_cast<BinaryConditionalOperator>(E)) { 8432 Visit(BCO->getCond()); 8433 HandleValue(BCO->getFalseExpr()); 8434 return; 8435 } 8436 8437 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8438 HandleValue(OVE->getSourceExpr()); 8439 return; 8440 } 8441 8442 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8443 if (BO->getOpcode() == BO_Comma) { 8444 Visit(BO->getLHS()); 8445 HandleValue(BO->getRHS()); 8446 return; 8447 } 8448 } 8449 8450 if (isa<MemberExpr>(E)) { 8451 if (isInitList) { 8452 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8453 false /*CheckReference*/)) 8454 return; 8455 } 8456 8457 Expr *Base = E->IgnoreParenImpCasts(); 8458 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8459 // Check for static member variables and don't warn on them. 8460 if (!isa<FieldDecl>(ME->getMemberDecl())) 8461 return; 8462 Base = ME->getBase()->IgnoreParenImpCasts(); 8463 } 8464 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8465 HandleDeclRefExpr(DRE); 8466 return; 8467 } 8468 8469 Visit(E); 8470 } 8471 8472 // Reference types not handled in HandleValue are handled here since all 8473 // uses of references are bad, not just r-value uses. 8474 void VisitDeclRefExpr(DeclRefExpr *E) { 8475 if (isReferenceType) 8476 HandleDeclRefExpr(E); 8477 } 8478 8479 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8480 if (E->getCastKind() == CK_LValueToRValue) { 8481 HandleValue(E->getSubExpr()); 8482 return; 8483 } 8484 8485 Inherited::VisitImplicitCastExpr(E); 8486 } 8487 8488 void VisitMemberExpr(MemberExpr *E) { 8489 if (isInitList) { 8490 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 8491 return; 8492 } 8493 8494 // Don't warn on arrays since they can be treated as pointers. 8495 if (E->getType()->canDecayToPointerType()) return; 8496 8497 // Warn when a non-static method call is followed by non-static member 8498 // field accesses, which is followed by a DeclRefExpr. 8499 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8500 bool Warn = (MD && !MD->isStatic()); 8501 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8502 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8503 if (!isa<FieldDecl>(ME->getMemberDecl())) 8504 Warn = false; 8505 Base = ME->getBase()->IgnoreParenImpCasts(); 8506 } 8507 8508 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8509 if (Warn) 8510 HandleDeclRefExpr(DRE); 8511 return; 8512 } 8513 8514 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8515 // Visit that expression. 8516 Visit(Base); 8517 } 8518 8519 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8520 Expr *Callee = E->getCallee(); 8521 8522 if (isa<UnresolvedLookupExpr>(Callee)) 8523 return Inherited::VisitCXXOperatorCallExpr(E); 8524 8525 Visit(Callee); 8526 for (auto Arg: E->arguments()) 8527 HandleValue(Arg->IgnoreParenImpCasts()); 8528 } 8529 8530 void VisitUnaryOperator(UnaryOperator *E) { 8531 // For POD record types, addresses of its own members are well-defined. 8532 if (E->getOpcode() == UO_AddrOf && isRecordType && 8533 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8534 if (!isPODType) 8535 HandleValue(E->getSubExpr()); 8536 return; 8537 } 8538 8539 if (E->isIncrementDecrementOp()) { 8540 HandleValue(E->getSubExpr()); 8541 return; 8542 } 8543 8544 Inherited::VisitUnaryOperator(E); 8545 } 8546 8547 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8548 8549 void VisitCXXConstructExpr(CXXConstructExpr *E) { 8550 if (E->getConstructor()->isCopyConstructor()) { 8551 Expr *ArgExpr = E->getArg(0); 8552 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 8553 if (ILE->getNumInits() == 1) 8554 ArgExpr = ILE->getInit(0); 8555 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8556 if (ICE->getCastKind() == CK_NoOp) 8557 ArgExpr = ICE->getSubExpr(); 8558 HandleValue(ArgExpr); 8559 return; 8560 } 8561 Inherited::VisitCXXConstructExpr(E); 8562 } 8563 8564 void VisitCallExpr(CallExpr *E) { 8565 // Treat std::move as a use. 8566 if (E->getNumArgs() == 1) { 8567 if (FunctionDecl *FD = E->getDirectCallee()) { 8568 if (FD->isInStdNamespace() && FD->getIdentifier() && 8569 FD->getIdentifier()->isStr("move")) { 8570 HandleValue(E->getArg(0)); 8571 return; 8572 } 8573 } 8574 } 8575 8576 Inherited::VisitCallExpr(E); 8577 } 8578 8579 void VisitBinaryOperator(BinaryOperator *E) { 8580 if (E->isCompoundAssignmentOp()) { 8581 HandleValue(E->getLHS()); 8582 Visit(E->getRHS()); 8583 return; 8584 } 8585 8586 Inherited::VisitBinaryOperator(E); 8587 } 8588 8589 // A custom visitor for BinaryConditionalOperator is needed because the 8590 // regular visitor would check the condition and true expression separately 8591 // but both point to the same place giving duplicate diagnostics. 8592 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 8593 Visit(E->getCond()); 8594 Visit(E->getFalseExpr()); 8595 } 8596 8597 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8598 Decl* ReferenceDecl = DRE->getDecl(); 8599 if (OrigDecl != ReferenceDecl) return; 8600 unsigned diag; 8601 if (isReferenceType) { 8602 diag = diag::warn_uninit_self_reference_in_reference_init; 8603 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8604 diag = diag::warn_static_self_reference_in_init; 8605 } else { 8606 diag = diag::warn_uninit_self_reference_in_init; 8607 } 8608 8609 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8610 S.PDiag(diag) 8611 << DRE->getNameInfo().getName() 8612 << OrigDecl->getLocation() 8613 << DRE->getSourceRange()); 8614 } 8615 }; 8616 8617 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8618 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8619 bool DirectInit) { 8620 // Parameters arguments are occassionially constructed with itself, 8621 // for instance, in recursive functions. Skip them. 8622 if (isa<ParmVarDecl>(OrigDecl)) 8623 return; 8624 8625 E = E->IgnoreParens(); 8626 8627 // Skip checking T a = a where T is not a record or reference type. 8628 // Doing so is a way to silence uninitialized warnings. 8629 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8630 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8631 if (ICE->getCastKind() == CK_LValueToRValue) 8632 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8633 if (DRE->getDecl() == OrigDecl) 8634 return; 8635 8636 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 8637 } 8638 } 8639 8640 /// AddInitializerToDecl - Adds the initializer Init to the 8641 /// declaration dcl. If DirectInit is true, this is C++ direct 8642 /// initialization rather than copy initialization. 8643 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8644 bool DirectInit, bool TypeMayContainAuto) { 8645 // If there is no declaration, there was an error parsing it. Just ignore 8646 // the initializer. 8647 if (!RealDecl || RealDecl->isInvalidDecl()) { 8648 CorrectDelayedTyposInExpr(Init); 8649 return; 8650 } 8651 8652 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8653 // With declarators parsed the way they are, the parser cannot 8654 // distinguish between a normal initializer and a pure-specifier. 8655 // Thus this grotesque test. 8656 IntegerLiteral *IL; 8657 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8658 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8659 CheckPureMethod(Method, Init->getSourceRange()); 8660 else { 8661 Diag(Method->getLocation(), diag::err_member_function_initialization) 8662 << Method->getDeclName() << Init->getSourceRange(); 8663 Method->setInvalidDecl(); 8664 } 8665 return; 8666 } 8667 8668 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8669 if (!VDecl) { 8670 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8671 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8672 RealDecl->setInvalidDecl(); 8673 return; 8674 } 8675 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8676 8677 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8678 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8679 Expr *DeduceInit = Init; 8680 // Initializer could be a C++ direct-initializer. Deduction only works if it 8681 // contains exactly one expression. 8682 if (CXXDirectInit) { 8683 if (CXXDirectInit->getNumExprs() == 0) { 8684 // It isn't possible to write this directly, but it is possible to 8685 // end up in this situation with "auto x(some_pack...);" 8686 Diag(CXXDirectInit->getLocStart(), 8687 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8688 : diag::err_auto_var_init_no_expression) 8689 << VDecl->getDeclName() << VDecl->getType() 8690 << VDecl->getSourceRange(); 8691 RealDecl->setInvalidDecl(); 8692 return; 8693 } else if (CXXDirectInit->getNumExprs() > 1) { 8694 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8695 VDecl->isInitCapture() 8696 ? diag::err_init_capture_multiple_expressions 8697 : diag::err_auto_var_init_multiple_expressions) 8698 << VDecl->getDeclName() << VDecl->getType() 8699 << VDecl->getSourceRange(); 8700 RealDecl->setInvalidDecl(); 8701 return; 8702 } else { 8703 DeduceInit = CXXDirectInit->getExpr(0); 8704 if (isa<InitListExpr>(DeduceInit)) 8705 Diag(CXXDirectInit->getLocStart(), 8706 diag::err_auto_var_init_paren_braces) 8707 << VDecl->getDeclName() << VDecl->getType() 8708 << VDecl->getSourceRange(); 8709 } 8710 } 8711 8712 // Expressions default to 'id' when we're in a debugger. 8713 bool DefaultedToAuto = false; 8714 if (getLangOpts().DebuggerCastResultToId && 8715 Init->getType() == Context.UnknownAnyTy) { 8716 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8717 if (Result.isInvalid()) { 8718 VDecl->setInvalidDecl(); 8719 return; 8720 } 8721 Init = Result.get(); 8722 DefaultedToAuto = true; 8723 } 8724 8725 QualType DeducedType; 8726 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8727 DAR_Failed) 8728 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8729 if (DeducedType.isNull()) { 8730 RealDecl->setInvalidDecl(); 8731 return; 8732 } 8733 VDecl->setType(DeducedType); 8734 assert(VDecl->isLinkageValid()); 8735 8736 // In ARC, infer lifetime. 8737 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8738 VDecl->setInvalidDecl(); 8739 8740 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8741 // 'id' instead of a specific object type prevents most of our usual checks. 8742 // We only want to warn outside of template instantiations, though: 8743 // inside a template, the 'id' could have come from a parameter. 8744 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8745 DeducedType->isObjCIdType()) { 8746 SourceLocation Loc = 8747 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8748 Diag(Loc, diag::warn_auto_var_is_id) 8749 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8750 } 8751 8752 // If this is a redeclaration, check that the type we just deduced matches 8753 // the previously declared type. 8754 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8755 // We never need to merge the type, because we cannot form an incomplete 8756 // array of auto, nor deduce such a type. 8757 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8758 } 8759 8760 // Check the deduced type is valid for a variable declaration. 8761 CheckVariableDeclarationType(VDecl); 8762 if (VDecl->isInvalidDecl()) 8763 return; 8764 8765 // If all looks well, warn if this is a case that will change meaning when 8766 // we implement N3922. 8767 if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) { 8768 Diag(Init->getLocStart(), 8769 diag::warn_auto_var_direct_list_init) 8770 << FixItHint::CreateInsertion(Init->getLocStart(), "="); 8771 } 8772 } 8773 8774 // dllimport cannot be used on variable definitions. 8775 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8776 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8777 VDecl->setInvalidDecl(); 8778 return; 8779 } 8780 8781 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8782 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8783 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8784 VDecl->setInvalidDecl(); 8785 return; 8786 } 8787 8788 if (!VDecl->getType()->isDependentType()) { 8789 // A definition must end up with a complete type, which means it must be 8790 // complete with the restriction that an array type might be completed by 8791 // the initializer; note that later code assumes this restriction. 8792 QualType BaseDeclType = VDecl->getType(); 8793 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8794 BaseDeclType = Array->getElementType(); 8795 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8796 diag::err_typecheck_decl_incomplete_type)) { 8797 RealDecl->setInvalidDecl(); 8798 return; 8799 } 8800 8801 // The variable can not have an abstract class type. 8802 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8803 diag::err_abstract_type_in_decl, 8804 AbstractVariableType)) 8805 VDecl->setInvalidDecl(); 8806 } 8807 8808 const VarDecl *Def; 8809 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8810 Diag(VDecl->getLocation(), diag::err_redefinition) 8811 << VDecl->getDeclName(); 8812 Diag(Def->getLocation(), diag::note_previous_definition); 8813 VDecl->setInvalidDecl(); 8814 return; 8815 } 8816 8817 const VarDecl *PrevInit = nullptr; 8818 if (getLangOpts().CPlusPlus) { 8819 // C++ [class.static.data]p4 8820 // If a static data member is of const integral or const 8821 // enumeration type, its declaration in the class definition can 8822 // specify a constant-initializer which shall be an integral 8823 // constant expression (5.19). In that case, the member can appear 8824 // in integral constant expressions. The member shall still be 8825 // defined in a namespace scope if it is used in the program and the 8826 // namespace scope definition shall not contain an initializer. 8827 // 8828 // We already performed a redefinition check above, but for static 8829 // data members we also need to check whether there was an in-class 8830 // declaration with an initializer. 8831 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8832 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8833 << VDecl->getDeclName(); 8834 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8835 return; 8836 } 8837 8838 if (VDecl->hasLocalStorage()) 8839 getCurFunction()->setHasBranchProtectedScope(); 8840 8841 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8842 VDecl->setInvalidDecl(); 8843 return; 8844 } 8845 } 8846 8847 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8848 // a kernel function cannot be initialized." 8849 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8850 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8851 VDecl->setInvalidDecl(); 8852 return; 8853 } 8854 8855 // Get the decls type and save a reference for later, since 8856 // CheckInitializerTypes may change it. 8857 QualType DclT = VDecl->getType(), SavT = DclT; 8858 8859 // Expressions default to 'id' when we're in a debugger 8860 // and we are assigning it to a variable of Objective-C pointer type. 8861 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8862 Init->getType() == Context.UnknownAnyTy) { 8863 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8864 if (Result.isInvalid()) { 8865 VDecl->setInvalidDecl(); 8866 return; 8867 } 8868 Init = Result.get(); 8869 } 8870 8871 // Perform the initialization. 8872 if (!VDecl->isInvalidDecl()) { 8873 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8874 InitializationKind Kind 8875 = DirectInit ? 8876 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8877 Init->getLocStart(), 8878 Init->getLocEnd()) 8879 : InitializationKind::CreateDirectList( 8880 VDecl->getLocation()) 8881 : InitializationKind::CreateCopy(VDecl->getLocation(), 8882 Init->getLocStart()); 8883 8884 MultiExprArg Args = Init; 8885 if (CXXDirectInit) 8886 Args = MultiExprArg(CXXDirectInit->getExprs(), 8887 CXXDirectInit->getNumExprs()); 8888 8889 // Try to correct any TypoExprs in the initialization arguments. 8890 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 8891 ExprResult Res = 8892 CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) { 8893 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 8894 return Init.Failed() ? ExprError() : E; 8895 }); 8896 if (Res.isInvalid()) { 8897 VDecl->setInvalidDecl(); 8898 } else if (Res.get() != Args[Idx]) { 8899 Args[Idx] = Res.get(); 8900 } 8901 } 8902 if (VDecl->isInvalidDecl()) 8903 return; 8904 8905 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8906 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8907 if (Result.isInvalid()) { 8908 VDecl->setInvalidDecl(); 8909 return; 8910 } 8911 8912 Init = Result.getAs<Expr>(); 8913 } 8914 8915 // Check for self-references within variable initializers. 8916 // Variables declared within a function/method body (except for references) 8917 // are handled by a dataflow analysis. 8918 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8919 VDecl->getType()->isReferenceType()) { 8920 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8921 } 8922 8923 // If the type changed, it means we had an incomplete type that was 8924 // completed by the initializer. For example: 8925 // int ary[] = { 1, 3, 5 }; 8926 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8927 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8928 VDecl->setType(DclT); 8929 8930 if (!VDecl->isInvalidDecl()) { 8931 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8932 8933 if (VDecl->hasAttr<BlocksAttr>()) 8934 checkRetainCycles(VDecl, Init); 8935 8936 // It is safe to assign a weak reference into a strong variable. 8937 // Although this code can still have problems: 8938 // id x = self.weakProp; 8939 // id y = self.weakProp; 8940 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8941 // paths through the function. This should be revisited if 8942 // -Wrepeated-use-of-weak is made flow-sensitive. 8943 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 8944 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 8945 Init->getLocStart())) 8946 getCurFunction()->markSafeWeakUse(Init); 8947 } 8948 8949 // The initialization is usually a full-expression. 8950 // 8951 // FIXME: If this is a braced initialization of an aggregate, it is not 8952 // an expression, and each individual field initializer is a separate 8953 // full-expression. For instance, in: 8954 // 8955 // struct Temp { ~Temp(); }; 8956 // struct S { S(Temp); }; 8957 // struct T { S a, b; } t = { Temp(), Temp() } 8958 // 8959 // we should destroy the first Temp before constructing the second. 8960 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8961 false, 8962 VDecl->isConstexpr()); 8963 if (Result.isInvalid()) { 8964 VDecl->setInvalidDecl(); 8965 return; 8966 } 8967 Init = Result.get(); 8968 8969 // Attach the initializer to the decl. 8970 VDecl->setInit(Init); 8971 8972 if (VDecl->isLocalVarDecl()) { 8973 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8974 // static storage duration shall be constant expressions or string literals. 8975 // C++ does not have this restriction. 8976 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8977 const Expr *Culprit; 8978 if (VDecl->getStorageClass() == SC_Static) 8979 CheckForConstantInitializer(Init, DclT); 8980 // C89 is stricter than C99 for non-static aggregate types. 8981 // C89 6.5.7p3: All the expressions [...] in an initializer list 8982 // for an object that has aggregate or union type shall be 8983 // constant expressions. 8984 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8985 isa<InitListExpr>(Init) && 8986 !Init->isConstantInitializer(Context, false, &Culprit)) 8987 Diag(Culprit->getExprLoc(), 8988 diag::ext_aggregate_init_not_constant) 8989 << Culprit->getSourceRange(); 8990 } 8991 } else if (VDecl->isStaticDataMember() && 8992 VDecl->getLexicalDeclContext()->isRecord()) { 8993 // This is an in-class initialization for a static data member, e.g., 8994 // 8995 // struct S { 8996 // static const int value = 17; 8997 // }; 8998 8999 // C++ [class.mem]p4: 9000 // A member-declarator can contain a constant-initializer only 9001 // if it declares a static member (9.4) of const integral or 9002 // const enumeration type, see 9.4.2. 9003 // 9004 // C++11 [class.static.data]p3: 9005 // If a non-volatile const static data member is of integral or 9006 // enumeration type, its declaration in the class definition can 9007 // specify a brace-or-equal-initializer in which every initalizer-clause 9008 // that is an assignment-expression is a constant expression. A static 9009 // data member of literal type can be declared in the class definition 9010 // with the constexpr specifier; if so, its declaration shall specify a 9011 // brace-or-equal-initializer in which every initializer-clause that is 9012 // an assignment-expression is a constant expression. 9013 9014 // Do nothing on dependent types. 9015 if (DclT->isDependentType()) { 9016 9017 // Allow any 'static constexpr' members, whether or not they are of literal 9018 // type. We separately check that every constexpr variable is of literal 9019 // type. 9020 } else if (VDecl->isConstexpr()) { 9021 9022 // Require constness. 9023 } else if (!DclT.isConstQualified()) { 9024 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9025 << Init->getSourceRange(); 9026 VDecl->setInvalidDecl(); 9027 9028 // We allow integer constant expressions in all cases. 9029 } else if (DclT->isIntegralOrEnumerationType()) { 9030 // Check whether the expression is a constant expression. 9031 SourceLocation Loc; 9032 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9033 // In C++11, a non-constexpr const static data member with an 9034 // in-class initializer cannot be volatile. 9035 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9036 else if (Init->isValueDependent()) 9037 ; // Nothing to check. 9038 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9039 ; // Ok, it's an ICE! 9040 else if (Init->isEvaluatable(Context)) { 9041 // If we can constant fold the initializer through heroics, accept it, 9042 // but report this as a use of an extension for -pedantic. 9043 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9044 << Init->getSourceRange(); 9045 } else { 9046 // Otherwise, this is some crazy unknown case. Report the issue at the 9047 // location provided by the isIntegerConstantExpr failed check. 9048 Diag(Loc, diag::err_in_class_initializer_non_constant) 9049 << Init->getSourceRange(); 9050 VDecl->setInvalidDecl(); 9051 } 9052 9053 // We allow foldable floating-point constants as an extension. 9054 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9055 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9056 // it anyway and provide a fixit to add the 'constexpr'. 9057 if (getLangOpts().CPlusPlus11) { 9058 Diag(VDecl->getLocation(), 9059 diag::ext_in_class_initializer_float_type_cxx11) 9060 << DclT << Init->getSourceRange(); 9061 Diag(VDecl->getLocStart(), 9062 diag::note_in_class_initializer_float_type_cxx11) 9063 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9064 } else { 9065 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9066 << DclT << Init->getSourceRange(); 9067 9068 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9069 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9070 << Init->getSourceRange(); 9071 VDecl->setInvalidDecl(); 9072 } 9073 } 9074 9075 // Suggest adding 'constexpr' in C++11 for literal types. 9076 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9077 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9078 << DclT << Init->getSourceRange() 9079 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9080 VDecl->setConstexpr(true); 9081 9082 } else { 9083 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9084 << DclT << Init->getSourceRange(); 9085 VDecl->setInvalidDecl(); 9086 } 9087 } else if (VDecl->isFileVarDecl()) { 9088 if (VDecl->getStorageClass() == SC_Extern && 9089 (!getLangOpts().CPlusPlus || 9090 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 9091 VDecl->isExternC())) && 9092 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9093 Diag(VDecl->getLocation(), diag::warn_extern_init); 9094 9095 // C99 6.7.8p4. All file scoped initializers need to be constant. 9096 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9097 CheckForConstantInitializer(Init, DclT); 9098 } 9099 9100 // We will represent direct-initialization similarly to copy-initialization: 9101 // int x(1); -as-> int x = 1; 9102 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9103 // 9104 // Clients that want to distinguish between the two forms, can check for 9105 // direct initializer using VarDecl::getInitStyle(). 9106 // A major benefit is that clients that don't particularly care about which 9107 // exactly form was it (like the CodeGen) can handle both cases without 9108 // special case code. 9109 9110 // C++ 8.5p11: 9111 // The form of initialization (using parentheses or '=') is generally 9112 // insignificant, but does matter when the entity being initialized has a 9113 // class type. 9114 if (CXXDirectInit) { 9115 assert(DirectInit && "Call-style initializer must be direct init."); 9116 VDecl->setInitStyle(VarDecl::CallInit); 9117 } else if (DirectInit) { 9118 // This must be list-initialization. No other way is direct-initialization. 9119 VDecl->setInitStyle(VarDecl::ListInit); 9120 } 9121 9122 CheckCompleteVariableDeclaration(VDecl); 9123 } 9124 9125 /// ActOnInitializerError - Given that there was an error parsing an 9126 /// initializer for the given declaration, try to return to some form 9127 /// of sanity. 9128 void Sema::ActOnInitializerError(Decl *D) { 9129 // Our main concern here is re-establishing invariants like "a 9130 // variable's type is either dependent or complete". 9131 if (!D || D->isInvalidDecl()) return; 9132 9133 VarDecl *VD = dyn_cast<VarDecl>(D); 9134 if (!VD) return; 9135 9136 // Auto types are meaningless if we can't make sense of the initializer. 9137 if (ParsingInitForAutoVars.count(D)) { 9138 D->setInvalidDecl(); 9139 return; 9140 } 9141 9142 QualType Ty = VD->getType(); 9143 if (Ty->isDependentType()) return; 9144 9145 // Require a complete type. 9146 if (RequireCompleteType(VD->getLocation(), 9147 Context.getBaseElementType(Ty), 9148 diag::err_typecheck_decl_incomplete_type)) { 9149 VD->setInvalidDecl(); 9150 return; 9151 } 9152 9153 // Require a non-abstract type. 9154 if (RequireNonAbstractType(VD->getLocation(), Ty, 9155 diag::err_abstract_type_in_decl, 9156 AbstractVariableType)) { 9157 VD->setInvalidDecl(); 9158 return; 9159 } 9160 9161 // Don't bother complaining about constructors or destructors, 9162 // though. 9163 } 9164 9165 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9166 bool TypeMayContainAuto) { 9167 // If there is no declaration, there was an error parsing it. Just ignore it. 9168 if (!RealDecl) 9169 return; 9170 9171 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9172 QualType Type = Var->getType(); 9173 9174 // C++11 [dcl.spec.auto]p3 9175 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9176 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9177 << Var->getDeclName() << Type; 9178 Var->setInvalidDecl(); 9179 return; 9180 } 9181 9182 // C++11 [class.static.data]p3: A static data member can be declared with 9183 // the constexpr specifier; if so, its declaration shall specify 9184 // a brace-or-equal-initializer. 9185 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9186 // the definition of a variable [...] or the declaration of a static data 9187 // member. 9188 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9189 if (Var->isStaticDataMember()) 9190 Diag(Var->getLocation(), 9191 diag::err_constexpr_static_mem_var_requires_init) 9192 << Var->getDeclName(); 9193 else 9194 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9195 Var->setInvalidDecl(); 9196 return; 9197 } 9198 9199 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9200 // be initialized. 9201 if (!Var->isInvalidDecl() && 9202 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9203 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9204 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9205 Var->setInvalidDecl(); 9206 return; 9207 } 9208 9209 switch (Var->isThisDeclarationADefinition()) { 9210 case VarDecl::Definition: 9211 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9212 break; 9213 9214 // We have an out-of-line definition of a static data member 9215 // that has an in-class initializer, so we type-check this like 9216 // a declaration. 9217 // 9218 // Fall through 9219 9220 case VarDecl::DeclarationOnly: 9221 // It's only a declaration. 9222 9223 // Block scope. C99 6.7p7: If an identifier for an object is 9224 // declared with no linkage (C99 6.2.2p6), the type for the 9225 // object shall be complete. 9226 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9227 !Var->hasLinkage() && !Var->isInvalidDecl() && 9228 RequireCompleteType(Var->getLocation(), Type, 9229 diag::err_typecheck_decl_incomplete_type)) 9230 Var->setInvalidDecl(); 9231 9232 // Make sure that the type is not abstract. 9233 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9234 RequireNonAbstractType(Var->getLocation(), Type, 9235 diag::err_abstract_type_in_decl, 9236 AbstractVariableType)) 9237 Var->setInvalidDecl(); 9238 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9239 Var->getStorageClass() == SC_PrivateExtern) { 9240 Diag(Var->getLocation(), diag::warn_private_extern); 9241 Diag(Var->getLocation(), diag::note_private_extern); 9242 } 9243 9244 return; 9245 9246 case VarDecl::TentativeDefinition: 9247 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9248 // object that has file scope without an initializer, and without a 9249 // storage-class specifier or with the storage-class specifier "static", 9250 // constitutes a tentative definition. Note: A tentative definition with 9251 // external linkage is valid (C99 6.2.2p5). 9252 if (!Var->isInvalidDecl()) { 9253 if (const IncompleteArrayType *ArrayT 9254 = Context.getAsIncompleteArrayType(Type)) { 9255 if (RequireCompleteType(Var->getLocation(), 9256 ArrayT->getElementType(), 9257 diag::err_illegal_decl_array_incomplete_type)) 9258 Var->setInvalidDecl(); 9259 } else if (Var->getStorageClass() == SC_Static) { 9260 // C99 6.9.2p3: If the declaration of an identifier for an object is 9261 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9262 // declared type shall not be an incomplete type. 9263 // NOTE: code such as the following 9264 // static struct s; 9265 // struct s { int a; }; 9266 // is accepted by gcc. Hence here we issue a warning instead of 9267 // an error and we do not invalidate the static declaration. 9268 // NOTE: to avoid multiple warnings, only check the first declaration. 9269 if (Var->isFirstDecl()) 9270 RequireCompleteType(Var->getLocation(), Type, 9271 diag::ext_typecheck_decl_incomplete_type); 9272 } 9273 } 9274 9275 // Record the tentative definition; we're done. 9276 if (!Var->isInvalidDecl()) 9277 TentativeDefinitions.push_back(Var); 9278 return; 9279 } 9280 9281 // Provide a specific diagnostic for uninitialized variable 9282 // definitions with incomplete array type. 9283 if (Type->isIncompleteArrayType()) { 9284 Diag(Var->getLocation(), 9285 diag::err_typecheck_incomplete_array_needs_initializer); 9286 Var->setInvalidDecl(); 9287 return; 9288 } 9289 9290 // Provide a specific diagnostic for uninitialized variable 9291 // definitions with reference type. 9292 if (Type->isReferenceType()) { 9293 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9294 << Var->getDeclName() 9295 << SourceRange(Var->getLocation(), Var->getLocation()); 9296 Var->setInvalidDecl(); 9297 return; 9298 } 9299 9300 // Do not attempt to type-check the default initializer for a 9301 // variable with dependent type. 9302 if (Type->isDependentType()) 9303 return; 9304 9305 if (Var->isInvalidDecl()) 9306 return; 9307 9308 if (!Var->hasAttr<AliasAttr>()) { 9309 if (RequireCompleteType(Var->getLocation(), 9310 Context.getBaseElementType(Type), 9311 diag::err_typecheck_decl_incomplete_type)) { 9312 Var->setInvalidDecl(); 9313 return; 9314 } 9315 } else { 9316 return; 9317 } 9318 9319 // The variable can not have an abstract class type. 9320 if (RequireNonAbstractType(Var->getLocation(), Type, 9321 diag::err_abstract_type_in_decl, 9322 AbstractVariableType)) { 9323 Var->setInvalidDecl(); 9324 return; 9325 } 9326 9327 // Check for jumps past the implicit initializer. C++0x 9328 // clarifies that this applies to a "variable with automatic 9329 // storage duration", not a "local variable". 9330 // C++11 [stmt.dcl]p3 9331 // A program that jumps from a point where a variable with automatic 9332 // storage duration is not in scope to a point where it is in scope is 9333 // ill-formed unless the variable has scalar type, class type with a 9334 // trivial default constructor and a trivial destructor, a cv-qualified 9335 // version of one of these types, or an array of one of the preceding 9336 // types and is declared without an initializer. 9337 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9338 if (const RecordType *Record 9339 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9340 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9341 // Mark the function for further checking even if the looser rules of 9342 // C++11 do not require such checks, so that we can diagnose 9343 // incompatibilities with C++98. 9344 if (!CXXRecord->isPOD()) 9345 getCurFunction()->setHasBranchProtectedScope(); 9346 } 9347 } 9348 9349 // C++03 [dcl.init]p9: 9350 // If no initializer is specified for an object, and the 9351 // object is of (possibly cv-qualified) non-POD class type (or 9352 // array thereof), the object shall be default-initialized; if 9353 // the object is of const-qualified type, the underlying class 9354 // type shall have a user-declared default 9355 // constructor. Otherwise, if no initializer is specified for 9356 // a non- static object, the object and its subobjects, if 9357 // any, have an indeterminate initial value); if the object 9358 // or any of its subobjects are of const-qualified type, the 9359 // program is ill-formed. 9360 // C++0x [dcl.init]p11: 9361 // If no initializer is specified for an object, the object is 9362 // default-initialized; [...]. 9363 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9364 InitializationKind Kind 9365 = InitializationKind::CreateDefault(Var->getLocation()); 9366 9367 InitializationSequence InitSeq(*this, Entity, Kind, None); 9368 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9369 if (Init.isInvalid()) 9370 Var->setInvalidDecl(); 9371 else if (Init.get()) { 9372 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9373 // This is important for template substitution. 9374 Var->setInitStyle(VarDecl::CallInit); 9375 } 9376 9377 CheckCompleteVariableDeclaration(Var); 9378 } 9379 } 9380 9381 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9382 VarDecl *VD = dyn_cast<VarDecl>(D); 9383 if (!VD) { 9384 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9385 D->setInvalidDecl(); 9386 return; 9387 } 9388 9389 VD->setCXXForRangeDecl(true); 9390 9391 // for-range-declaration cannot be given a storage class specifier. 9392 int Error = -1; 9393 switch (VD->getStorageClass()) { 9394 case SC_None: 9395 break; 9396 case SC_Extern: 9397 Error = 0; 9398 break; 9399 case SC_Static: 9400 Error = 1; 9401 break; 9402 case SC_PrivateExtern: 9403 Error = 2; 9404 break; 9405 case SC_Auto: 9406 Error = 3; 9407 break; 9408 case SC_Register: 9409 Error = 4; 9410 break; 9411 case SC_OpenCLWorkGroupLocal: 9412 llvm_unreachable("Unexpected storage class"); 9413 } 9414 if (Error != -1) { 9415 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9416 << VD->getDeclName() << Error; 9417 D->setInvalidDecl(); 9418 } 9419 } 9420 9421 StmtResult 9422 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9423 IdentifierInfo *Ident, 9424 ParsedAttributes &Attrs, 9425 SourceLocation AttrEnd) { 9426 // C++1y [stmt.iter]p1: 9427 // A range-based for statement of the form 9428 // for ( for-range-identifier : for-range-initializer ) statement 9429 // is equivalent to 9430 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9431 DeclSpec DS(Attrs.getPool().getFactory()); 9432 9433 const char *PrevSpec; 9434 unsigned DiagID; 9435 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 9436 getPrintingPolicy()); 9437 9438 Declarator D(DS, Declarator::ForContext); 9439 D.SetIdentifier(Ident, IdentLoc); 9440 D.takeAttributes(Attrs, AttrEnd); 9441 9442 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 9443 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 9444 EmptyAttrs, IdentLoc); 9445 Decl *Var = ActOnDeclarator(S, D); 9446 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 9447 FinalizeDeclaration(Var); 9448 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 9449 AttrEnd.isValid() ? AttrEnd : IdentLoc); 9450 } 9451 9452 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 9453 if (var->isInvalidDecl()) return; 9454 9455 // In ARC, don't allow jumps past the implicit initialization of a 9456 // local retaining variable. 9457 if (getLangOpts().ObjCAutoRefCount && 9458 var->hasLocalStorage()) { 9459 switch (var->getType().getObjCLifetime()) { 9460 case Qualifiers::OCL_None: 9461 case Qualifiers::OCL_ExplicitNone: 9462 case Qualifiers::OCL_Autoreleasing: 9463 break; 9464 9465 case Qualifiers::OCL_Weak: 9466 case Qualifiers::OCL_Strong: 9467 getCurFunction()->setHasBranchProtectedScope(); 9468 break; 9469 } 9470 } 9471 9472 // Warn about externally-visible variables being defined without a 9473 // prior declaration. We only want to do this for global 9474 // declarations, but we also specifically need to avoid doing it for 9475 // class members because the linkage of an anonymous class can 9476 // change if it's later given a typedef name. 9477 if (var->isThisDeclarationADefinition() && 9478 var->getDeclContext()->getRedeclContext()->isFileContext() && 9479 var->isExternallyVisible() && var->hasLinkage() && 9480 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9481 var->getLocation())) { 9482 // Find a previous declaration that's not a definition. 9483 VarDecl *prev = var->getPreviousDecl(); 9484 while (prev && prev->isThisDeclarationADefinition()) 9485 prev = prev->getPreviousDecl(); 9486 9487 if (!prev) 9488 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9489 } 9490 9491 if (var->getTLSKind() == VarDecl::TLS_Static) { 9492 const Expr *Culprit; 9493 if (var->getType().isDestructedType()) { 9494 // GNU C++98 edits for __thread, [basic.start.term]p3: 9495 // The type of an object with thread storage duration shall not 9496 // have a non-trivial destructor. 9497 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9498 if (getLangOpts().CPlusPlus11) 9499 Diag(var->getLocation(), diag::note_use_thread_local); 9500 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9501 !var->getInit()->isConstantInitializer( 9502 Context, var->getType()->isReferenceType(), &Culprit)) { 9503 // GNU C++98 edits for __thread, [basic.start.init]p4: 9504 // An object of thread storage duration shall not require dynamic 9505 // initialization. 9506 // FIXME: Need strict checking here. 9507 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9508 << Culprit->getSourceRange(); 9509 if (getLangOpts().CPlusPlus11) 9510 Diag(var->getLocation(), diag::note_use_thread_local); 9511 } 9512 9513 } 9514 9515 if (var->isThisDeclarationADefinition() && 9516 ActiveTemplateInstantiations.empty()) { 9517 PragmaStack<StringLiteral *> *Stack = nullptr; 9518 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 9519 if (var->getType().isConstQualified()) 9520 Stack = &ConstSegStack; 9521 else if (!var->getInit()) { 9522 Stack = &BSSSegStack; 9523 SectionFlags |= ASTContext::PSF_Write; 9524 } else { 9525 Stack = &DataSegStack; 9526 SectionFlags |= ASTContext::PSF_Write; 9527 } 9528 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue) 9529 var->addAttr( 9530 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 9531 Stack->CurrentValue->getString(), 9532 Stack->CurrentPragmaLocation)); 9533 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9534 if (UnifySection(SA->getName(), SectionFlags, var)) 9535 var->dropAttr<SectionAttr>(); 9536 9537 // Apply the init_seg attribute if this has an initializer. If the 9538 // initializer turns out to not be dynamic, we'll end up ignoring this 9539 // attribute. 9540 if (CurInitSeg && var->getInit()) 9541 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 9542 CurInitSegLoc)); 9543 } 9544 9545 // All the following checks are C++ only. 9546 if (!getLangOpts().CPlusPlus) return; 9547 9548 QualType type = var->getType(); 9549 if (type->isDependentType()) return; 9550 9551 // __block variables might require us to capture a copy-initializer. 9552 if (var->hasAttr<BlocksAttr>()) { 9553 // It's currently invalid to ever have a __block variable with an 9554 // array type; should we diagnose that here? 9555 9556 // Regardless, we don't want to ignore array nesting when 9557 // constructing this copy. 9558 if (type->isStructureOrClassType()) { 9559 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9560 SourceLocation poi = var->getLocation(); 9561 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9562 ExprResult result 9563 = PerformMoveOrCopyInitialization( 9564 InitializedEntity::InitializeBlock(poi, type, false), 9565 var, var->getType(), varRef, /*AllowNRVO=*/true); 9566 if (!result.isInvalid()) { 9567 result = MaybeCreateExprWithCleanups(result); 9568 Expr *init = result.getAs<Expr>(); 9569 Context.setBlockVarCopyInits(var, init); 9570 } 9571 } 9572 } 9573 9574 Expr *Init = var->getInit(); 9575 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 9576 QualType baseType = Context.getBaseElementType(type); 9577 9578 if (!var->getDeclContext()->isDependentContext() && 9579 Init && !Init->isValueDependent()) { 9580 if (IsGlobal && !var->isConstexpr() && 9581 !getDiagnostics().isIgnored(diag::warn_global_constructor, 9582 var->getLocation())) { 9583 // Warn about globals which don't have a constant initializer. Don't 9584 // warn about globals with a non-trivial destructor because we already 9585 // warned about them. 9586 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9587 if (!(RD && !RD->hasTrivialDestructor()) && 9588 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9589 Diag(var->getLocation(), diag::warn_global_constructor) 9590 << Init->getSourceRange(); 9591 } 9592 9593 if (var->isConstexpr()) { 9594 SmallVector<PartialDiagnosticAt, 8> Notes; 9595 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9596 SourceLocation DiagLoc = var->getLocation(); 9597 // If the note doesn't add any useful information other than a source 9598 // location, fold it into the primary diagnostic. 9599 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9600 diag::note_invalid_subexpr_in_const_expr) { 9601 DiagLoc = Notes[0].first; 9602 Notes.clear(); 9603 } 9604 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9605 << var << Init->getSourceRange(); 9606 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9607 Diag(Notes[I].first, Notes[I].second); 9608 } 9609 } else if (var->isUsableInConstantExpressions(Context)) { 9610 // Check whether the initializer of a const variable of integral or 9611 // enumeration type is an ICE now, since we can't tell whether it was 9612 // initialized by a constant expression if we check later. 9613 var->checkInitIsICE(); 9614 } 9615 } 9616 9617 // Require the destructor. 9618 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9619 FinalizeVarWithDestructor(var, recordType); 9620 } 9621 9622 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9623 /// any semantic actions necessary after any initializer has been attached. 9624 void 9625 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9626 // Note that we are no longer parsing the initializer for this declaration. 9627 ParsingInitForAutoVars.erase(ThisDecl); 9628 9629 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9630 if (!VD) 9631 return; 9632 9633 checkAttributesAfterMerging(*this, *VD); 9634 9635 // Static locals inherit dll attributes from their function. 9636 if (VD->isStaticLocal()) { 9637 if (FunctionDecl *FD = 9638 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 9639 if (Attr *A = getDLLAttr(FD)) { 9640 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 9641 NewAttr->setInherited(true); 9642 VD->addAttr(NewAttr); 9643 } 9644 } 9645 } 9646 9647 // Grab the dllimport or dllexport attribute off of the VarDecl. 9648 const InheritableAttr *DLLAttr = getDLLAttr(VD); 9649 9650 // Imported static data members cannot be defined out-of-line. 9651 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 9652 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9653 VD->isThisDeclarationADefinition()) { 9654 // We allow definitions of dllimport class template static data members 9655 // with a warning. 9656 CXXRecordDecl *Context = 9657 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9658 bool IsClassTemplateMember = 9659 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9660 Context->getDescribedClassTemplate(); 9661 9662 Diag(VD->getLocation(), 9663 IsClassTemplateMember 9664 ? diag::warn_attribute_dllimport_static_field_definition 9665 : diag::err_attribute_dllimport_static_field_definition); 9666 Diag(IA->getLocation(), diag::note_attribute); 9667 if (!IsClassTemplateMember) 9668 VD->setInvalidDecl(); 9669 } 9670 } 9671 9672 // dllimport/dllexport variables cannot be thread local, their TLS index 9673 // isn't exported with the variable. 9674 if (DLLAttr && VD->getTLSKind()) { 9675 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 9676 << DLLAttr; 9677 VD->setInvalidDecl(); 9678 } 9679 9680 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9681 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9682 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9683 VD->dropAttr<UsedAttr>(); 9684 } 9685 } 9686 9687 const DeclContext *DC = VD->getDeclContext(); 9688 // If there's a #pragma GCC visibility in scope, and this isn't a class 9689 // member, set the visibility of this variable. 9690 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9691 AddPushedVisibilityAttribute(VD); 9692 9693 // FIXME: Warn on unused templates. 9694 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9695 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9696 MarkUnusedFileScopedDecl(VD); 9697 9698 // Now we have parsed the initializer and can update the table of magic 9699 // tag values. 9700 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9701 !VD->getType()->isIntegralOrEnumerationType()) 9702 return; 9703 9704 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9705 const Expr *MagicValueExpr = VD->getInit(); 9706 if (!MagicValueExpr) { 9707 continue; 9708 } 9709 llvm::APSInt MagicValueInt; 9710 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9711 Diag(I->getRange().getBegin(), 9712 diag::err_type_tag_for_datatype_not_ice) 9713 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9714 continue; 9715 } 9716 if (MagicValueInt.getActiveBits() > 64) { 9717 Diag(I->getRange().getBegin(), 9718 diag::err_type_tag_for_datatype_too_large) 9719 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9720 continue; 9721 } 9722 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9723 RegisterTypeTagForDatatype(I->getArgumentKind(), 9724 MagicValue, 9725 I->getMatchingCType(), 9726 I->getLayoutCompatible(), 9727 I->getMustBeNull()); 9728 } 9729 } 9730 9731 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9732 ArrayRef<Decl *> Group) { 9733 SmallVector<Decl*, 8> Decls; 9734 9735 if (DS.isTypeSpecOwned()) 9736 Decls.push_back(DS.getRepAsDecl()); 9737 9738 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9739 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9740 if (Decl *D = Group[i]) { 9741 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9742 if (!FirstDeclaratorInGroup) 9743 FirstDeclaratorInGroup = DD; 9744 Decls.push_back(D); 9745 } 9746 9747 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9748 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9749 HandleTagNumbering(*this, Tag, S); 9750 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9751 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9752 } 9753 } 9754 9755 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9756 } 9757 9758 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9759 /// group, performing any necessary semantic checking. 9760 Sema::DeclGroupPtrTy 9761 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 9762 bool TypeMayContainAuto) { 9763 // C++0x [dcl.spec.auto]p7: 9764 // If the type deduced for the template parameter U is not the same in each 9765 // deduction, the program is ill-formed. 9766 // FIXME: When initializer-list support is added, a distinction is needed 9767 // between the deduced type U and the deduced type which 'auto' stands for. 9768 // auto a = 0, b = { 1, 2, 3 }; 9769 // is legal because the deduced type U is 'int' in both cases. 9770 if (TypeMayContainAuto && Group.size() > 1) { 9771 QualType Deduced; 9772 CanQualType DeducedCanon; 9773 VarDecl *DeducedDecl = nullptr; 9774 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9775 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9776 AutoType *AT = D->getType()->getContainedAutoType(); 9777 // Don't reissue diagnostics when instantiating a template. 9778 if (AT && D->isInvalidDecl()) 9779 break; 9780 QualType U = AT ? AT->getDeducedType() : QualType(); 9781 if (!U.isNull()) { 9782 CanQualType UCanon = Context.getCanonicalType(U); 9783 if (Deduced.isNull()) { 9784 Deduced = U; 9785 DeducedCanon = UCanon; 9786 DeducedDecl = D; 9787 } else if (DeducedCanon != UCanon) { 9788 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9789 diag::err_auto_different_deductions) 9790 << (AT->isDecltypeAuto() ? 1 : 0) 9791 << Deduced << DeducedDecl->getDeclName() 9792 << U << D->getDeclName() 9793 << DeducedDecl->getInit()->getSourceRange() 9794 << D->getInit()->getSourceRange(); 9795 D->setInvalidDecl(); 9796 break; 9797 } 9798 } 9799 } 9800 } 9801 } 9802 9803 ActOnDocumentableDecls(Group); 9804 9805 return DeclGroupPtrTy::make( 9806 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9807 } 9808 9809 void Sema::ActOnDocumentableDecl(Decl *D) { 9810 ActOnDocumentableDecls(D); 9811 } 9812 9813 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9814 // Don't parse the comment if Doxygen diagnostics are ignored. 9815 if (Group.empty() || !Group[0]) 9816 return; 9817 9818 if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation())) 9819 return; 9820 9821 if (Group.size() >= 2) { 9822 // This is a decl group. Normally it will contain only declarations 9823 // produced from declarator list. But in case we have any definitions or 9824 // additional declaration references: 9825 // 'typedef struct S {} S;' 9826 // 'typedef struct S *S;' 9827 // 'struct S *pS;' 9828 // FinalizeDeclaratorGroup adds these as separate declarations. 9829 Decl *MaybeTagDecl = Group[0]; 9830 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9831 Group = Group.slice(1); 9832 } 9833 } 9834 9835 // See if there are any new comments that are not attached to a decl. 9836 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9837 if (!Comments.empty() && 9838 !Comments.back()->isAttached()) { 9839 // There is at least one comment that not attached to a decl. 9840 // Maybe it should be attached to one of these decls? 9841 // 9842 // Note that this way we pick up not only comments that precede the 9843 // declaration, but also comments that *follow* the declaration -- thanks to 9844 // the lookahead in the lexer: we've consumed the semicolon and looked 9845 // ahead through comments. 9846 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9847 Context.getCommentForDecl(Group[i], &PP); 9848 } 9849 } 9850 9851 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9852 /// to introduce parameters into function prototype scope. 9853 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9854 const DeclSpec &DS = D.getDeclSpec(); 9855 9856 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9857 9858 // C++03 [dcl.stc]p2 also permits 'auto'. 9859 StorageClass SC = SC_None; 9860 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9861 SC = SC_Register; 9862 } else if (getLangOpts().CPlusPlus && 9863 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9864 SC = SC_Auto; 9865 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9866 Diag(DS.getStorageClassSpecLoc(), 9867 diag::err_invalid_storage_class_in_func_decl); 9868 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9869 } 9870 9871 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9872 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9873 << DeclSpec::getSpecifierName(TSCS); 9874 if (DS.isConstexprSpecified()) 9875 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9876 << 0; 9877 9878 DiagnoseFunctionSpecifiers(DS); 9879 9880 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9881 QualType parmDeclType = TInfo->getType(); 9882 9883 if (getLangOpts().CPlusPlus) { 9884 // Check that there are no default arguments inside the type of this 9885 // parameter. 9886 CheckExtraCXXDefaultArguments(D); 9887 9888 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9889 if (D.getCXXScopeSpec().isSet()) { 9890 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9891 << D.getCXXScopeSpec().getRange(); 9892 D.getCXXScopeSpec().clear(); 9893 } 9894 } 9895 9896 // Ensure we have a valid name 9897 IdentifierInfo *II = nullptr; 9898 if (D.hasName()) { 9899 II = D.getIdentifier(); 9900 if (!II) { 9901 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9902 << GetNameForDeclarator(D).getName(); 9903 D.setInvalidType(true); 9904 } 9905 } 9906 9907 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9908 if (II) { 9909 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9910 ForRedeclaration); 9911 LookupName(R, S); 9912 if (R.isSingleResult()) { 9913 NamedDecl *PrevDecl = R.getFoundDecl(); 9914 if (PrevDecl->isTemplateParameter()) { 9915 // Maybe we will complain about the shadowed template parameter. 9916 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9917 // Just pretend that we didn't see the previous declaration. 9918 PrevDecl = nullptr; 9919 } else if (S->isDeclScope(PrevDecl)) { 9920 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9921 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9922 9923 // Recover by removing the name 9924 II = nullptr; 9925 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 9926 D.setInvalidType(true); 9927 } 9928 } 9929 } 9930 9931 // Temporarily put parameter variables in the translation unit, not 9932 // the enclosing context. This prevents them from accidentally 9933 // looking like class members in C++. 9934 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9935 D.getLocStart(), 9936 D.getIdentifierLoc(), II, 9937 parmDeclType, TInfo, 9938 SC); 9939 9940 if (D.isInvalidType()) 9941 New->setInvalidDecl(); 9942 9943 assert(S->isFunctionPrototypeScope()); 9944 assert(S->getFunctionPrototypeDepth() >= 1); 9945 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9946 S->getNextFunctionPrototypeIndex()); 9947 9948 // Add the parameter declaration into this scope. 9949 S->AddDecl(New); 9950 if (II) 9951 IdResolver.AddDecl(New); 9952 9953 ProcessDeclAttributes(S, New, D); 9954 9955 if (D.getDeclSpec().isModulePrivateSpecified()) 9956 Diag(New->getLocation(), diag::err_module_private_local) 9957 << 1 << New->getDeclName() 9958 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9959 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9960 9961 if (New->hasAttr<BlocksAttr>()) { 9962 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9963 } 9964 return New; 9965 } 9966 9967 /// \brief Synthesizes a variable for a parameter arising from a 9968 /// typedef. 9969 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9970 SourceLocation Loc, 9971 QualType T) { 9972 /* FIXME: setting StartLoc == Loc. 9973 Would it be worth to modify callers so as to provide proper source 9974 location for the unnamed parameters, embedding the parameter's type? */ 9975 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 9976 T, Context.getTrivialTypeSourceInfo(T, Loc), 9977 SC_None, nullptr); 9978 Param->setImplicit(); 9979 return Param; 9980 } 9981 9982 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9983 ParmVarDecl * const *ParamEnd) { 9984 // Don't diagnose unused-parameter errors in template instantiations; we 9985 // will already have done so in the template itself. 9986 if (!ActiveTemplateInstantiations.empty()) 9987 return; 9988 9989 for (; Param != ParamEnd; ++Param) { 9990 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9991 !(*Param)->hasAttr<UnusedAttr>()) { 9992 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9993 << (*Param)->getDeclName(); 9994 } 9995 } 9996 } 9997 9998 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9999 ParmVarDecl * const *ParamEnd, 10000 QualType ReturnTy, 10001 NamedDecl *D) { 10002 if (LangOpts.NumLargeByValueCopy == 0) // No check. 10003 return; 10004 10005 // Warn if the return value is pass-by-value and larger than the specified 10006 // threshold. 10007 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 10008 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 10009 if (Size > LangOpts.NumLargeByValueCopy) 10010 Diag(D->getLocation(), diag::warn_return_value_size) 10011 << D->getDeclName() << Size; 10012 } 10013 10014 // Warn if any parameter is pass-by-value and larger than the specified 10015 // threshold. 10016 for (; Param != ParamEnd; ++Param) { 10017 QualType T = (*Param)->getType(); 10018 if (T->isDependentType() || !T.isPODType(Context)) 10019 continue; 10020 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 10021 if (Size > LangOpts.NumLargeByValueCopy) 10022 Diag((*Param)->getLocation(), diag::warn_parameter_size) 10023 << (*Param)->getDeclName() << Size; 10024 } 10025 } 10026 10027 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 10028 SourceLocation NameLoc, IdentifierInfo *Name, 10029 QualType T, TypeSourceInfo *TSInfo, 10030 StorageClass SC) { 10031 // In ARC, infer a lifetime qualifier for appropriate parameter types. 10032 if (getLangOpts().ObjCAutoRefCount && 10033 T.getObjCLifetime() == Qualifiers::OCL_None && 10034 T->isObjCLifetimeType()) { 10035 10036 Qualifiers::ObjCLifetime lifetime; 10037 10038 // Special cases for arrays: 10039 // - if it's const, use __unsafe_unretained 10040 // - otherwise, it's an error 10041 if (T->isArrayType()) { 10042 if (!T.isConstQualified()) { 10043 DelayedDiagnostics.add( 10044 sema::DelayedDiagnostic::makeForbiddenType( 10045 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 10046 } 10047 lifetime = Qualifiers::OCL_ExplicitNone; 10048 } else { 10049 lifetime = T->getObjCARCImplicitLifetime(); 10050 } 10051 T = Context.getLifetimeQualifiedType(T, lifetime); 10052 } 10053 10054 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 10055 Context.getAdjustedParameterType(T), 10056 TSInfo, SC, nullptr); 10057 10058 // Parameters can not be abstract class types. 10059 // For record types, this is done by the AbstractClassUsageDiagnoser once 10060 // the class has been completely parsed. 10061 if (!CurContext->isRecord() && 10062 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 10063 AbstractParamType)) 10064 New->setInvalidDecl(); 10065 10066 // Parameter declarators cannot be interface types. All ObjC objects are 10067 // passed by reference. 10068 if (T->isObjCObjectType()) { 10069 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 10070 Diag(NameLoc, 10071 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 10072 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 10073 T = Context.getObjCObjectPointerType(T); 10074 New->setType(T); 10075 } 10076 10077 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 10078 // duration shall not be qualified by an address-space qualifier." 10079 // Since all parameters have automatic store duration, they can not have 10080 // an address space. 10081 if (T.getAddressSpace() != 0) { 10082 // OpenCL allows function arguments declared to be an array of a type 10083 // to be qualified with an address space. 10084 if (!(getLangOpts().OpenCL && T->isArrayType())) { 10085 Diag(NameLoc, diag::err_arg_with_address_space); 10086 New->setInvalidDecl(); 10087 } 10088 } 10089 10090 return New; 10091 } 10092 10093 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 10094 SourceLocation LocAfterDecls) { 10095 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10096 10097 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 10098 // for a K&R function. 10099 if (!FTI.hasPrototype) { 10100 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10101 --i; 10102 if (FTI.Params[i].Param == nullptr) { 10103 SmallString<256> Code; 10104 llvm::raw_svector_ostream(Code) 10105 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10106 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10107 << FTI.Params[i].Ident 10108 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 10109 10110 // Implicitly declare the argument as type 'int' for lack of a better 10111 // type. 10112 AttributeFactory attrs; 10113 DeclSpec DS(attrs); 10114 const char* PrevSpec; // unused 10115 unsigned DiagID; // unused 10116 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10117 DiagID, Context.getPrintingPolicy()); 10118 // Use the identifier location for the type source range. 10119 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10120 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10121 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10122 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10123 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10124 } 10125 } 10126 } 10127 } 10128 10129 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 10130 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10131 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10132 Scope *ParentScope = FnBodyScope->getParent(); 10133 10134 D.setFunctionDefinitionKind(FDK_Definition); 10135 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 10136 return ActOnStartOfFunctionDef(FnBodyScope, DP); 10137 } 10138 10139 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10140 Consumer.HandleInlineMethodDefinition(D); 10141 } 10142 10143 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10144 const FunctionDecl*& PossibleZeroParamPrototype) { 10145 // Don't warn about invalid declarations. 10146 if (FD->isInvalidDecl()) 10147 return false; 10148 10149 // Or declarations that aren't global. 10150 if (!FD->isGlobal()) 10151 return false; 10152 10153 // Don't warn about C++ member functions. 10154 if (isa<CXXMethodDecl>(FD)) 10155 return false; 10156 10157 // Don't warn about 'main'. 10158 if (FD->isMain()) 10159 return false; 10160 10161 // Don't warn about inline functions. 10162 if (FD->isInlined()) 10163 return false; 10164 10165 // Don't warn about function templates. 10166 if (FD->getDescribedFunctionTemplate()) 10167 return false; 10168 10169 // Don't warn about function template specializations. 10170 if (FD->isFunctionTemplateSpecialization()) 10171 return false; 10172 10173 // Don't warn for OpenCL kernels. 10174 if (FD->hasAttr<OpenCLKernelAttr>()) 10175 return false; 10176 10177 bool MissingPrototype = true; 10178 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10179 Prev; Prev = Prev->getPreviousDecl()) { 10180 // Ignore any declarations that occur in function or method 10181 // scope, because they aren't visible from the header. 10182 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10183 continue; 10184 10185 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10186 if (FD->getNumParams() == 0) 10187 PossibleZeroParamPrototype = Prev; 10188 break; 10189 } 10190 10191 return MissingPrototype; 10192 } 10193 10194 void 10195 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10196 const FunctionDecl *EffectiveDefinition) { 10197 // Don't complain if we're in GNU89 mode and the previous definition 10198 // was an extern inline function. 10199 const FunctionDecl *Definition = EffectiveDefinition; 10200 if (!Definition) 10201 if (!FD->isDefined(Definition)) 10202 return; 10203 10204 if (canRedefineFunction(Definition, getLangOpts())) 10205 return; 10206 10207 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10208 Definition->getStorageClass() == SC_Extern) 10209 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10210 << FD->getDeclName() << getLangOpts().CPlusPlus; 10211 else 10212 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10213 10214 Diag(Definition->getLocation(), diag::note_previous_definition); 10215 FD->setInvalidDecl(); 10216 } 10217 10218 10219 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10220 Sema &S) { 10221 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10222 10223 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10224 LSI->CallOperator = CallOperator; 10225 LSI->Lambda = LambdaClass; 10226 LSI->ReturnType = CallOperator->getReturnType(); 10227 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10228 10229 if (LCD == LCD_None) 10230 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10231 else if (LCD == LCD_ByCopy) 10232 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10233 else if (LCD == LCD_ByRef) 10234 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10235 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10236 10237 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10238 LSI->Mutable = !CallOperator->isConst(); 10239 10240 // Add the captures to the LSI so they can be noted as already 10241 // captured within tryCaptureVar. 10242 auto I = LambdaClass->field_begin(); 10243 for (const auto &C : LambdaClass->captures()) { 10244 if (C.capturesVariable()) { 10245 VarDecl *VD = C.getCapturedVar(); 10246 if (VD->isInitCapture()) 10247 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10248 QualType CaptureType = VD->getType(); 10249 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10250 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10251 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 10252 /*EllipsisLoc*/C.isPackExpansion() 10253 ? C.getEllipsisLoc() : SourceLocation(), 10254 CaptureType, /*Expr*/ nullptr); 10255 10256 } else if (C.capturesThis()) { 10257 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10258 S.getCurrentThisType(), /*Expr*/ nullptr); 10259 } else { 10260 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10261 } 10262 ++I; 10263 } 10264 } 10265 10266 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 10267 // Clear the last template instantiation error context. 10268 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10269 10270 if (!D) 10271 return D; 10272 FunctionDecl *FD = nullptr; 10273 10274 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10275 FD = FunTmpl->getTemplatedDecl(); 10276 else 10277 FD = cast<FunctionDecl>(D); 10278 // If we are instantiating a generic lambda call operator, push 10279 // a LambdaScopeInfo onto the function stack. But use the information 10280 // that's already been calculated (ActOnLambdaExpr) to prime the current 10281 // LambdaScopeInfo. 10282 // When the template operator is being specialized, the LambdaScopeInfo, 10283 // has to be properly restored so that tryCaptureVariable doesn't try 10284 // and capture any new variables. In addition when calculating potential 10285 // captures during transformation of nested lambdas, it is necessary to 10286 // have the LSI properly restored. 10287 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10288 assert(ActiveTemplateInstantiations.size() && 10289 "There should be an active template instantiation on the stack " 10290 "when instantiating a generic lambda!"); 10291 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10292 } 10293 else 10294 // Enter a new function scope 10295 PushFunctionScope(); 10296 10297 // See if this is a redefinition. 10298 if (!FD->isLateTemplateParsed()) 10299 CheckForFunctionRedefinition(FD); 10300 10301 // Builtin functions cannot be defined. 10302 if (unsigned BuiltinID = FD->getBuiltinID()) { 10303 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10304 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10305 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10306 FD->setInvalidDecl(); 10307 } 10308 } 10309 10310 // The return type of a function definition must be complete 10311 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10312 QualType ResultType = FD->getReturnType(); 10313 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10314 !FD->isInvalidDecl() && 10315 RequireCompleteType(FD->getLocation(), ResultType, 10316 diag::err_func_def_incomplete_result)) 10317 FD->setInvalidDecl(); 10318 10319 // GNU warning -Wmissing-prototypes: 10320 // Warn if a global function is defined without a previous 10321 // prototype declaration. This warning is issued even if the 10322 // definition itself provides a prototype. The aim is to detect 10323 // global functions that fail to be declared in header files. 10324 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 10325 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 10326 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 10327 10328 if (PossibleZeroParamPrototype) { 10329 // We found a declaration that is not a prototype, 10330 // but that could be a zero-parameter prototype 10331 if (TypeSourceInfo *TI = 10332 PossibleZeroParamPrototype->getTypeSourceInfo()) { 10333 TypeLoc TL = TI->getTypeLoc(); 10334 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 10335 Diag(PossibleZeroParamPrototype->getLocation(), 10336 diag::note_declaration_not_a_prototype) 10337 << PossibleZeroParamPrototype 10338 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 10339 } 10340 } 10341 } 10342 10343 if (FnBodyScope) 10344 PushDeclContext(FnBodyScope, FD); 10345 10346 // Check the validity of our function parameters 10347 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10348 /*CheckParameterNames=*/true); 10349 10350 // Introduce our parameters into the function scope 10351 for (auto Param : FD->params()) { 10352 Param->setOwningFunction(FD); 10353 10354 // If this has an identifier, add it to the scope stack. 10355 if (Param->getIdentifier() && FnBodyScope) { 10356 CheckShadow(FnBodyScope, Param); 10357 10358 PushOnScopeChains(Param, FnBodyScope); 10359 } 10360 } 10361 10362 // If we had any tags defined in the function prototype, 10363 // introduce them into the function scope. 10364 if (FnBodyScope) { 10365 for (ArrayRef<NamedDecl *>::iterator 10366 I = FD->getDeclsInPrototypeScope().begin(), 10367 E = FD->getDeclsInPrototypeScope().end(); 10368 I != E; ++I) { 10369 NamedDecl *D = *I; 10370 10371 // Some of these decls (like enums) may have been pinned to the translation unit 10372 // for lack of a real context earlier. If so, remove from the translation unit 10373 // and reattach to the current context. 10374 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 10375 // Is the decl actually in the context? 10376 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 10377 if (DI == D) { 10378 Context.getTranslationUnitDecl()->removeDecl(D); 10379 break; 10380 } 10381 } 10382 // Either way, reassign the lexical decl context to our FunctionDecl. 10383 D->setLexicalDeclContext(CurContext); 10384 } 10385 10386 // If the decl has a non-null name, make accessible in the current scope. 10387 if (!D->getName().empty()) 10388 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 10389 10390 // Similarly, dive into enums and fish their constants out, making them 10391 // accessible in this scope. 10392 if (auto *ED = dyn_cast<EnumDecl>(D)) { 10393 for (auto *EI : ED->enumerators()) 10394 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 10395 } 10396 } 10397 } 10398 10399 // Ensure that the function's exception specification is instantiated. 10400 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 10401 ResolveExceptionSpec(D->getLocation(), FPT); 10402 10403 // dllimport cannot be applied to non-inline function definitions. 10404 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 10405 !FD->isTemplateInstantiation()) { 10406 assert(!FD->hasAttr<DLLExportAttr>()); 10407 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 10408 FD->setInvalidDecl(); 10409 return D; 10410 } 10411 // We want to attach documentation to original Decl (which might be 10412 // a function template). 10413 ActOnDocumentableDecl(D); 10414 if (getCurLexicalContext()->isObjCContainer() && 10415 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 10416 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 10417 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 10418 10419 return D; 10420 } 10421 10422 /// \brief Given the set of return statements within a function body, 10423 /// compute the variables that are subject to the named return value 10424 /// optimization. 10425 /// 10426 /// Each of the variables that is subject to the named return value 10427 /// optimization will be marked as NRVO variables in the AST, and any 10428 /// return statement that has a marked NRVO variable as its NRVO candidate can 10429 /// use the named return value optimization. 10430 /// 10431 /// This function applies a very simplistic algorithm for NRVO: if every return 10432 /// statement in the scope of a variable has the same NRVO candidate, that 10433 /// candidate is an NRVO variable. 10434 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 10435 ReturnStmt **Returns = Scope->Returns.data(); 10436 10437 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 10438 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 10439 if (!NRVOCandidate->isNRVOVariable()) 10440 Returns[I]->setNRVOCandidate(nullptr); 10441 } 10442 } 10443 } 10444 10445 bool Sema::canDelayFunctionBody(const Declarator &D) { 10446 // We can't delay parsing the body of a constexpr function template (yet). 10447 if (D.getDeclSpec().isConstexprSpecified()) 10448 return false; 10449 10450 // We can't delay parsing the body of a function template with a deduced 10451 // return type (yet). 10452 if (D.getDeclSpec().containsPlaceholderType()) { 10453 // If the placeholder introduces a non-deduced trailing return type, 10454 // we can still delay parsing it. 10455 if (D.getNumTypeObjects()) { 10456 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 10457 if (Outer.Kind == DeclaratorChunk::Function && 10458 Outer.Fun.hasTrailingReturnType()) { 10459 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 10460 return Ty.isNull() || !Ty->isUndeducedType(); 10461 } 10462 } 10463 return false; 10464 } 10465 10466 return true; 10467 } 10468 10469 bool Sema::canSkipFunctionBody(Decl *D) { 10470 // We cannot skip the body of a function (or function template) which is 10471 // constexpr, since we may need to evaluate its body in order to parse the 10472 // rest of the file. 10473 // We cannot skip the body of a function with an undeduced return type, 10474 // because any callers of that function need to know the type. 10475 if (const FunctionDecl *FD = D->getAsFunction()) 10476 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 10477 return false; 10478 return Consumer.shouldSkipFunctionBody(D); 10479 } 10480 10481 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 10482 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 10483 FD->setHasSkippedBody(); 10484 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10485 MD->setHasSkippedBody(); 10486 return ActOnFinishFunctionBody(Decl, nullptr); 10487 } 10488 10489 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10490 return ActOnFinishFunctionBody(D, BodyArg, false); 10491 } 10492 10493 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10494 bool IsInstantiation) { 10495 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10496 10497 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10498 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10499 10500 if (FD) { 10501 FD->setBody(Body); 10502 10503 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body && 10504 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10505 // If the function has a deduced result type but contains no 'return' 10506 // statements, the result type as written must be exactly 'auto', and 10507 // the deduced result type is 'void'. 10508 if (!FD->getReturnType()->getAs<AutoType>()) { 10509 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10510 << FD->getReturnType(); 10511 FD->setInvalidDecl(); 10512 } else { 10513 // Substitute 'void' for the 'auto' in the type. 10514 TypeLoc ResultType = getReturnTypeLoc(FD); 10515 Context.adjustDeducedFunctionResultType( 10516 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10517 } 10518 } 10519 10520 // The only way to be included in UndefinedButUsed is if there is an 10521 // ODR use before the definition. Avoid the expensive map lookup if this 10522 // is the first declaration. 10523 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 10524 if (!FD->isExternallyVisible()) 10525 UndefinedButUsed.erase(FD); 10526 else if (FD->isInlined() && 10527 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10528 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 10529 UndefinedButUsed.erase(FD); 10530 } 10531 10532 // If the function implicitly returns zero (like 'main') or is naked, 10533 // don't complain about missing return statements. 10534 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 10535 WP.disableCheckFallThrough(); 10536 10537 // MSVC permits the use of pure specifier (=0) on function definition, 10538 // defined at class scope, warn about this non-standard construct. 10539 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10540 Diag(FD->getLocation(), diag::ext_pure_function_definition); 10541 10542 if (!FD->isInvalidDecl()) { 10543 // Don't diagnose unused parameters of defaulted or deleted functions. 10544 if (Body) 10545 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10546 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10547 FD->getReturnType(), FD); 10548 10549 // If this is a structor, we need a vtable. 10550 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10551 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10552 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 10553 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 10554 10555 // Try to apply the named return value optimization. We have to check 10556 // if we can do this here because lambdas keep return statements around 10557 // to deduce an implicit return type. 10558 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10559 !FD->isDependentContext()) 10560 computeNRVO(Body, getCurFunction()); 10561 } 10562 10563 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10564 "Function parsing confused"); 10565 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10566 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10567 MD->setBody(Body); 10568 if (!MD->isInvalidDecl()) { 10569 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10570 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10571 MD->getReturnType(), MD); 10572 10573 if (Body) 10574 computeNRVO(Body, getCurFunction()); 10575 } 10576 if (getCurFunction()->ObjCShouldCallSuper) { 10577 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10578 << MD->getSelector().getAsString(); 10579 getCurFunction()->ObjCShouldCallSuper = false; 10580 } 10581 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10582 const ObjCMethodDecl *InitMethod = nullptr; 10583 bool isDesignated = 10584 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10585 assert(isDesignated && InitMethod); 10586 (void)isDesignated; 10587 10588 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10589 auto IFace = MD->getClassInterface(); 10590 if (!IFace) 10591 return false; 10592 auto SuperD = IFace->getSuperClass(); 10593 if (!SuperD) 10594 return false; 10595 return SuperD->getIdentifier() == 10596 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10597 }; 10598 // Don't issue this warning for unavailable inits or direct subclasses 10599 // of NSObject. 10600 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10601 Diag(MD->getLocation(), 10602 diag::warn_objc_designated_init_missing_super_call); 10603 Diag(InitMethod->getLocation(), 10604 diag::note_objc_designated_init_marked_here); 10605 } 10606 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10607 } 10608 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10609 // Don't issue this warning for unavaialable inits. 10610 if (!MD->isUnavailable()) 10611 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 10612 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10613 } 10614 } else { 10615 return nullptr; 10616 } 10617 10618 assert(!getCurFunction()->ObjCShouldCallSuper && 10619 "This should only be set for ObjC methods, which should have been " 10620 "handled in the block above."); 10621 10622 // Verify and clean out per-function state. 10623 if (Body) { 10624 // C++ constructors that have function-try-blocks can't have return 10625 // statements in the handlers of that block. (C++ [except.handle]p14) 10626 // Verify this. 10627 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10628 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10629 10630 // Verify that gotos and switch cases don't jump into scopes illegally. 10631 if (getCurFunction()->NeedsScopeChecking() && 10632 !PP.isCodeCompletionEnabled()) 10633 DiagnoseInvalidJumps(Body); 10634 10635 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10636 if (!Destructor->getParent()->isDependentType()) 10637 CheckDestructor(Destructor); 10638 10639 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10640 Destructor->getParent()); 10641 } 10642 10643 // If any errors have occurred, clear out any temporaries that may have 10644 // been leftover. This ensures that these temporaries won't be picked up for 10645 // deletion in some later function. 10646 if (getDiagnostics().hasErrorOccurred() || 10647 getDiagnostics().getSuppressAllDiagnostics()) { 10648 DiscardCleanupsInEvaluationContext(); 10649 } 10650 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10651 !isa<FunctionTemplateDecl>(dcl)) { 10652 // Since the body is valid, issue any analysis-based warnings that are 10653 // enabled. 10654 ActivePolicy = &WP; 10655 } 10656 10657 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10658 (!CheckConstexprFunctionDecl(FD) || 10659 !CheckConstexprFunctionBody(FD, Body))) 10660 FD->setInvalidDecl(); 10661 10662 if (FD && FD->hasAttr<NakedAttr>()) { 10663 for (const Stmt *S : Body->children()) { 10664 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 10665 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 10666 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 10667 FD->setInvalidDecl(); 10668 break; 10669 } 10670 } 10671 } 10672 10673 assert(ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects 10674 && "Leftover temporaries in function"); 10675 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10676 assert(MaybeODRUseExprs.empty() && 10677 "Leftover expressions for odr-use checking"); 10678 } 10679 10680 if (!IsInstantiation) 10681 PopDeclContext(); 10682 10683 PopFunctionScopeInfo(ActivePolicy, dcl); 10684 // If any errors have occurred, clear out any temporaries that may have 10685 // been leftover. This ensures that these temporaries won't be picked up for 10686 // deletion in some later function. 10687 if (getDiagnostics().hasErrorOccurred()) { 10688 DiscardCleanupsInEvaluationContext(); 10689 } 10690 10691 return dcl; 10692 } 10693 10694 10695 /// When we finish delayed parsing of an attribute, we must attach it to the 10696 /// relevant Decl. 10697 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10698 ParsedAttributes &Attrs) { 10699 // Always attach attributes to the underlying decl. 10700 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10701 D = TD->getTemplatedDecl(); 10702 ProcessDeclAttributeList(S, D, Attrs.getList()); 10703 10704 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10705 if (Method->isStatic()) 10706 checkThisInStaticMemberFunctionAttributes(Method); 10707 } 10708 10709 10710 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10711 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10712 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10713 IdentifierInfo &II, Scope *S) { 10714 // Before we produce a declaration for an implicitly defined 10715 // function, see whether there was a locally-scoped declaration of 10716 // this name as a function or variable. If so, use that 10717 // (non-visible) declaration, and complain about it. 10718 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10719 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10720 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10721 return ExternCPrev; 10722 } 10723 10724 // Extension in C99. Legal in C90, but warn about it. 10725 unsigned diag_id; 10726 if (II.getName().startswith("__builtin_")) 10727 diag_id = diag::warn_builtin_unknown; 10728 else if (getLangOpts().C99) 10729 diag_id = diag::ext_implicit_function_decl; 10730 else 10731 diag_id = diag::warn_implicit_function_decl; 10732 Diag(Loc, diag_id) << &II; 10733 10734 // Because typo correction is expensive, only do it if the implicit 10735 // function declaration is going to be treated as an error. 10736 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10737 TypoCorrection Corrected; 10738 if (S && 10739 (Corrected = CorrectTypo( 10740 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 10741 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 10742 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10743 /*ErrorRecovery*/false); 10744 } 10745 10746 // Set a Declarator for the implicit definition: int foo(); 10747 const char *Dummy; 10748 AttributeFactory attrFactory; 10749 DeclSpec DS(attrFactory); 10750 unsigned DiagID; 10751 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10752 Context.getPrintingPolicy()); 10753 (void)Error; // Silence warning. 10754 assert(!Error && "Error setting up implicit decl!"); 10755 SourceLocation NoLoc; 10756 Declarator D(DS, Declarator::BlockContext); 10757 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10758 /*IsAmbiguous=*/false, 10759 /*LParenLoc=*/NoLoc, 10760 /*Params=*/nullptr, 10761 /*NumParams=*/0, 10762 /*EllipsisLoc=*/NoLoc, 10763 /*RParenLoc=*/NoLoc, 10764 /*TypeQuals=*/0, 10765 /*RefQualifierIsLvalueRef=*/true, 10766 /*RefQualifierLoc=*/NoLoc, 10767 /*ConstQualifierLoc=*/NoLoc, 10768 /*VolatileQualifierLoc=*/NoLoc, 10769 /*RestrictQualifierLoc=*/NoLoc, 10770 /*MutableLoc=*/NoLoc, 10771 EST_None, 10772 /*ESpecLoc=*/NoLoc, 10773 /*Exceptions=*/nullptr, 10774 /*ExceptionRanges=*/nullptr, 10775 /*NumExceptions=*/0, 10776 /*NoexceptExpr=*/nullptr, 10777 /*ExceptionSpecTokens=*/nullptr, 10778 Loc, Loc, D), 10779 DS.getAttributes(), 10780 SourceLocation()); 10781 D.SetIdentifier(&II, Loc); 10782 10783 // Insert this function into translation-unit scope. 10784 10785 DeclContext *PrevDC = CurContext; 10786 CurContext = Context.getTranslationUnitDecl(); 10787 10788 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10789 FD->setImplicit(); 10790 10791 CurContext = PrevDC; 10792 10793 AddKnownFunctionAttributes(FD); 10794 10795 return FD; 10796 } 10797 10798 /// \brief Adds any function attributes that we know a priori based on 10799 /// the declaration of this function. 10800 /// 10801 /// These attributes can apply both to implicitly-declared builtins 10802 /// (like __builtin___printf_chk) or to library-declared functions 10803 /// like NSLog or printf. 10804 /// 10805 /// We need to check for duplicate attributes both here and where user-written 10806 /// attributes are applied to declarations. 10807 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10808 if (FD->isInvalidDecl()) 10809 return; 10810 10811 // If this is a built-in function, map its builtin attributes to 10812 // actual attributes. 10813 if (unsigned BuiltinID = FD->getBuiltinID()) { 10814 // Handle printf-formatting attributes. 10815 unsigned FormatIdx; 10816 bool HasVAListArg; 10817 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10818 if (!FD->hasAttr<FormatAttr>()) { 10819 const char *fmt = "printf"; 10820 unsigned int NumParams = FD->getNumParams(); 10821 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10822 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10823 fmt = "NSString"; 10824 FD->addAttr(FormatAttr::CreateImplicit(Context, 10825 &Context.Idents.get(fmt), 10826 FormatIdx+1, 10827 HasVAListArg ? 0 : FormatIdx+2, 10828 FD->getLocation())); 10829 } 10830 } 10831 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10832 HasVAListArg)) { 10833 if (!FD->hasAttr<FormatAttr>()) 10834 FD->addAttr(FormatAttr::CreateImplicit(Context, 10835 &Context.Idents.get("scanf"), 10836 FormatIdx+1, 10837 HasVAListArg ? 0 : FormatIdx+2, 10838 FD->getLocation())); 10839 } 10840 10841 // Mark const if we don't care about errno and that is the only 10842 // thing preventing the function from being const. This allows 10843 // IRgen to use LLVM intrinsics for such functions. 10844 if (!getLangOpts().MathErrno && 10845 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10846 if (!FD->hasAttr<ConstAttr>()) 10847 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10848 } 10849 10850 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10851 !FD->hasAttr<ReturnsTwiceAttr>()) 10852 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10853 FD->getLocation())); 10854 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10855 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10856 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10857 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10858 } 10859 10860 IdentifierInfo *Name = FD->getIdentifier(); 10861 if (!Name) 10862 return; 10863 if ((!getLangOpts().CPlusPlus && 10864 FD->getDeclContext()->isTranslationUnit()) || 10865 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10866 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10867 LinkageSpecDecl::lang_c)) { 10868 // Okay: this could be a libc/libm/Objective-C function we know 10869 // about. 10870 } else 10871 return; 10872 10873 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10874 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10875 // target-specific builtins, perhaps? 10876 if (!FD->hasAttr<FormatAttr>()) 10877 FD->addAttr(FormatAttr::CreateImplicit(Context, 10878 &Context.Idents.get("printf"), 2, 10879 Name->isStr("vasprintf") ? 0 : 3, 10880 FD->getLocation())); 10881 } 10882 10883 if (Name->isStr("__CFStringMakeConstantString")) { 10884 // We already have a __builtin___CFStringMakeConstantString, 10885 // but builds that use -fno-constant-cfstrings don't go through that. 10886 if (!FD->hasAttr<FormatArgAttr>()) 10887 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10888 FD->getLocation())); 10889 } 10890 } 10891 10892 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10893 TypeSourceInfo *TInfo) { 10894 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10895 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10896 10897 if (!TInfo) { 10898 assert(D.isInvalidType() && "no declarator info for valid type"); 10899 TInfo = Context.getTrivialTypeSourceInfo(T); 10900 } 10901 10902 // Scope manipulation handled by caller. 10903 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10904 D.getLocStart(), 10905 D.getIdentifierLoc(), 10906 D.getIdentifier(), 10907 TInfo); 10908 10909 // Bail out immediately if we have an invalid declaration. 10910 if (D.isInvalidType()) { 10911 NewTD->setInvalidDecl(); 10912 return NewTD; 10913 } 10914 10915 if (D.getDeclSpec().isModulePrivateSpecified()) { 10916 if (CurContext->isFunctionOrMethod()) 10917 Diag(NewTD->getLocation(), diag::err_module_private_local) 10918 << 2 << NewTD->getDeclName() 10919 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10920 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10921 else 10922 NewTD->setModulePrivate(); 10923 } 10924 10925 // C++ [dcl.typedef]p8: 10926 // If the typedef declaration defines an unnamed class (or 10927 // enum), the first typedef-name declared by the declaration 10928 // to be that class type (or enum type) is used to denote the 10929 // class type (or enum type) for linkage purposes only. 10930 // We need to check whether the type was declared in the declaration. 10931 switch (D.getDeclSpec().getTypeSpecType()) { 10932 case TST_enum: 10933 case TST_struct: 10934 case TST_interface: 10935 case TST_union: 10936 case TST_class: { 10937 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10938 10939 // Do nothing if the tag is not anonymous or already has an 10940 // associated typedef (from an earlier typedef in this decl group). 10941 if (tagFromDeclSpec->getIdentifier()) break; 10942 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10943 10944 // A well-formed anonymous tag must always be a TUK_Definition. 10945 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10946 10947 // The type must match the tag exactly; no qualifiers allowed. 10948 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10949 break; 10950 10951 // If we've already computed linkage for the anonymous tag, then 10952 // adding a typedef name for the anonymous decl can change that 10953 // linkage, which might be a serious problem. Diagnose this as 10954 // unsupported and ignore the typedef name. TODO: we should 10955 // pursue this as a language defect and establish a formal rule 10956 // for how to handle it. 10957 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10958 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10959 10960 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10961 tagLoc = getLocForEndOfToken(tagLoc); 10962 10963 llvm::SmallString<40> textToInsert; 10964 textToInsert += ' '; 10965 textToInsert += D.getIdentifier()->getName(); 10966 Diag(tagLoc, diag::note_typedef_changes_linkage) 10967 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10968 break; 10969 } 10970 10971 // Otherwise, set this is the anon-decl typedef for the tag. 10972 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10973 break; 10974 } 10975 10976 default: 10977 break; 10978 } 10979 10980 return NewTD; 10981 } 10982 10983 10984 /// \brief Check that this is a valid underlying type for an enum declaration. 10985 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10986 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10987 QualType T = TI->getType(); 10988 10989 if (T->isDependentType()) 10990 return false; 10991 10992 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10993 if (BT->isInteger()) 10994 return false; 10995 10996 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10997 return true; 10998 } 10999 11000 /// Check whether this is a valid redeclaration of a previous enumeration. 11001 /// \return true if the redeclaration was invalid. 11002 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 11003 QualType EnumUnderlyingTy, 11004 const EnumDecl *Prev) { 11005 bool IsFixed = !EnumUnderlyingTy.isNull(); 11006 11007 if (IsScoped != Prev->isScoped()) { 11008 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 11009 << Prev->isScoped(); 11010 Diag(Prev->getLocation(), diag::note_previous_declaration); 11011 return true; 11012 } 11013 11014 if (IsFixed && Prev->isFixed()) { 11015 if (!EnumUnderlyingTy->isDependentType() && 11016 !Prev->getIntegerType()->isDependentType() && 11017 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 11018 Prev->getIntegerType())) { 11019 // TODO: Highlight the underlying type of the redeclaration. 11020 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 11021 << EnumUnderlyingTy << Prev->getIntegerType(); 11022 Diag(Prev->getLocation(), diag::note_previous_declaration) 11023 << Prev->getIntegerTypeRange(); 11024 return true; 11025 } 11026 } else if (IsFixed != Prev->isFixed()) { 11027 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 11028 << Prev->isFixed(); 11029 Diag(Prev->getLocation(), diag::note_previous_declaration); 11030 return true; 11031 } 11032 11033 return false; 11034 } 11035 11036 /// \brief Get diagnostic %select index for tag kind for 11037 /// redeclaration diagnostic message. 11038 /// WARNING: Indexes apply to particular diagnostics only! 11039 /// 11040 /// \returns diagnostic %select index. 11041 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 11042 switch (Tag) { 11043 case TTK_Struct: return 0; 11044 case TTK_Interface: return 1; 11045 case TTK_Class: return 2; 11046 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 11047 } 11048 } 11049 11050 /// \brief Determine if tag kind is a class-key compatible with 11051 /// class for redeclaration (class, struct, or __interface). 11052 /// 11053 /// \returns true iff the tag kind is compatible. 11054 static bool isClassCompatTagKind(TagTypeKind Tag) 11055 { 11056 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 11057 } 11058 11059 /// \brief Determine whether a tag with a given kind is acceptable 11060 /// as a redeclaration of the given tag declaration. 11061 /// 11062 /// \returns true if the new tag kind is acceptable, false otherwise. 11063 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 11064 TagTypeKind NewTag, bool isDefinition, 11065 SourceLocation NewTagLoc, 11066 const IdentifierInfo &Name) { 11067 // C++ [dcl.type.elab]p3: 11068 // The class-key or enum keyword present in the 11069 // elaborated-type-specifier shall agree in kind with the 11070 // declaration to which the name in the elaborated-type-specifier 11071 // refers. This rule also applies to the form of 11072 // elaborated-type-specifier that declares a class-name or 11073 // friend class since it can be construed as referring to the 11074 // definition of the class. Thus, in any 11075 // elaborated-type-specifier, the enum keyword shall be used to 11076 // refer to an enumeration (7.2), the union class-key shall be 11077 // used to refer to a union (clause 9), and either the class or 11078 // struct class-key shall be used to refer to a class (clause 9) 11079 // declared using the class or struct class-key. 11080 TagTypeKind OldTag = Previous->getTagKind(); 11081 if (!isDefinition || !isClassCompatTagKind(NewTag)) 11082 if (OldTag == NewTag) 11083 return true; 11084 11085 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 11086 // Warn about the struct/class tag mismatch. 11087 bool isTemplate = false; 11088 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 11089 isTemplate = Record->getDescribedClassTemplate(); 11090 11091 if (!ActiveTemplateInstantiations.empty()) { 11092 // In a template instantiation, do not offer fix-its for tag mismatches 11093 // since they usually mess up the template instead of fixing the problem. 11094 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11095 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11096 << getRedeclDiagFromTagKind(OldTag); 11097 return true; 11098 } 11099 11100 if (isDefinition) { 11101 // On definitions, check previous tags and issue a fix-it for each 11102 // one that doesn't match the current tag. 11103 if (Previous->getDefinition()) { 11104 // Don't suggest fix-its for redefinitions. 11105 return true; 11106 } 11107 11108 bool previousMismatch = false; 11109 for (auto I : Previous->redecls()) { 11110 if (I->getTagKind() != NewTag) { 11111 if (!previousMismatch) { 11112 previousMismatch = true; 11113 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11114 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11115 << getRedeclDiagFromTagKind(I->getTagKind()); 11116 } 11117 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11118 << getRedeclDiagFromTagKind(NewTag) 11119 << FixItHint::CreateReplacement(I->getInnerLocStart(), 11120 TypeWithKeyword::getTagTypeKindName(NewTag)); 11121 } 11122 } 11123 return true; 11124 } 11125 11126 // Check for a previous definition. If current tag and definition 11127 // are same type, do nothing. If no definition, but disagree with 11128 // with previous tag type, give a warning, but no fix-it. 11129 const TagDecl *Redecl = Previous->getDefinition() ? 11130 Previous->getDefinition() : Previous; 11131 if (Redecl->getTagKind() == NewTag) { 11132 return true; 11133 } 11134 11135 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11136 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11137 << getRedeclDiagFromTagKind(OldTag); 11138 Diag(Redecl->getLocation(), diag::note_previous_use); 11139 11140 // If there is a previous definition, suggest a fix-it. 11141 if (Previous->getDefinition()) { 11142 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11143 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11144 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11145 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11146 } 11147 11148 return true; 11149 } 11150 return false; 11151 } 11152 11153 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11154 /// from an outer enclosing namespace or file scope inside a friend declaration. 11155 /// This should provide the commented out code in the following snippet: 11156 /// namespace N { 11157 /// struct X; 11158 /// namespace M { 11159 /// struct Y { friend struct /*N::*/ X; }; 11160 /// } 11161 /// } 11162 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11163 SourceLocation NameLoc) { 11164 // While the decl is in a namespace, do repeated lookup of that name and see 11165 // if we get the same namespace back. If we do not, continue until 11166 // translation unit scope, at which point we have a fully qualified NNS. 11167 SmallVector<IdentifierInfo *, 4> Namespaces; 11168 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11169 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11170 // This tag should be declared in a namespace, which can only be enclosed by 11171 // other namespaces. Bail if there's an anonymous namespace in the chain. 11172 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11173 if (!Namespace || Namespace->isAnonymousNamespace()) 11174 return FixItHint(); 11175 IdentifierInfo *II = Namespace->getIdentifier(); 11176 Namespaces.push_back(II); 11177 NamedDecl *Lookup = SemaRef.LookupSingleName( 11178 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11179 if (Lookup == Namespace) 11180 break; 11181 } 11182 11183 // Once we have all the namespaces, reverse them to go outermost first, and 11184 // build an NNS. 11185 SmallString<64> Insertion; 11186 llvm::raw_svector_ostream OS(Insertion); 11187 if (DC->isTranslationUnit()) 11188 OS << "::"; 11189 std::reverse(Namespaces.begin(), Namespaces.end()); 11190 for (auto *II : Namespaces) 11191 OS << II->getName() << "::"; 11192 OS.flush(); 11193 return FixItHint::CreateInsertion(NameLoc, Insertion); 11194 } 11195 11196 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 11197 /// former case, Name will be non-null. In the later case, Name will be null. 11198 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11199 /// reference/declaration/definition of a tag. 11200 /// 11201 /// IsTypeSpecifier is true if this is a type-specifier (or 11202 /// trailing-type-specifier) other than one in an alias-declaration. 11203 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11204 SourceLocation KWLoc, CXXScopeSpec &SS, 11205 IdentifierInfo *Name, SourceLocation NameLoc, 11206 AttributeList *Attr, AccessSpecifier AS, 11207 SourceLocation ModulePrivateLoc, 11208 MultiTemplateParamsArg TemplateParameterLists, 11209 bool &OwnedDecl, bool &IsDependent, 11210 SourceLocation ScopedEnumKWLoc, 11211 bool ScopedEnumUsesClassTag, 11212 TypeResult UnderlyingType, 11213 bool IsTypeSpecifier) { 11214 // If this is not a definition, it must have a name. 11215 IdentifierInfo *OrigName = Name; 11216 assert((Name != nullptr || TUK == TUK_Definition) && 11217 "Nameless record must be a definition!"); 11218 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11219 11220 OwnedDecl = false; 11221 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11222 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11223 11224 // FIXME: Check explicit specializations more carefully. 11225 bool isExplicitSpecialization = false; 11226 bool Invalid = false; 11227 11228 // We only need to do this matching if we have template parameters 11229 // or a scope specifier, which also conveniently avoids this work 11230 // for non-C++ cases. 11231 if (TemplateParameterLists.size() > 0 || 11232 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11233 if (TemplateParameterList *TemplateParams = 11234 MatchTemplateParametersToScopeSpecifier( 11235 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11236 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11237 if (Kind == TTK_Enum) { 11238 Diag(KWLoc, diag::err_enum_template); 11239 return nullptr; 11240 } 11241 11242 if (TemplateParams->size() > 0) { 11243 // This is a declaration or definition of a class template (which may 11244 // be a member of another template). 11245 11246 if (Invalid) 11247 return nullptr; 11248 11249 OwnedDecl = false; 11250 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11251 SS, Name, NameLoc, Attr, 11252 TemplateParams, AS, 11253 ModulePrivateLoc, 11254 /*FriendLoc*/SourceLocation(), 11255 TemplateParameterLists.size()-1, 11256 TemplateParameterLists.data()); 11257 return Result.get(); 11258 } else { 11259 // The "template<>" header is extraneous. 11260 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11261 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11262 isExplicitSpecialization = true; 11263 } 11264 } 11265 } 11266 11267 // Figure out the underlying type if this a enum declaration. We need to do 11268 // this early, because it's needed to detect if this is an incompatible 11269 // redeclaration. 11270 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 11271 11272 if (Kind == TTK_Enum) { 11273 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 11274 // No underlying type explicitly specified, or we failed to parse the 11275 // type, default to int. 11276 EnumUnderlying = Context.IntTy.getTypePtr(); 11277 else if (UnderlyingType.get()) { 11278 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 11279 // integral type; any cv-qualification is ignored. 11280 TypeSourceInfo *TI = nullptr; 11281 GetTypeFromParser(UnderlyingType.get(), &TI); 11282 EnumUnderlying = TI; 11283 11284 if (CheckEnumUnderlyingType(TI)) 11285 // Recover by falling back to int. 11286 EnumUnderlying = Context.IntTy.getTypePtr(); 11287 11288 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 11289 UPPC_FixedUnderlyingType)) 11290 EnumUnderlying = Context.IntTy.getTypePtr(); 11291 11292 } else if (getLangOpts().MSVCCompat) 11293 // Microsoft enums are always of int type. 11294 EnumUnderlying = Context.IntTy.getTypePtr(); 11295 } 11296 11297 DeclContext *SearchDC = CurContext; 11298 DeclContext *DC = CurContext; 11299 bool isStdBadAlloc = false; 11300 11301 RedeclarationKind Redecl = ForRedeclaration; 11302 if (TUK == TUK_Friend || TUK == TUK_Reference) 11303 Redecl = NotForRedeclaration; 11304 11305 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 11306 if (Name && SS.isNotEmpty()) { 11307 // We have a nested-name tag ('struct foo::bar'). 11308 11309 // Check for invalid 'foo::'. 11310 if (SS.isInvalid()) { 11311 Name = nullptr; 11312 goto CreateNewDecl; 11313 } 11314 11315 // If this is a friend or a reference to a class in a dependent 11316 // context, don't try to make a decl for it. 11317 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11318 DC = computeDeclContext(SS, false); 11319 if (!DC) { 11320 IsDependent = true; 11321 return nullptr; 11322 } 11323 } else { 11324 DC = computeDeclContext(SS, true); 11325 if (!DC) { 11326 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 11327 << SS.getRange(); 11328 return nullptr; 11329 } 11330 } 11331 11332 if (RequireCompleteDeclContext(SS, DC)) 11333 return nullptr; 11334 11335 SearchDC = DC; 11336 // Look-up name inside 'foo::'. 11337 LookupQualifiedName(Previous, DC); 11338 11339 if (Previous.isAmbiguous()) 11340 return nullptr; 11341 11342 if (Previous.empty()) { 11343 // Name lookup did not find anything. However, if the 11344 // nested-name-specifier refers to the current instantiation, 11345 // and that current instantiation has any dependent base 11346 // classes, we might find something at instantiation time: treat 11347 // this as a dependent elaborated-type-specifier. 11348 // But this only makes any sense for reference-like lookups. 11349 if (Previous.wasNotFoundInCurrentInstantiation() && 11350 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11351 IsDependent = true; 11352 return nullptr; 11353 } 11354 11355 // A tag 'foo::bar' must already exist. 11356 Diag(NameLoc, diag::err_not_tag_in_scope) 11357 << Kind << Name << DC << SS.getRange(); 11358 Name = nullptr; 11359 Invalid = true; 11360 goto CreateNewDecl; 11361 } 11362 } else if (Name) { 11363 // If this is a named struct, check to see if there was a previous forward 11364 // declaration or definition. 11365 // FIXME: We're looking into outer scopes here, even when we 11366 // shouldn't be. Doing so can result in ambiguities that we 11367 // shouldn't be diagnosing. 11368 LookupName(Previous, S); 11369 11370 // When declaring or defining a tag, ignore ambiguities introduced 11371 // by types using'ed into this scope. 11372 if (Previous.isAmbiguous() && 11373 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 11374 LookupResult::Filter F = Previous.makeFilter(); 11375 while (F.hasNext()) { 11376 NamedDecl *ND = F.next(); 11377 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 11378 F.erase(); 11379 } 11380 F.done(); 11381 } 11382 11383 // C++11 [namespace.memdef]p3: 11384 // If the name in a friend declaration is neither qualified nor 11385 // a template-id and the declaration is a function or an 11386 // elaborated-type-specifier, the lookup to determine whether 11387 // the entity has been previously declared shall not consider 11388 // any scopes outside the innermost enclosing namespace. 11389 // 11390 // MSVC doesn't implement the above rule for types, so a friend tag 11391 // declaration may be a redeclaration of a type declared in an enclosing 11392 // scope. They do implement this rule for friend functions. 11393 // 11394 // Does it matter that this should be by scope instead of by 11395 // semantic context? 11396 if (!Previous.empty() && TUK == TUK_Friend) { 11397 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 11398 LookupResult::Filter F = Previous.makeFilter(); 11399 bool FriendSawTagOutsideEnclosingNamespace = false; 11400 while (F.hasNext()) { 11401 NamedDecl *ND = F.next(); 11402 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11403 if (DC->isFileContext() && 11404 !EnclosingNS->Encloses(ND->getDeclContext())) { 11405 if (getLangOpts().MSVCCompat) 11406 FriendSawTagOutsideEnclosingNamespace = true; 11407 else 11408 F.erase(); 11409 } 11410 } 11411 F.done(); 11412 11413 // Diagnose this MSVC extension in the easy case where lookup would have 11414 // unambiguously found something outside the enclosing namespace. 11415 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 11416 NamedDecl *ND = Previous.getFoundDecl(); 11417 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 11418 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 11419 } 11420 } 11421 11422 // Note: there used to be some attempt at recovery here. 11423 if (Previous.isAmbiguous()) 11424 return nullptr; 11425 11426 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 11427 // FIXME: This makes sure that we ignore the contexts associated 11428 // with C structs, unions, and enums when looking for a matching 11429 // tag declaration or definition. See the similar lookup tweak 11430 // in Sema::LookupName; is there a better way to deal with this? 11431 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 11432 SearchDC = SearchDC->getParent(); 11433 } 11434 } 11435 11436 if (Previous.isSingleResult() && 11437 Previous.getFoundDecl()->isTemplateParameter()) { 11438 // Maybe we will complain about the shadowed template parameter. 11439 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 11440 // Just pretend that we didn't see the previous declaration. 11441 Previous.clear(); 11442 } 11443 11444 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 11445 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 11446 // This is a declaration of or a reference to "std::bad_alloc". 11447 isStdBadAlloc = true; 11448 11449 if (Previous.empty() && StdBadAlloc) { 11450 // std::bad_alloc has been implicitly declared (but made invisible to 11451 // name lookup). Fill in this implicit declaration as the previous 11452 // declaration, so that the declarations get chained appropriately. 11453 Previous.addDecl(getStdBadAlloc()); 11454 } 11455 } 11456 11457 // If we didn't find a previous declaration, and this is a reference 11458 // (or friend reference), move to the correct scope. In C++, we 11459 // also need to do a redeclaration lookup there, just in case 11460 // there's a shadow friend decl. 11461 if (Name && Previous.empty() && 11462 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11463 if (Invalid) goto CreateNewDecl; 11464 assert(SS.isEmpty()); 11465 11466 if (TUK == TUK_Reference) { 11467 // C++ [basic.scope.pdecl]p5: 11468 // -- for an elaborated-type-specifier of the form 11469 // 11470 // class-key identifier 11471 // 11472 // if the elaborated-type-specifier is used in the 11473 // decl-specifier-seq or parameter-declaration-clause of a 11474 // function defined in namespace scope, the identifier is 11475 // declared as a class-name in the namespace that contains 11476 // the declaration; otherwise, except as a friend 11477 // declaration, the identifier is declared in the smallest 11478 // non-class, non-function-prototype scope that contains the 11479 // declaration. 11480 // 11481 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 11482 // C structs and unions. 11483 // 11484 // It is an error in C++ to declare (rather than define) an enum 11485 // type, including via an elaborated type specifier. We'll 11486 // diagnose that later; for now, declare the enum in the same 11487 // scope as we would have picked for any other tag type. 11488 // 11489 // GNU C also supports this behavior as part of its incomplete 11490 // enum types extension, while GNU C++ does not. 11491 // 11492 // Find the context where we'll be declaring the tag. 11493 // FIXME: We would like to maintain the current DeclContext as the 11494 // lexical context, 11495 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 11496 SearchDC = SearchDC->getParent(); 11497 11498 // Find the scope where we'll be declaring the tag. 11499 while (S->isClassScope() || 11500 (getLangOpts().CPlusPlus && 11501 S->isFunctionPrototypeScope()) || 11502 ((S->getFlags() & Scope::DeclScope) == 0) || 11503 (S->getEntity() && S->getEntity()->isTransparentContext())) 11504 S = S->getParent(); 11505 } else { 11506 assert(TUK == TUK_Friend); 11507 // C++ [namespace.memdef]p3: 11508 // If a friend declaration in a non-local class first declares a 11509 // class or function, the friend class or function is a member of 11510 // the innermost enclosing namespace. 11511 SearchDC = SearchDC->getEnclosingNamespaceContext(); 11512 } 11513 11514 // In C++, we need to do a redeclaration lookup to properly 11515 // diagnose some problems. 11516 if (getLangOpts().CPlusPlus) { 11517 Previous.setRedeclarationKind(ForRedeclaration); 11518 LookupQualifiedName(Previous, SearchDC); 11519 } 11520 } 11521 11522 if (!Previous.empty()) { 11523 NamedDecl *PrevDecl = Previous.getFoundDecl(); 11524 NamedDecl *DirectPrevDecl = 11525 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 11526 11527 // It's okay to have a tag decl in the same scope as a typedef 11528 // which hides a tag decl in the same scope. Finding this 11529 // insanity with a redeclaration lookup can only actually happen 11530 // in C++. 11531 // 11532 // This is also okay for elaborated-type-specifiers, which is 11533 // technically forbidden by the current standard but which is 11534 // okay according to the likely resolution of an open issue; 11535 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 11536 if (getLangOpts().CPlusPlus) { 11537 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11538 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 11539 TagDecl *Tag = TT->getDecl(); 11540 if (Tag->getDeclName() == Name && 11541 Tag->getDeclContext()->getRedeclContext() 11542 ->Equals(TD->getDeclContext()->getRedeclContext())) { 11543 PrevDecl = Tag; 11544 Previous.clear(); 11545 Previous.addDecl(Tag); 11546 Previous.resolveKind(); 11547 } 11548 } 11549 } 11550 } 11551 11552 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 11553 // If this is a use of a previous tag, or if the tag is already declared 11554 // in the same scope (so that the definition/declaration completes or 11555 // rementions the tag), reuse the decl. 11556 if (TUK == TUK_Reference || TUK == TUK_Friend || 11557 isDeclInScope(DirectPrevDecl, SearchDC, S, 11558 SS.isNotEmpty() || isExplicitSpecialization)) { 11559 // Make sure that this wasn't declared as an enum and now used as a 11560 // struct or something similar. 11561 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 11562 TUK == TUK_Definition, KWLoc, 11563 *Name)) { 11564 bool SafeToContinue 11565 = (PrevTagDecl->getTagKind() != TTK_Enum && 11566 Kind != TTK_Enum); 11567 if (SafeToContinue) 11568 Diag(KWLoc, diag::err_use_with_wrong_tag) 11569 << Name 11570 << FixItHint::CreateReplacement(SourceRange(KWLoc), 11571 PrevTagDecl->getKindName()); 11572 else 11573 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 11574 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 11575 11576 if (SafeToContinue) 11577 Kind = PrevTagDecl->getTagKind(); 11578 else { 11579 // Recover by making this an anonymous redefinition. 11580 Name = nullptr; 11581 Previous.clear(); 11582 Invalid = true; 11583 } 11584 } 11585 11586 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 11587 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 11588 11589 // If this is an elaborated-type-specifier for a scoped enumeration, 11590 // the 'class' keyword is not necessary and not permitted. 11591 if (TUK == TUK_Reference || TUK == TUK_Friend) { 11592 if (ScopedEnum) 11593 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 11594 << PrevEnum->isScoped() 11595 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 11596 return PrevTagDecl; 11597 } 11598 11599 QualType EnumUnderlyingTy; 11600 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11601 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 11602 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 11603 EnumUnderlyingTy = QualType(T, 0); 11604 11605 // All conflicts with previous declarations are recovered by 11606 // returning the previous declaration, unless this is a definition, 11607 // in which case we want the caller to bail out. 11608 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11609 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11610 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11611 } 11612 11613 // C++11 [class.mem]p1: 11614 // A member shall not be declared twice in the member-specification, 11615 // except that a nested class or member class template can be declared 11616 // and then later defined. 11617 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11618 S->isDeclScope(PrevDecl)) { 11619 Diag(NameLoc, diag::ext_member_redeclared); 11620 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11621 } 11622 11623 if (!Invalid) { 11624 // If this is a use, just return the declaration we found, unless 11625 // we have attributes. 11626 11627 // FIXME: In the future, return a variant or some other clue 11628 // for the consumer of this Decl to know it doesn't own it. 11629 // For our current ASTs this shouldn't be a problem, but will 11630 // need to be changed with DeclGroups. 11631 if (!Attr && 11632 ((TUK == TUK_Reference && 11633 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11634 || TUK == TUK_Friend)) 11635 return PrevTagDecl; 11636 11637 // Diagnose attempts to redefine a tag. 11638 if (TUK == TUK_Definition) { 11639 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 11640 // If we're defining a specialization and the previous definition 11641 // is from an implicit instantiation, don't emit an error 11642 // here; we'll catch this in the general case below. 11643 bool IsExplicitSpecializationAfterInstantiation = false; 11644 if (isExplicitSpecialization) { 11645 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11646 IsExplicitSpecializationAfterInstantiation = 11647 RD->getTemplateSpecializationKind() != 11648 TSK_ExplicitSpecialization; 11649 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11650 IsExplicitSpecializationAfterInstantiation = 11651 ED->getTemplateSpecializationKind() != 11652 TSK_ExplicitSpecialization; 11653 } 11654 11655 if (!IsExplicitSpecializationAfterInstantiation) { 11656 // A redeclaration in function prototype scope in C isn't 11657 // visible elsewhere, so merely issue a warning. 11658 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11659 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11660 else 11661 Diag(NameLoc, diag::err_redefinition) << Name; 11662 Diag(Def->getLocation(), diag::note_previous_definition); 11663 // If this is a redefinition, recover by making this 11664 // struct be anonymous, which will make any later 11665 // references get the previous definition. 11666 Name = nullptr; 11667 Previous.clear(); 11668 Invalid = true; 11669 } 11670 } else { 11671 // If the type is currently being defined, complain 11672 // about a nested redefinition. 11673 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 11674 if (TD->isBeingDefined()) { 11675 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11676 Diag(PrevTagDecl->getLocation(), 11677 diag::note_previous_definition); 11678 Name = nullptr; 11679 Previous.clear(); 11680 Invalid = true; 11681 } 11682 } 11683 11684 // Okay, this is definition of a previously declared or referenced 11685 // tag. We're going to create a new Decl for it. 11686 } 11687 11688 // Okay, we're going to make a redeclaration. If this is some kind 11689 // of reference, make sure we build the redeclaration in the same DC 11690 // as the original, and ignore the current access specifier. 11691 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11692 SearchDC = PrevTagDecl->getDeclContext(); 11693 AS = AS_none; 11694 } 11695 } 11696 // If we get here we have (another) forward declaration or we 11697 // have a definition. Just create a new decl. 11698 11699 } else { 11700 // If we get here, this is a definition of a new tag type in a nested 11701 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11702 // new decl/type. We set PrevDecl to NULL so that the entities 11703 // have distinct types. 11704 Previous.clear(); 11705 } 11706 // If we get here, we're going to create a new Decl. If PrevDecl 11707 // is non-NULL, it's a definition of the tag declared by 11708 // PrevDecl. If it's NULL, we have a new definition. 11709 11710 11711 // Otherwise, PrevDecl is not a tag, but was found with tag 11712 // lookup. This is only actually possible in C++, where a few 11713 // things like templates still live in the tag namespace. 11714 } else { 11715 // Use a better diagnostic if an elaborated-type-specifier 11716 // found the wrong kind of type on the first 11717 // (non-redeclaration) lookup. 11718 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11719 !Previous.isForRedeclaration()) { 11720 unsigned Kind = 0; 11721 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11722 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11723 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11724 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11725 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11726 Invalid = true; 11727 11728 // Otherwise, only diagnose if the declaration is in scope. 11729 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11730 SS.isNotEmpty() || isExplicitSpecialization)) { 11731 // do nothing 11732 11733 // Diagnose implicit declarations introduced by elaborated types. 11734 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11735 unsigned Kind = 0; 11736 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11737 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11738 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11739 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11740 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11741 Invalid = true; 11742 11743 // Otherwise it's a declaration. Call out a particularly common 11744 // case here. 11745 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11746 unsigned Kind = 0; 11747 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11748 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11749 << Name << Kind << TND->getUnderlyingType(); 11750 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11751 Invalid = true; 11752 11753 // Otherwise, diagnose. 11754 } else { 11755 // The tag name clashes with something else in the target scope, 11756 // issue an error and recover by making this tag be anonymous. 11757 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11758 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11759 Name = nullptr; 11760 Invalid = true; 11761 } 11762 11763 // The existing declaration isn't relevant to us; we're in a 11764 // new scope, so clear out the previous declaration. 11765 Previous.clear(); 11766 } 11767 } 11768 11769 CreateNewDecl: 11770 11771 TagDecl *PrevDecl = nullptr; 11772 if (Previous.isSingleResult()) 11773 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11774 11775 // If there is an identifier, use the location of the identifier as the 11776 // location of the decl, otherwise use the location of the struct/union 11777 // keyword. 11778 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11779 11780 // Otherwise, create a new declaration. If there is a previous 11781 // declaration of the same entity, the two will be linked via 11782 // PrevDecl. 11783 TagDecl *New; 11784 11785 bool IsForwardReference = false; 11786 if (Kind == TTK_Enum) { 11787 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11788 // enum X { A, B, C } D; D should chain to X. 11789 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11790 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11791 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11792 // If this is an undefined enum, warn. 11793 if (TUK != TUK_Definition && !Invalid) { 11794 TagDecl *Def; 11795 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11796 cast<EnumDecl>(New)->isFixed()) { 11797 // C++0x: 7.2p2: opaque-enum-declaration. 11798 // Conflicts are diagnosed above. Do nothing. 11799 } 11800 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11801 Diag(Loc, diag::ext_forward_ref_enum_def) 11802 << New; 11803 Diag(Def->getLocation(), diag::note_previous_definition); 11804 } else { 11805 unsigned DiagID = diag::ext_forward_ref_enum; 11806 if (getLangOpts().MSVCCompat) 11807 DiagID = diag::ext_ms_forward_ref_enum; 11808 else if (getLangOpts().CPlusPlus) 11809 DiagID = diag::err_forward_ref_enum; 11810 Diag(Loc, DiagID); 11811 11812 // If this is a forward-declared reference to an enumeration, make a 11813 // note of it; we won't actually be introducing the declaration into 11814 // the declaration context. 11815 if (TUK == TUK_Reference) 11816 IsForwardReference = true; 11817 } 11818 } 11819 11820 if (EnumUnderlying) { 11821 EnumDecl *ED = cast<EnumDecl>(New); 11822 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11823 ED->setIntegerTypeSourceInfo(TI); 11824 else 11825 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11826 ED->setPromotionType(ED->getIntegerType()); 11827 } 11828 11829 } else { 11830 // struct/union/class 11831 11832 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11833 // struct X { int A; } D; D should chain to X. 11834 if (getLangOpts().CPlusPlus) { 11835 // FIXME: Look for a way to use RecordDecl for simple structs. 11836 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11837 cast_or_null<CXXRecordDecl>(PrevDecl)); 11838 11839 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11840 StdBadAlloc = cast<CXXRecordDecl>(New); 11841 } else 11842 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11843 cast_or_null<RecordDecl>(PrevDecl)); 11844 } 11845 11846 // C++11 [dcl.type]p3: 11847 // A type-specifier-seq shall not define a class or enumeration [...]. 11848 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11849 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11850 << Context.getTagDeclType(New); 11851 Invalid = true; 11852 } 11853 11854 // Maybe add qualifier info. 11855 if (SS.isNotEmpty()) { 11856 if (SS.isSet()) { 11857 // If this is either a declaration or a definition, check the 11858 // nested-name-specifier against the current context. We don't do this 11859 // for explicit specializations, because they have similar checking 11860 // (with more specific diagnostics) in the call to 11861 // CheckMemberSpecialization, below. 11862 if (!isExplicitSpecialization && 11863 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11864 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 11865 Invalid = true; 11866 11867 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11868 if (TemplateParameterLists.size() > 0) { 11869 New->setTemplateParameterListsInfo(Context, 11870 TemplateParameterLists.size(), 11871 TemplateParameterLists.data()); 11872 } 11873 } 11874 else 11875 Invalid = true; 11876 } 11877 11878 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11879 // Add alignment attributes if necessary; these attributes are checked when 11880 // the ASTContext lays out the structure. 11881 // 11882 // It is important for implementing the correct semantics that this 11883 // happen here (in act on tag decl). The #pragma pack stack is 11884 // maintained as a result of parser callbacks which can occur at 11885 // many points during the parsing of a struct declaration (because 11886 // the #pragma tokens are effectively skipped over during the 11887 // parsing of the struct). 11888 if (TUK == TUK_Definition) { 11889 AddAlignmentAttributesForRecord(RD); 11890 AddMsStructLayoutForRecord(RD); 11891 } 11892 } 11893 11894 if (ModulePrivateLoc.isValid()) { 11895 if (isExplicitSpecialization) 11896 Diag(New->getLocation(), diag::err_module_private_specialization) 11897 << 2 11898 << FixItHint::CreateRemoval(ModulePrivateLoc); 11899 // __module_private__ does not apply to local classes. However, we only 11900 // diagnose this as an error when the declaration specifiers are 11901 // freestanding. Here, we just ignore the __module_private__. 11902 else if (!SearchDC->isFunctionOrMethod()) 11903 New->setModulePrivate(); 11904 } 11905 11906 // If this is a specialization of a member class (of a class template), 11907 // check the specialization. 11908 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11909 Invalid = true; 11910 11911 // If we're declaring or defining a tag in function prototype scope in C, 11912 // note that this type can only be used within the function and add it to 11913 // the list of decls to inject into the function definition scope. 11914 if ((Name || Kind == TTK_Enum) && 11915 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11916 if (getLangOpts().CPlusPlus) { 11917 // C++ [dcl.fct]p6: 11918 // Types shall not be defined in return or parameter types. 11919 if (TUK == TUK_Definition && !IsTypeSpecifier) { 11920 Diag(Loc, diag::err_type_defined_in_param_type) 11921 << Name; 11922 Invalid = true; 11923 } 11924 } else { 11925 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11926 } 11927 DeclsInPrototypeScope.push_back(New); 11928 } 11929 11930 if (Invalid) 11931 New->setInvalidDecl(); 11932 11933 if (Attr) 11934 ProcessDeclAttributeList(S, New, Attr); 11935 11936 // Set the lexical context. If the tag has a C++ scope specifier, the 11937 // lexical context will be different from the semantic context. 11938 New->setLexicalDeclContext(CurContext); 11939 11940 // Mark this as a friend decl if applicable. 11941 // In Microsoft mode, a friend declaration also acts as a forward 11942 // declaration so we always pass true to setObjectOfFriendDecl to make 11943 // the tag name visible. 11944 if (TUK == TUK_Friend) 11945 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 11946 11947 // Set the access specifier. 11948 if (!Invalid && SearchDC->isRecord()) 11949 SetMemberAccessSpecifier(New, PrevDecl, AS); 11950 11951 if (TUK == TUK_Definition) 11952 New->startDefinition(); 11953 11954 // If this has an identifier, add it to the scope stack. 11955 if (TUK == TUK_Friend) { 11956 // We might be replacing an existing declaration in the lookup tables; 11957 // if so, borrow its access specifier. 11958 if (PrevDecl) 11959 New->setAccess(PrevDecl->getAccess()); 11960 11961 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11962 DC->makeDeclVisibleInContext(New); 11963 if (Name) // can be null along some error paths 11964 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11965 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11966 } else if (Name) { 11967 S = getNonFieldDeclScope(S); 11968 PushOnScopeChains(New, S, !IsForwardReference); 11969 if (IsForwardReference) 11970 SearchDC->makeDeclVisibleInContext(New); 11971 11972 } else { 11973 CurContext->addDecl(New); 11974 } 11975 11976 // If this is the C FILE type, notify the AST context. 11977 if (IdentifierInfo *II = New->getIdentifier()) 11978 if (!New->isInvalidDecl() && 11979 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11980 II->isStr("FILE")) 11981 Context.setFILEDecl(New); 11982 11983 if (PrevDecl) 11984 mergeDeclAttributes(New, PrevDecl); 11985 11986 // If there's a #pragma GCC visibility in scope, set the visibility of this 11987 // record. 11988 AddPushedVisibilityAttribute(New); 11989 11990 OwnedDecl = true; 11991 // In C++, don't return an invalid declaration. We can't recover well from 11992 // the cases where we make the type anonymous. 11993 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 11994 } 11995 11996 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11997 AdjustDeclIfTemplate(TagD); 11998 TagDecl *Tag = cast<TagDecl>(TagD); 11999 12000 // Enter the tag context. 12001 PushDeclContext(S, Tag); 12002 12003 ActOnDocumentableDecl(TagD); 12004 12005 // If there's a #pragma GCC visibility in scope, set the visibility of this 12006 // record. 12007 AddPushedVisibilityAttribute(Tag); 12008 } 12009 12010 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 12011 assert(isa<ObjCContainerDecl>(IDecl) && 12012 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 12013 DeclContext *OCD = cast<DeclContext>(IDecl); 12014 assert(getContainingDC(OCD) == CurContext && 12015 "The next DeclContext should be lexically contained in the current one."); 12016 CurContext = OCD; 12017 return IDecl; 12018 } 12019 12020 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 12021 SourceLocation FinalLoc, 12022 bool IsFinalSpelledSealed, 12023 SourceLocation LBraceLoc) { 12024 AdjustDeclIfTemplate(TagD); 12025 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 12026 12027 FieldCollector->StartClass(); 12028 12029 if (!Record->getIdentifier()) 12030 return; 12031 12032 if (FinalLoc.isValid()) 12033 Record->addAttr(new (Context) 12034 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 12035 12036 // C++ [class]p2: 12037 // [...] The class-name is also inserted into the scope of the 12038 // class itself; this is known as the injected-class-name. For 12039 // purposes of access checking, the injected-class-name is treated 12040 // as if it were a public member name. 12041 CXXRecordDecl *InjectedClassName 12042 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 12043 Record->getLocStart(), Record->getLocation(), 12044 Record->getIdentifier(), 12045 /*PrevDecl=*/nullptr, 12046 /*DelayTypeCreation=*/true); 12047 Context.getTypeDeclType(InjectedClassName, Record); 12048 InjectedClassName->setImplicit(); 12049 InjectedClassName->setAccess(AS_public); 12050 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 12051 InjectedClassName->setDescribedClassTemplate(Template); 12052 PushOnScopeChains(InjectedClassName, S); 12053 assert(InjectedClassName->isInjectedClassName() && 12054 "Broken injected-class-name"); 12055 } 12056 12057 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 12058 SourceLocation RBraceLoc) { 12059 AdjustDeclIfTemplate(TagD); 12060 TagDecl *Tag = cast<TagDecl>(TagD); 12061 Tag->setRBraceLoc(RBraceLoc); 12062 12063 // Make sure we "complete" the definition even it is invalid. 12064 if (Tag->isBeingDefined()) { 12065 assert(Tag->isInvalidDecl() && "We should already have completed it"); 12066 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12067 RD->completeDefinition(); 12068 } 12069 12070 if (isa<CXXRecordDecl>(Tag)) 12071 FieldCollector->FinishClass(); 12072 12073 // Exit this scope of this tag's definition. 12074 PopDeclContext(); 12075 12076 if (getCurLexicalContext()->isObjCContainer() && 12077 Tag->getDeclContext()->isFileContext()) 12078 Tag->setTopLevelDeclInObjCContainer(); 12079 12080 // Notify the consumer that we've defined a tag. 12081 if (!Tag->isInvalidDecl()) 12082 Consumer.HandleTagDeclDefinition(Tag); 12083 } 12084 12085 void Sema::ActOnObjCContainerFinishDefinition() { 12086 // Exit this scope of this interface definition. 12087 PopDeclContext(); 12088 } 12089 12090 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 12091 assert(DC == CurContext && "Mismatch of container contexts"); 12092 OriginalLexicalContext = DC; 12093 ActOnObjCContainerFinishDefinition(); 12094 } 12095 12096 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 12097 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 12098 OriginalLexicalContext = nullptr; 12099 } 12100 12101 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 12102 AdjustDeclIfTemplate(TagD); 12103 TagDecl *Tag = cast<TagDecl>(TagD); 12104 Tag->setInvalidDecl(); 12105 12106 // Make sure we "complete" the definition even it is invalid. 12107 if (Tag->isBeingDefined()) { 12108 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12109 RD->completeDefinition(); 12110 } 12111 12112 // We're undoing ActOnTagStartDefinition here, not 12113 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 12114 // the FieldCollector. 12115 12116 PopDeclContext(); 12117 } 12118 12119 // Note that FieldName may be null for anonymous bitfields. 12120 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 12121 IdentifierInfo *FieldName, 12122 QualType FieldTy, bool IsMsStruct, 12123 Expr *BitWidth, bool *ZeroWidth) { 12124 // Default to true; that shouldn't confuse checks for emptiness 12125 if (ZeroWidth) 12126 *ZeroWidth = true; 12127 12128 // C99 6.7.2.1p4 - verify the field type. 12129 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 12130 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 12131 // Handle incomplete types with specific error. 12132 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12133 return ExprError(); 12134 if (FieldName) 12135 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12136 << FieldName << FieldTy << BitWidth->getSourceRange(); 12137 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12138 << FieldTy << BitWidth->getSourceRange(); 12139 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12140 UPPC_BitFieldWidth)) 12141 return ExprError(); 12142 12143 // If the bit-width is type- or value-dependent, don't try to check 12144 // it now. 12145 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12146 return BitWidth; 12147 12148 llvm::APSInt Value; 12149 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12150 if (ICE.isInvalid()) 12151 return ICE; 12152 BitWidth = ICE.get(); 12153 12154 if (Value != 0 && ZeroWidth) 12155 *ZeroWidth = false; 12156 12157 // Zero-width bitfield is ok for anonymous field. 12158 if (Value == 0 && FieldName) 12159 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12160 12161 if (Value.isSigned() && Value.isNegative()) { 12162 if (FieldName) 12163 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12164 << FieldName << Value.toString(10); 12165 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12166 << Value.toString(10); 12167 } 12168 12169 if (!FieldTy->isDependentType()) { 12170 uint64_t TypeSize = Context.getTypeSize(FieldTy); 12171 if (Value.getZExtValue() > TypeSize) { 12172 if (!getLangOpts().CPlusPlus || IsMsStruct || 12173 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12174 if (FieldName) 12175 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 12176 << FieldName << (unsigned)Value.getZExtValue() 12177 << (unsigned)TypeSize; 12178 12179 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 12180 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12181 } 12182 12183 if (FieldName) 12184 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 12185 << FieldName << (unsigned)Value.getZExtValue() 12186 << (unsigned)TypeSize; 12187 else 12188 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 12189 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12190 } 12191 } 12192 12193 return BitWidth; 12194 } 12195 12196 /// ActOnField - Each field of a C struct/union is passed into this in order 12197 /// to create a FieldDecl object for it. 12198 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 12199 Declarator &D, Expr *BitfieldWidth) { 12200 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 12201 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 12202 /*InitStyle=*/ICIS_NoInit, AS_public); 12203 return Res; 12204 } 12205 12206 /// HandleField - Analyze a field of a C struct or a C++ data member. 12207 /// 12208 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 12209 SourceLocation DeclStart, 12210 Declarator &D, Expr *BitWidth, 12211 InClassInitStyle InitStyle, 12212 AccessSpecifier AS) { 12213 IdentifierInfo *II = D.getIdentifier(); 12214 SourceLocation Loc = DeclStart; 12215 if (II) Loc = D.getIdentifierLoc(); 12216 12217 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12218 QualType T = TInfo->getType(); 12219 if (getLangOpts().CPlusPlus) { 12220 CheckExtraCXXDefaultArguments(D); 12221 12222 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12223 UPPC_DataMemberType)) { 12224 D.setInvalidType(); 12225 T = Context.IntTy; 12226 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12227 } 12228 } 12229 12230 // TR 18037 does not allow fields to be declared with address spaces. 12231 if (T.getQualifiers().hasAddressSpace()) { 12232 Diag(Loc, diag::err_field_with_address_space); 12233 D.setInvalidType(); 12234 } 12235 12236 // OpenCL 1.2 spec, s6.9 r: 12237 // The event type cannot be used to declare a structure or union field. 12238 if (LangOpts.OpenCL && T->isEventT()) { 12239 Diag(Loc, diag::err_event_t_struct_field); 12240 D.setInvalidType(); 12241 } 12242 12243 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12244 12245 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12246 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12247 diag::err_invalid_thread) 12248 << DeclSpec::getSpecifierName(TSCS); 12249 12250 // Check to see if this name was declared as a member previously 12251 NamedDecl *PrevDecl = nullptr; 12252 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12253 LookupName(Previous, S); 12254 switch (Previous.getResultKind()) { 12255 case LookupResult::Found: 12256 case LookupResult::FoundUnresolvedValue: 12257 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12258 break; 12259 12260 case LookupResult::FoundOverloaded: 12261 PrevDecl = Previous.getRepresentativeDecl(); 12262 break; 12263 12264 case LookupResult::NotFound: 12265 case LookupResult::NotFoundInCurrentInstantiation: 12266 case LookupResult::Ambiguous: 12267 break; 12268 } 12269 Previous.suppressDiagnostics(); 12270 12271 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12272 // Maybe we will complain about the shadowed template parameter. 12273 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12274 // Just pretend that we didn't see the previous declaration. 12275 PrevDecl = nullptr; 12276 } 12277 12278 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12279 PrevDecl = nullptr; 12280 12281 bool Mutable 12282 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 12283 SourceLocation TSSL = D.getLocStart(); 12284 FieldDecl *NewFD 12285 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 12286 TSSL, AS, PrevDecl, &D); 12287 12288 if (NewFD->isInvalidDecl()) 12289 Record->setInvalidDecl(); 12290 12291 if (D.getDeclSpec().isModulePrivateSpecified()) 12292 NewFD->setModulePrivate(); 12293 12294 if (NewFD->isInvalidDecl() && PrevDecl) { 12295 // Don't introduce NewFD into scope; there's already something 12296 // with the same name in the same scope. 12297 } else if (II) { 12298 PushOnScopeChains(NewFD, S); 12299 } else 12300 Record->addDecl(NewFD); 12301 12302 return NewFD; 12303 } 12304 12305 /// \brief Build a new FieldDecl and check its well-formedness. 12306 /// 12307 /// This routine builds a new FieldDecl given the fields name, type, 12308 /// record, etc. \p PrevDecl should refer to any previous declaration 12309 /// with the same name and in the same scope as the field to be 12310 /// created. 12311 /// 12312 /// \returns a new FieldDecl. 12313 /// 12314 /// \todo The Declarator argument is a hack. It will be removed once 12315 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 12316 TypeSourceInfo *TInfo, 12317 RecordDecl *Record, SourceLocation Loc, 12318 bool Mutable, Expr *BitWidth, 12319 InClassInitStyle InitStyle, 12320 SourceLocation TSSL, 12321 AccessSpecifier AS, NamedDecl *PrevDecl, 12322 Declarator *D) { 12323 IdentifierInfo *II = Name.getAsIdentifierInfo(); 12324 bool InvalidDecl = false; 12325 if (D) InvalidDecl = D->isInvalidType(); 12326 12327 // If we receive a broken type, recover by assuming 'int' and 12328 // marking this declaration as invalid. 12329 if (T.isNull()) { 12330 InvalidDecl = true; 12331 T = Context.IntTy; 12332 } 12333 12334 QualType EltTy = Context.getBaseElementType(T); 12335 if (!EltTy->isDependentType()) { 12336 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 12337 // Fields of incomplete type force their record to be invalid. 12338 Record->setInvalidDecl(); 12339 InvalidDecl = true; 12340 } else { 12341 NamedDecl *Def; 12342 EltTy->isIncompleteType(&Def); 12343 if (Def && Def->isInvalidDecl()) { 12344 Record->setInvalidDecl(); 12345 InvalidDecl = true; 12346 } 12347 } 12348 } 12349 12350 // OpenCL v1.2 s6.9.c: bitfields are not supported. 12351 if (BitWidth && getLangOpts().OpenCL) { 12352 Diag(Loc, diag::err_opencl_bitfields); 12353 InvalidDecl = true; 12354 } 12355 12356 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12357 // than a variably modified type. 12358 if (!InvalidDecl && T->isVariablyModifiedType()) { 12359 bool SizeIsNegative; 12360 llvm::APSInt Oversized; 12361 12362 TypeSourceInfo *FixedTInfo = 12363 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 12364 SizeIsNegative, 12365 Oversized); 12366 if (FixedTInfo) { 12367 Diag(Loc, diag::warn_illegal_constant_array_size); 12368 TInfo = FixedTInfo; 12369 T = FixedTInfo->getType(); 12370 } else { 12371 if (SizeIsNegative) 12372 Diag(Loc, diag::err_typecheck_negative_array_size); 12373 else if (Oversized.getBoolValue()) 12374 Diag(Loc, diag::err_array_too_large) 12375 << Oversized.toString(10); 12376 else 12377 Diag(Loc, diag::err_typecheck_field_variable_size); 12378 InvalidDecl = true; 12379 } 12380 } 12381 12382 // Fields can not have abstract class types 12383 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 12384 diag::err_abstract_type_in_decl, 12385 AbstractFieldType)) 12386 InvalidDecl = true; 12387 12388 bool ZeroWidth = false; 12389 // If this is declared as a bit-field, check the bit-field. 12390 if (!InvalidDecl && BitWidth) { 12391 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 12392 &ZeroWidth).get(); 12393 if (!BitWidth) { 12394 InvalidDecl = true; 12395 BitWidth = nullptr; 12396 ZeroWidth = false; 12397 } 12398 } 12399 12400 // Check that 'mutable' is consistent with the type of the declaration. 12401 if (!InvalidDecl && Mutable) { 12402 unsigned DiagID = 0; 12403 if (T->isReferenceType()) 12404 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 12405 : diag::err_mutable_reference; 12406 else if (T.isConstQualified()) 12407 DiagID = diag::err_mutable_const; 12408 12409 if (DiagID) { 12410 SourceLocation ErrLoc = Loc; 12411 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 12412 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 12413 Diag(ErrLoc, DiagID); 12414 if (DiagID != diag::ext_mutable_reference) { 12415 Mutable = false; 12416 InvalidDecl = true; 12417 } 12418 } 12419 } 12420 12421 // C++11 [class.union]p8 (DR1460): 12422 // At most one variant member of a union may have a 12423 // brace-or-equal-initializer. 12424 if (InitStyle != ICIS_NoInit) 12425 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 12426 12427 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 12428 BitWidth, Mutable, InitStyle); 12429 if (InvalidDecl) 12430 NewFD->setInvalidDecl(); 12431 12432 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 12433 Diag(Loc, diag::err_duplicate_member) << II; 12434 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12435 NewFD->setInvalidDecl(); 12436 } 12437 12438 if (!InvalidDecl && getLangOpts().CPlusPlus) { 12439 if (Record->isUnion()) { 12440 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12441 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12442 if (RDecl->getDefinition()) { 12443 // C++ [class.union]p1: An object of a class with a non-trivial 12444 // constructor, a non-trivial copy constructor, a non-trivial 12445 // destructor, or a non-trivial copy assignment operator 12446 // cannot be a member of a union, nor can an array of such 12447 // objects. 12448 if (CheckNontrivialField(NewFD)) 12449 NewFD->setInvalidDecl(); 12450 } 12451 } 12452 12453 // C++ [class.union]p1: If a union contains a member of reference type, 12454 // the program is ill-formed, except when compiling with MSVC extensions 12455 // enabled. 12456 if (EltTy->isReferenceType()) { 12457 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 12458 diag::ext_union_member_of_reference_type : 12459 diag::err_union_member_of_reference_type) 12460 << NewFD->getDeclName() << EltTy; 12461 if (!getLangOpts().MicrosoftExt) 12462 NewFD->setInvalidDecl(); 12463 } 12464 } 12465 } 12466 12467 // FIXME: We need to pass in the attributes given an AST 12468 // representation, not a parser representation. 12469 if (D) { 12470 // FIXME: The current scope is almost... but not entirely... correct here. 12471 ProcessDeclAttributes(getCurScope(), NewFD, *D); 12472 12473 if (NewFD->hasAttrs()) 12474 CheckAlignasUnderalignment(NewFD); 12475 } 12476 12477 // In auto-retain/release, infer strong retension for fields of 12478 // retainable type. 12479 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 12480 NewFD->setInvalidDecl(); 12481 12482 if (T.isObjCGCWeak()) 12483 Diag(Loc, diag::warn_attribute_weak_on_field); 12484 12485 NewFD->setAccess(AS); 12486 return NewFD; 12487 } 12488 12489 bool Sema::CheckNontrivialField(FieldDecl *FD) { 12490 assert(FD); 12491 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 12492 12493 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 12494 return false; 12495 12496 QualType EltTy = Context.getBaseElementType(FD->getType()); 12497 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12498 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12499 if (RDecl->getDefinition()) { 12500 // We check for copy constructors before constructors 12501 // because otherwise we'll never get complaints about 12502 // copy constructors. 12503 12504 CXXSpecialMember member = CXXInvalid; 12505 // We're required to check for any non-trivial constructors. Since the 12506 // implicit default constructor is suppressed if there are any 12507 // user-declared constructors, we just need to check that there is a 12508 // trivial default constructor and a trivial copy constructor. (We don't 12509 // worry about move constructors here, since this is a C++98 check.) 12510 if (RDecl->hasNonTrivialCopyConstructor()) 12511 member = CXXCopyConstructor; 12512 else if (!RDecl->hasTrivialDefaultConstructor()) 12513 member = CXXDefaultConstructor; 12514 else if (RDecl->hasNonTrivialCopyAssignment()) 12515 member = CXXCopyAssignment; 12516 else if (RDecl->hasNonTrivialDestructor()) 12517 member = CXXDestructor; 12518 12519 if (member != CXXInvalid) { 12520 if (!getLangOpts().CPlusPlus11 && 12521 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 12522 // Objective-C++ ARC: it is an error to have a non-trivial field of 12523 // a union. However, system headers in Objective-C programs 12524 // occasionally have Objective-C lifetime objects within unions, 12525 // and rather than cause the program to fail, we make those 12526 // members unavailable. 12527 SourceLocation Loc = FD->getLocation(); 12528 if (getSourceManager().isInSystemHeader(Loc)) { 12529 if (!FD->hasAttr<UnavailableAttr>()) 12530 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12531 "this system field has retaining ownership", 12532 Loc)); 12533 return false; 12534 } 12535 } 12536 12537 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 12538 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 12539 diag::err_illegal_union_or_anon_struct_member) 12540 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 12541 DiagnoseNontrivial(RDecl, member); 12542 return !getLangOpts().CPlusPlus11; 12543 } 12544 } 12545 } 12546 12547 return false; 12548 } 12549 12550 /// TranslateIvarVisibility - Translate visibility from a token ID to an 12551 /// AST enum value. 12552 static ObjCIvarDecl::AccessControl 12553 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 12554 switch (ivarVisibility) { 12555 default: llvm_unreachable("Unknown visitibility kind"); 12556 case tok::objc_private: return ObjCIvarDecl::Private; 12557 case tok::objc_public: return ObjCIvarDecl::Public; 12558 case tok::objc_protected: return ObjCIvarDecl::Protected; 12559 case tok::objc_package: return ObjCIvarDecl::Package; 12560 } 12561 } 12562 12563 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 12564 /// in order to create an IvarDecl object for it. 12565 Decl *Sema::ActOnIvar(Scope *S, 12566 SourceLocation DeclStart, 12567 Declarator &D, Expr *BitfieldWidth, 12568 tok::ObjCKeywordKind Visibility) { 12569 12570 IdentifierInfo *II = D.getIdentifier(); 12571 Expr *BitWidth = (Expr*)BitfieldWidth; 12572 SourceLocation Loc = DeclStart; 12573 if (II) Loc = D.getIdentifierLoc(); 12574 12575 // FIXME: Unnamed fields can be handled in various different ways, for 12576 // example, unnamed unions inject all members into the struct namespace! 12577 12578 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12579 QualType T = TInfo->getType(); 12580 12581 if (BitWidth) { 12582 // 6.7.2.1p3, 6.7.2.1p4 12583 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 12584 if (!BitWidth) 12585 D.setInvalidType(); 12586 } else { 12587 // Not a bitfield. 12588 12589 // validate II. 12590 12591 } 12592 if (T->isReferenceType()) { 12593 Diag(Loc, diag::err_ivar_reference_type); 12594 D.setInvalidType(); 12595 } 12596 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12597 // than a variably modified type. 12598 else if (T->isVariablyModifiedType()) { 12599 Diag(Loc, diag::err_typecheck_ivar_variable_size); 12600 D.setInvalidType(); 12601 } 12602 12603 // Get the visibility (access control) for this ivar. 12604 ObjCIvarDecl::AccessControl ac = 12605 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 12606 : ObjCIvarDecl::None; 12607 // Must set ivar's DeclContext to its enclosing interface. 12608 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 12609 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 12610 return nullptr; 12611 ObjCContainerDecl *EnclosingContext; 12612 if (ObjCImplementationDecl *IMPDecl = 12613 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12614 if (LangOpts.ObjCRuntime.isFragile()) { 12615 // Case of ivar declared in an implementation. Context is that of its class. 12616 EnclosingContext = IMPDecl->getClassInterface(); 12617 assert(EnclosingContext && "Implementation has no class interface!"); 12618 } 12619 else 12620 EnclosingContext = EnclosingDecl; 12621 } else { 12622 if (ObjCCategoryDecl *CDecl = 12623 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12624 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12625 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12626 return nullptr; 12627 } 12628 } 12629 EnclosingContext = EnclosingDecl; 12630 } 12631 12632 // Construct the decl. 12633 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12634 DeclStart, Loc, II, T, 12635 TInfo, ac, (Expr *)BitfieldWidth); 12636 12637 if (II) { 12638 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12639 ForRedeclaration); 12640 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12641 && !isa<TagDecl>(PrevDecl)) { 12642 Diag(Loc, diag::err_duplicate_member) << II; 12643 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12644 NewID->setInvalidDecl(); 12645 } 12646 } 12647 12648 // Process attributes attached to the ivar. 12649 ProcessDeclAttributes(S, NewID, D); 12650 12651 if (D.isInvalidType()) 12652 NewID->setInvalidDecl(); 12653 12654 // In ARC, infer 'retaining' for ivars of retainable type. 12655 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12656 NewID->setInvalidDecl(); 12657 12658 if (D.getDeclSpec().isModulePrivateSpecified()) 12659 NewID->setModulePrivate(); 12660 12661 if (II) { 12662 // FIXME: When interfaces are DeclContexts, we'll need to add 12663 // these to the interface. 12664 S->AddDecl(NewID); 12665 IdResolver.AddDecl(NewID); 12666 } 12667 12668 if (LangOpts.ObjCRuntime.isNonFragile() && 12669 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12670 Diag(Loc, diag::warn_ivars_in_interface); 12671 12672 return NewID; 12673 } 12674 12675 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12676 /// class and class extensions. For every class \@interface and class 12677 /// extension \@interface, if the last ivar is a bitfield of any type, 12678 /// then add an implicit `char :0` ivar to the end of that interface. 12679 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12680 SmallVectorImpl<Decl *> &AllIvarDecls) { 12681 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12682 return; 12683 12684 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12685 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12686 12687 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12688 return; 12689 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12690 if (!ID) { 12691 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12692 if (!CD->IsClassExtension()) 12693 return; 12694 } 12695 // No need to add this to end of @implementation. 12696 else 12697 return; 12698 } 12699 // All conditions are met. Add a new bitfield to the tail end of ivars. 12700 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12701 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12702 12703 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12704 DeclLoc, DeclLoc, nullptr, 12705 Context.CharTy, 12706 Context.getTrivialTypeSourceInfo(Context.CharTy, 12707 DeclLoc), 12708 ObjCIvarDecl::Private, BW, 12709 true); 12710 AllIvarDecls.push_back(Ivar); 12711 } 12712 12713 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12714 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12715 SourceLocation RBrac, AttributeList *Attr) { 12716 assert(EnclosingDecl && "missing record or interface decl"); 12717 12718 // If this is an Objective-C @implementation or category and we have 12719 // new fields here we should reset the layout of the interface since 12720 // it will now change. 12721 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12722 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12723 switch (DC->getKind()) { 12724 default: break; 12725 case Decl::ObjCCategory: 12726 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12727 break; 12728 case Decl::ObjCImplementation: 12729 Context. 12730 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12731 break; 12732 } 12733 } 12734 12735 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12736 12737 // Start counting up the number of named members; make sure to include 12738 // members of anonymous structs and unions in the total. 12739 unsigned NumNamedMembers = 0; 12740 if (Record) { 12741 for (const auto *I : Record->decls()) { 12742 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12743 if (IFD->getDeclName()) 12744 ++NumNamedMembers; 12745 } 12746 } 12747 12748 // Verify that all the fields are okay. 12749 SmallVector<FieldDecl*, 32> RecFields; 12750 12751 bool ARCErrReported = false; 12752 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12753 i != end; ++i) { 12754 FieldDecl *FD = cast<FieldDecl>(*i); 12755 12756 // Get the type for the field. 12757 const Type *FDTy = FD->getType().getTypePtr(); 12758 12759 if (!FD->isAnonymousStructOrUnion()) { 12760 // Remember all fields written by the user. 12761 RecFields.push_back(FD); 12762 } 12763 12764 // If the field is already invalid for some reason, don't emit more 12765 // diagnostics about it. 12766 if (FD->isInvalidDecl()) { 12767 EnclosingDecl->setInvalidDecl(); 12768 continue; 12769 } 12770 12771 // C99 6.7.2.1p2: 12772 // A structure or union shall not contain a member with 12773 // incomplete or function type (hence, a structure shall not 12774 // contain an instance of itself, but may contain a pointer to 12775 // an instance of itself), except that the last member of a 12776 // structure with more than one named member may have incomplete 12777 // array type; such a structure (and any union containing, 12778 // possibly recursively, a member that is such a structure) 12779 // shall not be a member of a structure or an element of an 12780 // array. 12781 if (FDTy->isFunctionType()) { 12782 // Field declared as a function. 12783 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12784 << FD->getDeclName(); 12785 FD->setInvalidDecl(); 12786 EnclosingDecl->setInvalidDecl(); 12787 continue; 12788 } else if (FDTy->isIncompleteArrayType() && Record && 12789 ((i + 1 == Fields.end() && !Record->isUnion()) || 12790 ((getLangOpts().MicrosoftExt || 12791 getLangOpts().CPlusPlus) && 12792 (i + 1 == Fields.end() || Record->isUnion())))) { 12793 // Flexible array member. 12794 // Microsoft and g++ is more permissive regarding flexible array. 12795 // It will accept flexible array in union and also 12796 // as the sole element of a struct/class. 12797 unsigned DiagID = 0; 12798 if (Record->isUnion()) 12799 DiagID = getLangOpts().MicrosoftExt 12800 ? diag::ext_flexible_array_union_ms 12801 : getLangOpts().CPlusPlus 12802 ? diag::ext_flexible_array_union_gnu 12803 : diag::err_flexible_array_union; 12804 else if (Fields.size() == 1) 12805 DiagID = getLangOpts().MicrosoftExt 12806 ? diag::ext_flexible_array_empty_aggregate_ms 12807 : getLangOpts().CPlusPlus 12808 ? diag::ext_flexible_array_empty_aggregate_gnu 12809 : NumNamedMembers < 1 12810 ? diag::err_flexible_array_empty_aggregate 12811 : 0; 12812 12813 if (DiagID) 12814 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12815 << Record->getTagKind(); 12816 // While the layout of types that contain virtual bases is not specified 12817 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12818 // virtual bases after the derived members. This would make a flexible 12819 // array member declared at the end of an object not adjacent to the end 12820 // of the type. 12821 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12822 if (RD->getNumVBases() != 0) 12823 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12824 << FD->getDeclName() << Record->getTagKind(); 12825 if (!getLangOpts().C99) 12826 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12827 << FD->getDeclName() << Record->getTagKind(); 12828 12829 // If the element type has a non-trivial destructor, we would not 12830 // implicitly destroy the elements, so disallow it for now. 12831 // 12832 // FIXME: GCC allows this. We should probably either implicitly delete 12833 // the destructor of the containing class, or just allow this. 12834 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12835 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12836 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12837 << FD->getDeclName() << FD->getType(); 12838 FD->setInvalidDecl(); 12839 EnclosingDecl->setInvalidDecl(); 12840 continue; 12841 } 12842 // Okay, we have a legal flexible array member at the end of the struct. 12843 Record->setHasFlexibleArrayMember(true); 12844 } else if (!FDTy->isDependentType() && 12845 RequireCompleteType(FD->getLocation(), FD->getType(), 12846 diag::err_field_incomplete)) { 12847 // Incomplete type 12848 FD->setInvalidDecl(); 12849 EnclosingDecl->setInvalidDecl(); 12850 continue; 12851 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12852 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 12853 // A type which contains a flexible array member is considered to be a 12854 // flexible array member. 12855 Record->setHasFlexibleArrayMember(true); 12856 if (!Record->isUnion()) { 12857 // If this is a struct/class and this is not the last element, reject 12858 // it. Note that GCC supports variable sized arrays in the middle of 12859 // structures. 12860 if (i + 1 != Fields.end()) 12861 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12862 << FD->getDeclName() << FD->getType(); 12863 else { 12864 // We support flexible arrays at the end of structs in 12865 // other structs as an extension. 12866 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12867 << FD->getDeclName(); 12868 } 12869 } 12870 } 12871 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12872 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12873 diag::err_abstract_type_in_decl, 12874 AbstractIvarType)) { 12875 // Ivars can not have abstract class types 12876 FD->setInvalidDecl(); 12877 } 12878 if (Record && FDTTy->getDecl()->hasObjectMember()) 12879 Record->setHasObjectMember(true); 12880 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12881 Record->setHasVolatileMember(true); 12882 } else if (FDTy->isObjCObjectType()) { 12883 /// A field cannot be an Objective-c object 12884 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12885 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12886 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12887 FD->setType(T); 12888 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12889 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12890 // It's an error in ARC if a field has lifetime. 12891 // We don't want to report this in a system header, though, 12892 // so we just make the field unavailable. 12893 // FIXME: that's really not sufficient; we need to make the type 12894 // itself invalid to, say, initialize or copy. 12895 QualType T = FD->getType(); 12896 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12897 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12898 SourceLocation loc = FD->getLocation(); 12899 if (getSourceManager().isInSystemHeader(loc)) { 12900 if (!FD->hasAttr<UnavailableAttr>()) { 12901 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12902 "this system field has retaining ownership", 12903 loc)); 12904 } 12905 } else { 12906 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12907 << T->isBlockPointerType() << Record->getTagKind(); 12908 } 12909 ARCErrReported = true; 12910 } 12911 } else if (getLangOpts().ObjC1 && 12912 getLangOpts().getGC() != LangOptions::NonGC && 12913 Record && !Record->hasObjectMember()) { 12914 if (FD->getType()->isObjCObjectPointerType() || 12915 FD->getType().isObjCGCStrong()) 12916 Record->setHasObjectMember(true); 12917 else if (Context.getAsArrayType(FD->getType())) { 12918 QualType BaseType = Context.getBaseElementType(FD->getType()); 12919 if (BaseType->isRecordType() && 12920 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12921 Record->setHasObjectMember(true); 12922 else if (BaseType->isObjCObjectPointerType() || 12923 BaseType.isObjCGCStrong()) 12924 Record->setHasObjectMember(true); 12925 } 12926 } 12927 if (Record && FD->getType().isVolatileQualified()) 12928 Record->setHasVolatileMember(true); 12929 // Keep track of the number of named members. 12930 if (FD->getIdentifier()) 12931 ++NumNamedMembers; 12932 } 12933 12934 // Okay, we successfully defined 'Record'. 12935 if (Record) { 12936 bool Completed = false; 12937 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12938 if (!CXXRecord->isInvalidDecl()) { 12939 // Set access bits correctly on the directly-declared conversions. 12940 for (CXXRecordDecl::conversion_iterator 12941 I = CXXRecord->conversion_begin(), 12942 E = CXXRecord->conversion_end(); I != E; ++I) 12943 I.setAccess((*I)->getAccess()); 12944 12945 if (!CXXRecord->isDependentType()) { 12946 if (CXXRecord->hasUserDeclaredDestructor()) { 12947 // Adjust user-defined destructor exception spec. 12948 if (getLangOpts().CPlusPlus11) 12949 AdjustDestructorExceptionSpec(CXXRecord, 12950 CXXRecord->getDestructor()); 12951 } 12952 12953 // Add any implicitly-declared members to this class. 12954 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12955 12956 // If we have virtual base classes, we may end up finding multiple 12957 // final overriders for a given virtual function. Check for this 12958 // problem now. 12959 if (CXXRecord->getNumVBases()) { 12960 CXXFinalOverriderMap FinalOverriders; 12961 CXXRecord->getFinalOverriders(FinalOverriders); 12962 12963 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12964 MEnd = FinalOverriders.end(); 12965 M != MEnd; ++M) { 12966 for (OverridingMethods::iterator SO = M->second.begin(), 12967 SOEnd = M->second.end(); 12968 SO != SOEnd; ++SO) { 12969 assert(SO->second.size() > 0 && 12970 "Virtual function without overridding functions?"); 12971 if (SO->second.size() == 1) 12972 continue; 12973 12974 // C++ [class.virtual]p2: 12975 // In a derived class, if a virtual member function of a base 12976 // class subobject has more than one final overrider the 12977 // program is ill-formed. 12978 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12979 << (const NamedDecl *)M->first << Record; 12980 Diag(M->first->getLocation(), 12981 diag::note_overridden_virtual_function); 12982 for (OverridingMethods::overriding_iterator 12983 OM = SO->second.begin(), 12984 OMEnd = SO->second.end(); 12985 OM != OMEnd; ++OM) 12986 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12987 << (const NamedDecl *)M->first << OM->Method->getParent(); 12988 12989 Record->setInvalidDecl(); 12990 } 12991 } 12992 CXXRecord->completeDefinition(&FinalOverriders); 12993 Completed = true; 12994 } 12995 } 12996 } 12997 } 12998 12999 if (!Completed) 13000 Record->completeDefinition(); 13001 13002 if (Record->hasAttrs()) { 13003 CheckAlignasUnderalignment(Record); 13004 13005 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 13006 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 13007 IA->getRange(), IA->getBestCase(), 13008 IA->getSemanticSpelling()); 13009 } 13010 13011 // Check if the structure/union declaration is a type that can have zero 13012 // size in C. For C this is a language extension, for C++ it may cause 13013 // compatibility problems. 13014 bool CheckForZeroSize; 13015 if (!getLangOpts().CPlusPlus) { 13016 CheckForZeroSize = true; 13017 } else { 13018 // For C++ filter out types that cannot be referenced in C code. 13019 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 13020 CheckForZeroSize = 13021 CXXRecord->getLexicalDeclContext()->isExternCContext() && 13022 !CXXRecord->isDependentType() && 13023 CXXRecord->isCLike(); 13024 } 13025 if (CheckForZeroSize) { 13026 bool ZeroSize = true; 13027 bool IsEmpty = true; 13028 unsigned NonBitFields = 0; 13029 for (RecordDecl::field_iterator I = Record->field_begin(), 13030 E = Record->field_end(); 13031 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 13032 IsEmpty = false; 13033 if (I->isUnnamedBitfield()) { 13034 if (I->getBitWidthValue(Context) > 0) 13035 ZeroSize = false; 13036 } else { 13037 ++NonBitFields; 13038 QualType FieldType = I->getType(); 13039 if (FieldType->isIncompleteType() || 13040 !Context.getTypeSizeInChars(FieldType).isZero()) 13041 ZeroSize = false; 13042 } 13043 } 13044 13045 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 13046 // allowed in C++, but warn if its declaration is inside 13047 // extern "C" block. 13048 if (ZeroSize) { 13049 Diag(RecLoc, getLangOpts().CPlusPlus ? 13050 diag::warn_zero_size_struct_union_in_extern_c : 13051 diag::warn_zero_size_struct_union_compat) 13052 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 13053 } 13054 13055 // Structs without named members are extension in C (C99 6.7.2.1p7), 13056 // but are accepted by GCC. 13057 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 13058 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 13059 diag::ext_no_named_members_in_struct_union) 13060 << Record->isUnion(); 13061 } 13062 } 13063 } else { 13064 ObjCIvarDecl **ClsFields = 13065 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 13066 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 13067 ID->setEndOfDefinitionLoc(RBrac); 13068 // Add ivar's to class's DeclContext. 13069 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13070 ClsFields[i]->setLexicalDeclContext(ID); 13071 ID->addDecl(ClsFields[i]); 13072 } 13073 // Must enforce the rule that ivars in the base classes may not be 13074 // duplicates. 13075 if (ID->getSuperClass()) 13076 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 13077 } else if (ObjCImplementationDecl *IMPDecl = 13078 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13079 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 13080 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 13081 // Ivar declared in @implementation never belongs to the implementation. 13082 // Only it is in implementation's lexical context. 13083 ClsFields[I]->setLexicalDeclContext(IMPDecl); 13084 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 13085 IMPDecl->setIvarLBraceLoc(LBrac); 13086 IMPDecl->setIvarRBraceLoc(RBrac); 13087 } else if (ObjCCategoryDecl *CDecl = 13088 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13089 // case of ivars in class extension; all other cases have been 13090 // reported as errors elsewhere. 13091 // FIXME. Class extension does not have a LocEnd field. 13092 // CDecl->setLocEnd(RBrac); 13093 // Add ivar's to class extension's DeclContext. 13094 // Diagnose redeclaration of private ivars. 13095 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 13096 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13097 if (IDecl) { 13098 if (const ObjCIvarDecl *ClsIvar = 13099 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 13100 Diag(ClsFields[i]->getLocation(), 13101 diag::err_duplicate_ivar_declaration); 13102 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 13103 continue; 13104 } 13105 for (const auto *Ext : IDecl->known_extensions()) { 13106 if (const ObjCIvarDecl *ClsExtIvar 13107 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 13108 Diag(ClsFields[i]->getLocation(), 13109 diag::err_duplicate_ivar_declaration); 13110 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 13111 continue; 13112 } 13113 } 13114 } 13115 ClsFields[i]->setLexicalDeclContext(CDecl); 13116 CDecl->addDecl(ClsFields[i]); 13117 } 13118 CDecl->setIvarLBraceLoc(LBrac); 13119 CDecl->setIvarRBraceLoc(RBrac); 13120 } 13121 } 13122 13123 if (Attr) 13124 ProcessDeclAttributeList(S, Record, Attr); 13125 } 13126 13127 /// \brief Determine whether the given integral value is representable within 13128 /// the given type T. 13129 static bool isRepresentableIntegerValue(ASTContext &Context, 13130 llvm::APSInt &Value, 13131 QualType T) { 13132 assert(T->isIntegralType(Context) && "Integral type required!"); 13133 unsigned BitWidth = Context.getIntWidth(T); 13134 13135 if (Value.isUnsigned() || Value.isNonNegative()) { 13136 if (T->isSignedIntegerOrEnumerationType()) 13137 --BitWidth; 13138 return Value.getActiveBits() <= BitWidth; 13139 } 13140 return Value.getMinSignedBits() <= BitWidth; 13141 } 13142 13143 // \brief Given an integral type, return the next larger integral type 13144 // (or a NULL type of no such type exists). 13145 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13146 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13147 // enum checking below. 13148 assert(T->isIntegralType(Context) && "Integral type required!"); 13149 const unsigned NumTypes = 4; 13150 QualType SignedIntegralTypes[NumTypes] = { 13151 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13152 }; 13153 QualType UnsignedIntegralTypes[NumTypes] = { 13154 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13155 Context.UnsignedLongLongTy 13156 }; 13157 13158 unsigned BitWidth = Context.getTypeSize(T); 13159 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13160 : UnsignedIntegralTypes; 13161 for (unsigned I = 0; I != NumTypes; ++I) 13162 if (Context.getTypeSize(Types[I]) > BitWidth) 13163 return Types[I]; 13164 13165 return QualType(); 13166 } 13167 13168 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13169 EnumConstantDecl *LastEnumConst, 13170 SourceLocation IdLoc, 13171 IdentifierInfo *Id, 13172 Expr *Val) { 13173 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13174 llvm::APSInt EnumVal(IntWidth); 13175 QualType EltTy; 13176 13177 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13178 Val = nullptr; 13179 13180 if (Val) 13181 Val = DefaultLvalueConversion(Val).get(); 13182 13183 if (Val) { 13184 if (Enum->isDependentType() || Val->isTypeDependent()) 13185 EltTy = Context.DependentTy; 13186 else { 13187 SourceLocation ExpLoc; 13188 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 13189 !getLangOpts().MSVCCompat) { 13190 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 13191 // constant-expression in the enumerator-definition shall be a converted 13192 // constant expression of the underlying type. 13193 EltTy = Enum->getIntegerType(); 13194 ExprResult Converted = 13195 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 13196 CCEK_Enumerator); 13197 if (Converted.isInvalid()) 13198 Val = nullptr; 13199 else 13200 Val = Converted.get(); 13201 } else if (!Val->isValueDependent() && 13202 !(Val = VerifyIntegerConstantExpression(Val, 13203 &EnumVal).get())) { 13204 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 13205 } else { 13206 if (Enum->isFixed()) { 13207 EltTy = Enum->getIntegerType(); 13208 13209 // In Obj-C and Microsoft mode, require the enumeration value to be 13210 // representable in the underlying type of the enumeration. In C++11, 13211 // we perform a non-narrowing conversion as part of converted constant 13212 // expression checking. 13213 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13214 if (getLangOpts().MSVCCompat) { 13215 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 13216 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13217 } else 13218 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 13219 } else 13220 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13221 } else if (getLangOpts().CPlusPlus) { 13222 // C++11 [dcl.enum]p5: 13223 // If the underlying type is not fixed, the type of each enumerator 13224 // is the type of its initializing value: 13225 // - If an initializer is specified for an enumerator, the 13226 // initializing value has the same type as the expression. 13227 EltTy = Val->getType(); 13228 } else { 13229 // C99 6.7.2.2p2: 13230 // The expression that defines the value of an enumeration constant 13231 // shall be an integer constant expression that has a value 13232 // representable as an int. 13233 13234 // Complain if the value is not representable in an int. 13235 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 13236 Diag(IdLoc, diag::ext_enum_value_not_int) 13237 << EnumVal.toString(10) << Val->getSourceRange() 13238 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 13239 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 13240 // Force the type of the expression to 'int'. 13241 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 13242 } 13243 EltTy = Val->getType(); 13244 } 13245 } 13246 } 13247 } 13248 13249 if (!Val) { 13250 if (Enum->isDependentType()) 13251 EltTy = Context.DependentTy; 13252 else if (!LastEnumConst) { 13253 // C++0x [dcl.enum]p5: 13254 // If the underlying type is not fixed, the type of each enumerator 13255 // is the type of its initializing value: 13256 // - If no initializer is specified for the first enumerator, the 13257 // initializing value has an unspecified integral type. 13258 // 13259 // GCC uses 'int' for its unspecified integral type, as does 13260 // C99 6.7.2.2p3. 13261 if (Enum->isFixed()) { 13262 EltTy = Enum->getIntegerType(); 13263 } 13264 else { 13265 EltTy = Context.IntTy; 13266 } 13267 } else { 13268 // Assign the last value + 1. 13269 EnumVal = LastEnumConst->getInitVal(); 13270 ++EnumVal; 13271 EltTy = LastEnumConst->getType(); 13272 13273 // Check for overflow on increment. 13274 if (EnumVal < LastEnumConst->getInitVal()) { 13275 // C++0x [dcl.enum]p5: 13276 // If the underlying type is not fixed, the type of each enumerator 13277 // is the type of its initializing value: 13278 // 13279 // - Otherwise the type of the initializing value is the same as 13280 // the type of the initializing value of the preceding enumerator 13281 // unless the incremented value is not representable in that type, 13282 // in which case the type is an unspecified integral type 13283 // sufficient to contain the incremented value. If no such type 13284 // exists, the program is ill-formed. 13285 QualType T = getNextLargerIntegralType(Context, EltTy); 13286 if (T.isNull() || Enum->isFixed()) { 13287 // There is no integral type larger enough to represent this 13288 // value. Complain, then allow the value to wrap around. 13289 EnumVal = LastEnumConst->getInitVal(); 13290 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 13291 ++EnumVal; 13292 if (Enum->isFixed()) 13293 // When the underlying type is fixed, this is ill-formed. 13294 Diag(IdLoc, diag::err_enumerator_wrapped) 13295 << EnumVal.toString(10) 13296 << EltTy; 13297 else 13298 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 13299 << EnumVal.toString(10); 13300 } else { 13301 EltTy = T; 13302 } 13303 13304 // Retrieve the last enumerator's value, extent that type to the 13305 // type that is supposed to be large enough to represent the incremented 13306 // value, then increment. 13307 EnumVal = LastEnumConst->getInitVal(); 13308 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13309 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 13310 ++EnumVal; 13311 13312 // If we're not in C++, diagnose the overflow of enumerator values, 13313 // which in C99 means that the enumerator value is not representable in 13314 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 13315 // permits enumerator values that are representable in some larger 13316 // integral type. 13317 if (!getLangOpts().CPlusPlus && !T.isNull()) 13318 Diag(IdLoc, diag::warn_enum_value_overflow); 13319 } else if (!getLangOpts().CPlusPlus && 13320 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13321 // Enforce C99 6.7.2.2p2 even when we compute the next value. 13322 Diag(IdLoc, diag::ext_enum_value_not_int) 13323 << EnumVal.toString(10) << 1; 13324 } 13325 } 13326 } 13327 13328 if (!EltTy->isDependentType()) { 13329 // Make the enumerator value match the signedness and size of the 13330 // enumerator's type. 13331 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 13332 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13333 } 13334 13335 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 13336 Val, EnumVal); 13337 } 13338 13339 13340 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 13341 SourceLocation IdLoc, IdentifierInfo *Id, 13342 AttributeList *Attr, 13343 SourceLocation EqualLoc, Expr *Val) { 13344 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 13345 EnumConstantDecl *LastEnumConst = 13346 cast_or_null<EnumConstantDecl>(lastEnumConst); 13347 13348 // The scope passed in may not be a decl scope. Zip up the scope tree until 13349 // we find one that is. 13350 S = getNonFieldDeclScope(S); 13351 13352 // Verify that there isn't already something declared with this name in this 13353 // scope. 13354 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 13355 ForRedeclaration); 13356 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13357 // Maybe we will complain about the shadowed template parameter. 13358 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 13359 // Just pretend that we didn't see the previous declaration. 13360 PrevDecl = nullptr; 13361 } 13362 13363 if (PrevDecl) { 13364 // When in C++, we may get a TagDecl with the same name; in this case the 13365 // enum constant will 'hide' the tag. 13366 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 13367 "Received TagDecl when not in C++!"); 13368 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 13369 if (isa<EnumConstantDecl>(PrevDecl)) 13370 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 13371 else 13372 Diag(IdLoc, diag::err_redefinition) << Id; 13373 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13374 return nullptr; 13375 } 13376 } 13377 13378 // C++ [class.mem]p15: 13379 // If T is the name of a class, then each of the following shall have a name 13380 // different from T: 13381 // - every enumerator of every member of class T that is an unscoped 13382 // enumerated type 13383 if (CXXRecordDecl *Record 13384 = dyn_cast<CXXRecordDecl>( 13385 TheEnumDecl->getDeclContext()->getRedeclContext())) 13386 if (!TheEnumDecl->isScoped() && 13387 Record->getIdentifier() && Record->getIdentifier() == Id) 13388 Diag(IdLoc, diag::err_member_name_of_class) << Id; 13389 13390 EnumConstantDecl *New = 13391 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 13392 13393 if (New) { 13394 // Process attributes. 13395 if (Attr) ProcessDeclAttributeList(S, New, Attr); 13396 13397 // Register this decl in the current scope stack. 13398 New->setAccess(TheEnumDecl->getAccess()); 13399 PushOnScopeChains(New, S); 13400 } 13401 13402 ActOnDocumentableDecl(New); 13403 13404 return New; 13405 } 13406 13407 // Returns true when the enum initial expression does not trigger the 13408 // duplicate enum warning. A few common cases are exempted as follows: 13409 // Element2 = Element1 13410 // Element2 = Element1 + 1 13411 // Element2 = Element1 - 1 13412 // Where Element2 and Element1 are from the same enum. 13413 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 13414 Expr *InitExpr = ECD->getInitExpr(); 13415 if (!InitExpr) 13416 return true; 13417 InitExpr = InitExpr->IgnoreImpCasts(); 13418 13419 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 13420 if (!BO->isAdditiveOp()) 13421 return true; 13422 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 13423 if (!IL) 13424 return true; 13425 if (IL->getValue() != 1) 13426 return true; 13427 13428 InitExpr = BO->getLHS(); 13429 } 13430 13431 // This checks if the elements are from the same enum. 13432 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 13433 if (!DRE) 13434 return true; 13435 13436 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 13437 if (!EnumConstant) 13438 return true; 13439 13440 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 13441 Enum) 13442 return true; 13443 13444 return false; 13445 } 13446 13447 struct DupKey { 13448 int64_t val; 13449 bool isTombstoneOrEmptyKey; 13450 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 13451 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 13452 }; 13453 13454 static DupKey GetDupKey(const llvm::APSInt& Val) { 13455 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 13456 false); 13457 } 13458 13459 struct DenseMapInfoDupKey { 13460 static DupKey getEmptyKey() { return DupKey(0, true); } 13461 static DupKey getTombstoneKey() { return DupKey(1, true); } 13462 static unsigned getHashValue(const DupKey Key) { 13463 return (unsigned)(Key.val * 37); 13464 } 13465 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 13466 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 13467 LHS.val == RHS.val; 13468 } 13469 }; 13470 13471 // Emits a warning when an element is implicitly set a value that 13472 // a previous element has already been set to. 13473 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 13474 EnumDecl *Enum, 13475 QualType EnumType) { 13476 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 13477 return; 13478 // Avoid anonymous enums 13479 if (!Enum->getIdentifier()) 13480 return; 13481 13482 // Only check for small enums. 13483 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 13484 return; 13485 13486 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 13487 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 13488 13489 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 13490 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 13491 ValueToVectorMap; 13492 13493 DuplicatesVector DupVector; 13494 ValueToVectorMap EnumMap; 13495 13496 // Populate the EnumMap with all values represented by enum constants without 13497 // an initialier. 13498 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13499 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13500 13501 // Null EnumConstantDecl means a previous diagnostic has been emitted for 13502 // this constant. Skip this enum since it may be ill-formed. 13503 if (!ECD) { 13504 return; 13505 } 13506 13507 if (ECD->getInitExpr()) 13508 continue; 13509 13510 DupKey Key = GetDupKey(ECD->getInitVal()); 13511 DeclOrVector &Entry = EnumMap[Key]; 13512 13513 // First time encountering this value. 13514 if (Entry.isNull()) 13515 Entry = ECD; 13516 } 13517 13518 // Create vectors for any values that has duplicates. 13519 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13520 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 13521 if (!ValidDuplicateEnum(ECD, Enum)) 13522 continue; 13523 13524 DupKey Key = GetDupKey(ECD->getInitVal()); 13525 13526 DeclOrVector& Entry = EnumMap[Key]; 13527 if (Entry.isNull()) 13528 continue; 13529 13530 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 13531 // Ensure constants are different. 13532 if (D == ECD) 13533 continue; 13534 13535 // Create new vector and push values onto it. 13536 ECDVector *Vec = new ECDVector(); 13537 Vec->push_back(D); 13538 Vec->push_back(ECD); 13539 13540 // Update entry to point to the duplicates vector. 13541 Entry = Vec; 13542 13543 // Store the vector somewhere we can consult later for quick emission of 13544 // diagnostics. 13545 DupVector.push_back(Vec); 13546 continue; 13547 } 13548 13549 ECDVector *Vec = Entry.get<ECDVector*>(); 13550 // Make sure constants are not added more than once. 13551 if (*Vec->begin() == ECD) 13552 continue; 13553 13554 Vec->push_back(ECD); 13555 } 13556 13557 // Emit diagnostics. 13558 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 13559 DupVectorEnd = DupVector.end(); 13560 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 13561 ECDVector *Vec = *DupVectorIter; 13562 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 13563 13564 // Emit warning for one enum constant. 13565 ECDVector::iterator I = Vec->begin(); 13566 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 13567 << (*I)->getName() << (*I)->getInitVal().toString(10) 13568 << (*I)->getSourceRange(); 13569 ++I; 13570 13571 // Emit one note for each of the remaining enum constants with 13572 // the same value. 13573 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 13574 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 13575 << (*I)->getName() << (*I)->getInitVal().toString(10) 13576 << (*I)->getSourceRange(); 13577 delete Vec; 13578 } 13579 } 13580 13581 bool 13582 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 13583 bool AllowMask) const { 13584 FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>(); 13585 assert(FEAttr && "looking for value in non-flag enum"); 13586 13587 llvm::APInt FlagMask = ~FEAttr->getFlagBits(); 13588 unsigned Width = FlagMask.getBitWidth(); 13589 13590 // We will try a zero-extended value for the regular check first. 13591 llvm::APInt ExtVal = Val.zextOrSelf(Width); 13592 13593 // A value is in a flag enum if either its bits are a subset of the enum's 13594 // flag bits (the first condition) or we are allowing masks and the same is 13595 // true of its complement (the second condition). When masks are allowed, we 13596 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 13597 // 13598 // While it's true that any value could be used as a mask, the assumption is 13599 // that a mask will have all of the insignificant bits set. Anything else is 13600 // likely a logic error. 13601 if (!(FlagMask & ExtVal)) 13602 return true; 13603 13604 if (AllowMask) { 13605 // Try a one-extended value instead. This can happen if the enum is wider 13606 // than the constant used, in C with extensions to allow for wider enums. 13607 // The mask will still have the correct behaviour, so we give the user the 13608 // benefit of the doubt. 13609 // 13610 // FIXME: This heuristic can cause weird results if the enum was extended 13611 // to a larger type and is signed, because then bit-masks of smaller types 13612 // that get extended will fall out of range (e.g. ~0x1u). We currently don't 13613 // detect that case and will get a false positive for it. In most cases, 13614 // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may 13615 // be fine just to accept this as a warning. 13616 ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth()); 13617 if (!(FlagMask & ~ExtVal)) 13618 return true; 13619 } 13620 13621 return false; 13622 } 13623 13624 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 13625 SourceLocation RBraceLoc, Decl *EnumDeclX, 13626 ArrayRef<Decl *> Elements, 13627 Scope *S, AttributeList *Attr) { 13628 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 13629 QualType EnumType = Context.getTypeDeclType(Enum); 13630 13631 if (Attr) 13632 ProcessDeclAttributeList(S, Enum, Attr); 13633 13634 if (Enum->isDependentType()) { 13635 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13636 EnumConstantDecl *ECD = 13637 cast_or_null<EnumConstantDecl>(Elements[i]); 13638 if (!ECD) continue; 13639 13640 ECD->setType(EnumType); 13641 } 13642 13643 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 13644 return; 13645 } 13646 13647 // TODO: If the result value doesn't fit in an int, it must be a long or long 13648 // long value. ISO C does not support this, but GCC does as an extension, 13649 // emit a warning. 13650 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13651 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 13652 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 13653 13654 // Verify that all the values are okay, compute the size of the values, and 13655 // reverse the list. 13656 unsigned NumNegativeBits = 0; 13657 unsigned NumPositiveBits = 0; 13658 13659 // Keep track of whether all elements have type int. 13660 bool AllElementsInt = true; 13661 13662 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13663 EnumConstantDecl *ECD = 13664 cast_or_null<EnumConstantDecl>(Elements[i]); 13665 if (!ECD) continue; // Already issued a diagnostic. 13666 13667 const llvm::APSInt &InitVal = ECD->getInitVal(); 13668 13669 // Keep track of the size of positive and negative values. 13670 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13671 NumPositiveBits = std::max(NumPositiveBits, 13672 (unsigned)InitVal.getActiveBits()); 13673 else 13674 NumNegativeBits = std::max(NumNegativeBits, 13675 (unsigned)InitVal.getMinSignedBits()); 13676 13677 // Keep track of whether every enum element has type int (very commmon). 13678 if (AllElementsInt) 13679 AllElementsInt = ECD->getType() == Context.IntTy; 13680 } 13681 13682 // Figure out the type that should be used for this enum. 13683 QualType BestType; 13684 unsigned BestWidth; 13685 13686 // C++0x N3000 [conv.prom]p3: 13687 // An rvalue of an unscoped enumeration type whose underlying 13688 // type is not fixed can be converted to an rvalue of the first 13689 // of the following types that can represent all the values of 13690 // the enumeration: int, unsigned int, long int, unsigned long 13691 // int, long long int, or unsigned long long int. 13692 // C99 6.4.4.3p2: 13693 // An identifier declared as an enumeration constant has type int. 13694 // The C99 rule is modified by a gcc extension 13695 QualType BestPromotionType; 13696 13697 bool Packed = Enum->hasAttr<PackedAttr>(); 13698 // -fshort-enums is the equivalent to specifying the packed attribute on all 13699 // enum definitions. 13700 if (LangOpts.ShortEnums) 13701 Packed = true; 13702 13703 if (Enum->isFixed()) { 13704 BestType = Enum->getIntegerType(); 13705 if (BestType->isPromotableIntegerType()) 13706 BestPromotionType = Context.getPromotedIntegerType(BestType); 13707 else 13708 BestPromotionType = BestType; 13709 13710 BestWidth = Context.getIntWidth(BestType); 13711 } 13712 else if (NumNegativeBits) { 13713 // If there is a negative value, figure out the smallest integer type (of 13714 // int/long/longlong) that fits. 13715 // If it's packed, check also if it fits a char or a short. 13716 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13717 BestType = Context.SignedCharTy; 13718 BestWidth = CharWidth; 13719 } else if (Packed && NumNegativeBits <= ShortWidth && 13720 NumPositiveBits < ShortWidth) { 13721 BestType = Context.ShortTy; 13722 BestWidth = ShortWidth; 13723 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13724 BestType = Context.IntTy; 13725 BestWidth = IntWidth; 13726 } else { 13727 BestWidth = Context.getTargetInfo().getLongWidth(); 13728 13729 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13730 BestType = Context.LongTy; 13731 } else { 13732 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13733 13734 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13735 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13736 BestType = Context.LongLongTy; 13737 } 13738 } 13739 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13740 } else { 13741 // If there is no negative value, figure out the smallest type that fits 13742 // all of the enumerator values. 13743 // If it's packed, check also if it fits a char or a short. 13744 if (Packed && NumPositiveBits <= CharWidth) { 13745 BestType = Context.UnsignedCharTy; 13746 BestPromotionType = Context.IntTy; 13747 BestWidth = CharWidth; 13748 } else if (Packed && NumPositiveBits <= ShortWidth) { 13749 BestType = Context.UnsignedShortTy; 13750 BestPromotionType = Context.IntTy; 13751 BestWidth = ShortWidth; 13752 } else if (NumPositiveBits <= IntWidth) { 13753 BestType = Context.UnsignedIntTy; 13754 BestWidth = IntWidth; 13755 BestPromotionType 13756 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13757 ? Context.UnsignedIntTy : Context.IntTy; 13758 } else if (NumPositiveBits <= 13759 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13760 BestType = Context.UnsignedLongTy; 13761 BestPromotionType 13762 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13763 ? Context.UnsignedLongTy : Context.LongTy; 13764 } else { 13765 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13766 assert(NumPositiveBits <= BestWidth && 13767 "How could an initializer get larger than ULL?"); 13768 BestType = Context.UnsignedLongLongTy; 13769 BestPromotionType 13770 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13771 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13772 } 13773 } 13774 13775 FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>(); 13776 if (FEAttr) 13777 FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0); 13778 13779 // Loop over all of the enumerator constants, changing their types to match 13780 // the type of the enum if needed. If we have a flag type, we also prepare the 13781 // FlagBits cache. 13782 for (auto *D : Elements) { 13783 auto *ECD = cast_or_null<EnumConstantDecl>(D); 13784 if (!ECD) continue; // Already issued a diagnostic. 13785 13786 // Standard C says the enumerators have int type, but we allow, as an 13787 // extension, the enumerators to be larger than int size. If each 13788 // enumerator value fits in an int, type it as an int, otherwise type it the 13789 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13790 // that X has type 'int', not 'unsigned'. 13791 13792 // Determine whether the value fits into an int. 13793 llvm::APSInt InitVal = ECD->getInitVal(); 13794 13795 // If it fits into an integer type, force it. Otherwise force it to match 13796 // the enum decl type. 13797 QualType NewTy; 13798 unsigned NewWidth; 13799 bool NewSign; 13800 if (!getLangOpts().CPlusPlus && 13801 !Enum->isFixed() && 13802 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13803 NewTy = Context.IntTy; 13804 NewWidth = IntWidth; 13805 NewSign = true; 13806 } else if (ECD->getType() == BestType) { 13807 // Already the right type! 13808 if (getLangOpts().CPlusPlus) 13809 // C++ [dcl.enum]p4: Following the closing brace of an 13810 // enum-specifier, each enumerator has the type of its 13811 // enumeration. 13812 ECD->setType(EnumType); 13813 goto flagbits; 13814 } else { 13815 NewTy = BestType; 13816 NewWidth = BestWidth; 13817 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13818 } 13819 13820 // Adjust the APSInt value. 13821 InitVal = InitVal.extOrTrunc(NewWidth); 13822 InitVal.setIsSigned(NewSign); 13823 ECD->setInitVal(InitVal); 13824 13825 // Adjust the Expr initializer and type. 13826 if (ECD->getInitExpr() && 13827 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13828 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13829 CK_IntegralCast, 13830 ECD->getInitExpr(), 13831 /*base paths*/ nullptr, 13832 VK_RValue)); 13833 if (getLangOpts().CPlusPlus) 13834 // C++ [dcl.enum]p4: Following the closing brace of an 13835 // enum-specifier, each enumerator has the type of its 13836 // enumeration. 13837 ECD->setType(EnumType); 13838 else 13839 ECD->setType(NewTy); 13840 13841 flagbits: 13842 // Check to see if we have a constant with exactly one bit set. Note that x 13843 // & (x - 1) will be nonzero if and only if x has more than one bit set. 13844 if (FEAttr) { 13845 llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth); 13846 if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) { 13847 FEAttr->getFlagBits() |= ExtVal; 13848 } 13849 } 13850 } 13851 13852 if (FEAttr) { 13853 for (Decl *D : Elements) { 13854 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 13855 if (!ECD) continue; // Already issued a diagnostic. 13856 13857 llvm::APSInt InitVal = ECD->getInitVal(); 13858 if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true)) 13859 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 13860 << ECD << Enum; 13861 } 13862 } 13863 13864 13865 13866 Enum->completeDefinition(BestType, BestPromotionType, 13867 NumPositiveBits, NumNegativeBits); 13868 13869 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13870 13871 // Now that the enum type is defined, ensure it's not been underaligned. 13872 if (Enum->hasAttrs()) 13873 CheckAlignasUnderalignment(Enum); 13874 } 13875 13876 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13877 SourceLocation StartLoc, 13878 SourceLocation EndLoc) { 13879 StringLiteral *AsmString = cast<StringLiteral>(expr); 13880 13881 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13882 AsmString, StartLoc, 13883 EndLoc); 13884 CurContext->addDecl(New); 13885 return New; 13886 } 13887 13888 static void checkModuleImportContext(Sema &S, Module *M, 13889 SourceLocation ImportLoc, 13890 DeclContext *DC) { 13891 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13892 switch (LSD->getLanguage()) { 13893 case LinkageSpecDecl::lang_c: 13894 if (!M->IsExternC) { 13895 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13896 << M->getFullModuleName(); 13897 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13898 return; 13899 } 13900 break; 13901 case LinkageSpecDecl::lang_cxx: 13902 break; 13903 } 13904 DC = LSD->getParent(); 13905 } 13906 13907 while (isa<LinkageSpecDecl>(DC)) 13908 DC = DC->getParent(); 13909 if (!isa<TranslationUnitDecl>(DC)) { 13910 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13911 << M->getFullModuleName() << DC; 13912 S.Diag(cast<Decl>(DC)->getLocStart(), 13913 diag::note_module_import_not_at_top_level) 13914 << DC; 13915 } 13916 } 13917 13918 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13919 SourceLocation ImportLoc, 13920 ModuleIdPath Path) { 13921 Module *Mod = 13922 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 13923 /*IsIncludeDirective=*/false); 13924 if (!Mod) 13925 return true; 13926 13927 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13928 13929 // FIXME: we should support importing a submodule within a different submodule 13930 // of the same top-level module. Until we do, make it an error rather than 13931 // silently ignoring the import. 13932 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 13933 Diag(ImportLoc, diag::err_module_self_import) 13934 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 13935 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule) 13936 Diag(ImportLoc, diag::err_module_import_in_implementation) 13937 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule; 13938 13939 SmallVector<SourceLocation, 2> IdentifierLocs; 13940 Module *ModCheck = Mod; 13941 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13942 // If we've run out of module parents, just drop the remaining identifiers. 13943 // We need the length to be consistent. 13944 if (!ModCheck) 13945 break; 13946 ModCheck = ModCheck->Parent; 13947 13948 IdentifierLocs.push_back(Path[I].second); 13949 } 13950 13951 ImportDecl *Import = ImportDecl::Create(Context, 13952 Context.getTranslationUnitDecl(), 13953 AtLoc.isValid()? AtLoc : ImportLoc, 13954 Mod, IdentifierLocs); 13955 Context.getTranslationUnitDecl()->addDecl(Import); 13956 return Import; 13957 } 13958 13959 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13960 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13961 13962 // FIXME: Should we synthesize an ImportDecl here? 13963 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13964 /*Complain=*/true); 13965 } 13966 13967 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 13968 Module *Mod) { 13969 // Bail if we're not allowed to implicitly import a module here. 13970 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 13971 return; 13972 13973 // Create the implicit import declaration. 13974 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13975 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13976 Loc, Mod, Loc); 13977 TU->addDecl(ImportD); 13978 Consumer.HandleImplicitImportDecl(ImportD); 13979 13980 // Make the module visible. 13981 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13982 /*Complain=*/false); 13983 } 13984 13985 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13986 IdentifierInfo* AliasName, 13987 SourceLocation PragmaLoc, 13988 SourceLocation NameLoc, 13989 SourceLocation AliasNameLoc) { 13990 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13991 LookupOrdinaryName); 13992 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13993 AliasName->getName(), 0); 13994 13995 if (PrevDecl) 13996 PrevDecl->addAttr(Attr); 13997 else 13998 (void)ExtnameUndeclaredIdentifiers.insert( 13999 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 14000 } 14001 14002 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 14003 SourceLocation PragmaLoc, 14004 SourceLocation NameLoc) { 14005 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 14006 14007 if (PrevDecl) { 14008 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 14009 } else { 14010 (void)WeakUndeclaredIdentifiers.insert( 14011 std::pair<IdentifierInfo*,WeakInfo> 14012 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 14013 } 14014 } 14015 14016 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 14017 IdentifierInfo* AliasName, 14018 SourceLocation PragmaLoc, 14019 SourceLocation NameLoc, 14020 SourceLocation AliasNameLoc) { 14021 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 14022 LookupOrdinaryName); 14023 WeakInfo W = WeakInfo(Name, NameLoc); 14024 14025 if (PrevDecl) { 14026 if (!PrevDecl->hasAttr<AliasAttr>()) 14027 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 14028 DeclApplyPragmaWeak(TUScope, ND, W); 14029 } else { 14030 (void)WeakUndeclaredIdentifiers.insert( 14031 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 14032 } 14033 } 14034 14035 Decl *Sema::getObjCDeclContext() const { 14036 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 14037 } 14038 14039 AvailabilityResult Sema::getCurContextAvailability() const { 14040 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 14041 if (!D) 14042 return AR_Available; 14043 14044 // If we are within an Objective-C method, we should consult 14045 // both the availability of the method as well as the 14046 // enclosing class. If the class is (say) deprecated, 14047 // the entire method is considered deprecated from the 14048 // purpose of checking if the current context is deprecated. 14049 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 14050 AvailabilityResult R = MD->getAvailability(); 14051 if (R != AR_Available) 14052 return R; 14053 D = MD->getClassInterface(); 14054 } 14055 // If we are within an Objective-c @implementation, it 14056 // gets the same availability context as the @interface. 14057 else if (const ObjCImplementationDecl *ID = 14058 dyn_cast<ObjCImplementationDecl>(D)) { 14059 D = ID->getClassInterface(); 14060 } 14061 // Recover from user error. 14062 return D ? D->getAvailability() : AR_Available; 14063 } 14064