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 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1085 Decl *D) { 1086 // Unlike PushDeclContext, the context to which we return is not necessarily 1087 // the containing DC of TD, because the new context will be some pre-existing 1088 // TagDecl definition instead of a fresh one. 1089 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1090 CurContext = cast<TagDecl>(D)->getDefinition(); 1091 assert(CurContext && "skipping definition of undefined tag"); 1092 S->setEntity(CurContext); 1093 return Result; 1094 } 1095 1096 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1097 CurContext = static_cast<decltype(CurContext)>(Context); 1098 } 1099 1100 /// EnterDeclaratorContext - Used when we must lookup names in the context 1101 /// of a declarator's nested name specifier. 1102 /// 1103 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1104 // C++0x [basic.lookup.unqual]p13: 1105 // A name used in the definition of a static data member of class 1106 // X (after the qualified-id of the static member) is looked up as 1107 // if the name was used in a member function of X. 1108 // C++0x [basic.lookup.unqual]p14: 1109 // If a variable member of a namespace is defined outside of the 1110 // scope of its namespace then any name used in the definition of 1111 // the variable member (after the declarator-id) is looked up as 1112 // if the definition of the variable member occurred in its 1113 // namespace. 1114 // Both of these imply that we should push a scope whose context 1115 // is the semantic context of the declaration. We can't use 1116 // PushDeclContext here because that context is not necessarily 1117 // lexically contained in the current context. Fortunately, 1118 // the containing scope should have the appropriate information. 1119 1120 assert(!S->getEntity() && "scope already has entity"); 1121 1122 #ifndef NDEBUG 1123 Scope *Ancestor = S->getParent(); 1124 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1125 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1126 #endif 1127 1128 CurContext = DC; 1129 S->setEntity(DC); 1130 } 1131 1132 void Sema::ExitDeclaratorContext(Scope *S) { 1133 assert(S->getEntity() == CurContext && "Context imbalance!"); 1134 1135 // Switch back to the lexical context. The safety of this is 1136 // enforced by an assert in EnterDeclaratorContext. 1137 Scope *Ancestor = S->getParent(); 1138 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1139 CurContext = Ancestor->getEntity(); 1140 1141 // We don't need to do anything with the scope, which is going to 1142 // disappear. 1143 } 1144 1145 1146 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1147 // We assume that the caller has already called 1148 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1149 FunctionDecl *FD = D->getAsFunction(); 1150 if (!FD) 1151 return; 1152 1153 // Same implementation as PushDeclContext, but enters the context 1154 // from the lexical parent, rather than the top-level class. 1155 assert(CurContext == FD->getLexicalParent() && 1156 "The next DeclContext should be lexically contained in the current one."); 1157 CurContext = FD; 1158 S->setEntity(CurContext); 1159 1160 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1161 ParmVarDecl *Param = FD->getParamDecl(P); 1162 // If the parameter has an identifier, then add it to the scope 1163 if (Param->getIdentifier()) { 1164 S->AddDecl(Param); 1165 IdResolver.AddDecl(Param); 1166 } 1167 } 1168 } 1169 1170 1171 void Sema::ActOnExitFunctionContext() { 1172 // Same implementation as PopDeclContext, but returns to the lexical parent, 1173 // rather than the top-level class. 1174 assert(CurContext && "DeclContext imbalance!"); 1175 CurContext = CurContext->getLexicalParent(); 1176 assert(CurContext && "Popped translation unit!"); 1177 } 1178 1179 1180 /// \brief Determine whether we allow overloading of the function 1181 /// PrevDecl with another declaration. 1182 /// 1183 /// This routine determines whether overloading is possible, not 1184 /// whether some new function is actually an overload. It will return 1185 /// true in C++ (where we can always provide overloads) or, as an 1186 /// extension, in C when the previous function is already an 1187 /// overloaded function declaration or has the "overloadable" 1188 /// attribute. 1189 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1190 ASTContext &Context) { 1191 if (Context.getLangOpts().CPlusPlus) 1192 return true; 1193 1194 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1195 return true; 1196 1197 return (Previous.getResultKind() == LookupResult::Found 1198 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1199 } 1200 1201 /// Add this decl to the scope shadowed decl chains. 1202 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1203 // Move up the scope chain until we find the nearest enclosing 1204 // non-transparent context. The declaration will be introduced into this 1205 // scope. 1206 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1207 S = S->getParent(); 1208 1209 // Add scoped declarations into their context, so that they can be 1210 // found later. Declarations without a context won't be inserted 1211 // into any context. 1212 if (AddToContext) 1213 CurContext->addDecl(D); 1214 1215 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1216 // are function-local declarations. 1217 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1218 !D->getDeclContext()->getRedeclContext()->Equals( 1219 D->getLexicalDeclContext()->getRedeclContext()) && 1220 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1221 return; 1222 1223 // Template instantiations should also not be pushed into scope. 1224 if (isa<FunctionDecl>(D) && 1225 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1226 return; 1227 1228 // If this replaces anything in the current scope, 1229 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1230 IEnd = IdResolver.end(); 1231 for (; I != IEnd; ++I) { 1232 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1233 S->RemoveDecl(*I); 1234 IdResolver.RemoveDecl(*I); 1235 1236 // Should only need to replace one decl. 1237 break; 1238 } 1239 } 1240 1241 S->AddDecl(D); 1242 1243 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1244 // Implicitly-generated labels may end up getting generated in an order that 1245 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1246 // the label at the appropriate place in the identifier chain. 1247 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1248 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1249 if (IDC == CurContext) { 1250 if (!S->isDeclScope(*I)) 1251 continue; 1252 } else if (IDC->Encloses(CurContext)) 1253 break; 1254 } 1255 1256 IdResolver.InsertDeclAfter(I, D); 1257 } else { 1258 IdResolver.AddDecl(D); 1259 } 1260 } 1261 1262 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1263 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1264 TUScope->AddDecl(D); 1265 } 1266 1267 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1268 bool AllowInlineNamespace) { 1269 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1270 } 1271 1272 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1273 DeclContext *TargetDC = DC->getPrimaryContext(); 1274 do { 1275 if (DeclContext *ScopeDC = S->getEntity()) 1276 if (ScopeDC->getPrimaryContext() == TargetDC) 1277 return S; 1278 } while ((S = S->getParent())); 1279 1280 return nullptr; 1281 } 1282 1283 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1284 DeclContext*, 1285 ASTContext&); 1286 1287 /// Filters out lookup results that don't fall within the given scope 1288 /// as determined by isDeclInScope. 1289 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1290 bool ConsiderLinkage, 1291 bool AllowInlineNamespace) { 1292 LookupResult::Filter F = R.makeFilter(); 1293 while (F.hasNext()) { 1294 NamedDecl *D = F.next(); 1295 1296 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1297 continue; 1298 1299 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1300 continue; 1301 1302 F.erase(); 1303 } 1304 1305 F.done(); 1306 } 1307 1308 static bool isUsingDecl(NamedDecl *D) { 1309 return isa<UsingShadowDecl>(D) || 1310 isa<UnresolvedUsingTypenameDecl>(D) || 1311 isa<UnresolvedUsingValueDecl>(D); 1312 } 1313 1314 /// Removes using shadow declarations from the lookup results. 1315 static void RemoveUsingDecls(LookupResult &R) { 1316 LookupResult::Filter F = R.makeFilter(); 1317 while (F.hasNext()) 1318 if (isUsingDecl(F.next())) 1319 F.erase(); 1320 1321 F.done(); 1322 } 1323 1324 /// \brief Check for this common pattern: 1325 /// @code 1326 /// class S { 1327 /// S(const S&); // DO NOT IMPLEMENT 1328 /// void operator=(const S&); // DO NOT IMPLEMENT 1329 /// }; 1330 /// @endcode 1331 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1332 // FIXME: Should check for private access too but access is set after we get 1333 // the decl here. 1334 if (D->doesThisDeclarationHaveABody()) 1335 return false; 1336 1337 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1338 return CD->isCopyConstructor(); 1339 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1340 return Method->isCopyAssignmentOperator(); 1341 return false; 1342 } 1343 1344 // We need this to handle 1345 // 1346 // typedef struct { 1347 // void *foo() { return 0; } 1348 // } A; 1349 // 1350 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1351 // for example. If 'A', foo will have external linkage. If we have '*A', 1352 // foo will have no linkage. Since we can't know until we get to the end 1353 // of the typedef, this function finds out if D might have non-external linkage. 1354 // Callers should verify at the end of the TU if it D has external linkage or 1355 // not. 1356 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1357 const DeclContext *DC = D->getDeclContext(); 1358 while (!DC->isTranslationUnit()) { 1359 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1360 if (!RD->hasNameForLinkage()) 1361 return true; 1362 } 1363 DC = DC->getParent(); 1364 } 1365 1366 return !D->isExternallyVisible(); 1367 } 1368 1369 // FIXME: This needs to be refactored; some other isInMainFile users want 1370 // these semantics. 1371 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1372 if (S.TUKind != TU_Complete) 1373 return false; 1374 return S.SourceMgr.isInMainFile(Loc); 1375 } 1376 1377 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1378 assert(D); 1379 1380 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1381 return false; 1382 1383 // Ignore all entities declared within templates, and out-of-line definitions 1384 // of members of class templates. 1385 if (D->getDeclContext()->isDependentContext() || 1386 D->getLexicalDeclContext()->isDependentContext()) 1387 return false; 1388 1389 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1390 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1391 return false; 1392 1393 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1394 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1395 return false; 1396 } else { 1397 // 'static inline' functions are defined in headers; don't warn. 1398 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1399 return false; 1400 } 1401 1402 if (FD->doesThisDeclarationHaveABody() && 1403 Context.DeclMustBeEmitted(FD)) 1404 return false; 1405 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1406 // Constants and utility variables are defined in headers with internal 1407 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1408 // like "inline".) 1409 if (!isMainFileLoc(*this, VD->getLocation())) 1410 return false; 1411 1412 if (Context.DeclMustBeEmitted(VD)) 1413 return false; 1414 1415 if (VD->isStaticDataMember() && 1416 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1417 return false; 1418 } else { 1419 return false; 1420 } 1421 1422 // Only warn for unused decls internal to the translation unit. 1423 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1424 // for inline functions defined in the main source file, for instance. 1425 return mightHaveNonExternalLinkage(D); 1426 } 1427 1428 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1429 if (!D) 1430 return; 1431 1432 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1433 const FunctionDecl *First = FD->getFirstDecl(); 1434 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1435 return; // First should already be in the vector. 1436 } 1437 1438 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1439 const VarDecl *First = VD->getFirstDecl(); 1440 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1441 return; // First should already be in the vector. 1442 } 1443 1444 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1445 UnusedFileScopedDecls.push_back(D); 1446 } 1447 1448 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1449 if (D->isInvalidDecl()) 1450 return false; 1451 1452 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1453 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1454 return false; 1455 1456 if (isa<LabelDecl>(D)) 1457 return true; 1458 1459 // Except for labels, we only care about unused decls that are local to 1460 // functions. 1461 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1462 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1463 // For dependent types, the diagnostic is deferred. 1464 WithinFunction = 1465 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1466 if (!WithinFunction) 1467 return false; 1468 1469 if (isa<TypedefNameDecl>(D)) 1470 return true; 1471 1472 // White-list anything that isn't a local variable. 1473 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1474 return false; 1475 1476 // Types of valid local variables should be complete, so this should succeed. 1477 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1478 1479 // White-list anything with an __attribute__((unused)) type. 1480 QualType Ty = VD->getType(); 1481 1482 // Only look at the outermost level of typedef. 1483 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1484 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1485 return false; 1486 } 1487 1488 // If we failed to complete the type for some reason, or if the type is 1489 // dependent, don't diagnose the variable. 1490 if (Ty->isIncompleteType() || Ty->isDependentType()) 1491 return false; 1492 1493 if (const TagType *TT = Ty->getAs<TagType>()) { 1494 const TagDecl *Tag = TT->getDecl(); 1495 if (Tag->hasAttr<UnusedAttr>()) 1496 return false; 1497 1498 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1499 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1500 return false; 1501 1502 if (const Expr *Init = VD->getInit()) { 1503 if (const ExprWithCleanups *Cleanups = 1504 dyn_cast<ExprWithCleanups>(Init)) 1505 Init = Cleanups->getSubExpr(); 1506 const CXXConstructExpr *Construct = 1507 dyn_cast<CXXConstructExpr>(Init); 1508 if (Construct && !Construct->isElidable()) { 1509 CXXConstructorDecl *CD = Construct->getConstructor(); 1510 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1511 return false; 1512 } 1513 } 1514 } 1515 } 1516 1517 // TODO: __attribute__((unused)) templates? 1518 } 1519 1520 return true; 1521 } 1522 1523 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1524 FixItHint &Hint) { 1525 if (isa<LabelDecl>(D)) { 1526 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1527 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1528 if (AfterColon.isInvalid()) 1529 return; 1530 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1531 getCharRange(D->getLocStart(), AfterColon)); 1532 } 1533 return; 1534 } 1535 1536 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1537 if (D->getTypeForDecl()->isDependentType()) 1538 return; 1539 1540 for (auto *TmpD : D->decls()) { 1541 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1542 DiagnoseUnusedDecl(T); 1543 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1544 DiagnoseUnusedNestedTypedefs(R); 1545 } 1546 } 1547 1548 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1549 /// unless they are marked attr(unused). 1550 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1551 if (!ShouldDiagnoseUnusedDecl(D)) 1552 return; 1553 1554 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1555 // typedefs can be referenced later on, so the diagnostics are emitted 1556 // at end-of-translation-unit. 1557 UnusedLocalTypedefNameCandidates.insert(TD); 1558 return; 1559 } 1560 1561 FixItHint Hint; 1562 GenerateFixForUnusedDecl(D, Context, Hint); 1563 1564 unsigned DiagID; 1565 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1566 DiagID = diag::warn_unused_exception_param; 1567 else if (isa<LabelDecl>(D)) 1568 DiagID = diag::warn_unused_label; 1569 else 1570 DiagID = diag::warn_unused_variable; 1571 1572 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1573 } 1574 1575 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1576 // Verify that we have no forward references left. If so, there was a goto 1577 // or address of a label taken, but no definition of it. Label fwd 1578 // definitions are indicated with a null substmt which is also not a resolved 1579 // MS inline assembly label name. 1580 bool Diagnose = false; 1581 if (L->isMSAsmLabel()) 1582 Diagnose = !L->isResolvedMSAsmLabel(); 1583 else 1584 Diagnose = L->getStmt() == nullptr; 1585 if (Diagnose) 1586 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1587 } 1588 1589 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1590 S->mergeNRVOIntoParent(); 1591 1592 if (S->decl_empty()) return; 1593 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1594 "Scope shouldn't contain decls!"); 1595 1596 for (auto *TmpD : S->decls()) { 1597 assert(TmpD && "This decl didn't get pushed??"); 1598 1599 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1600 NamedDecl *D = cast<NamedDecl>(TmpD); 1601 1602 if (!D->getDeclName()) continue; 1603 1604 // Diagnose unused variables in this scope. 1605 if (!S->hasUnrecoverableErrorOccurred()) { 1606 DiagnoseUnusedDecl(D); 1607 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1608 DiagnoseUnusedNestedTypedefs(RD); 1609 } 1610 1611 // If this was a forward reference to a label, verify it was defined. 1612 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1613 CheckPoppedLabel(LD, *this); 1614 1615 // Remove this name from our lexical scope. 1616 IdResolver.RemoveDecl(D); 1617 } 1618 } 1619 1620 /// \brief Look for an Objective-C class in the translation unit. 1621 /// 1622 /// \param Id The name of the Objective-C class we're looking for. If 1623 /// typo-correction fixes this name, the Id will be updated 1624 /// to the fixed name. 1625 /// 1626 /// \param IdLoc The location of the name in the translation unit. 1627 /// 1628 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1629 /// if there is no class with the given name. 1630 /// 1631 /// \returns The declaration of the named Objective-C class, or NULL if the 1632 /// class could not be found. 1633 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1634 SourceLocation IdLoc, 1635 bool DoTypoCorrection) { 1636 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1637 // creation from this context. 1638 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1639 1640 if (!IDecl && DoTypoCorrection) { 1641 // Perform typo correction at the given location, but only if we 1642 // find an Objective-C class name. 1643 if (TypoCorrection C = CorrectTypo( 1644 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1645 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1646 CTK_ErrorRecovery)) { 1647 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1648 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1649 Id = IDecl->getIdentifier(); 1650 } 1651 } 1652 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1653 // This routine must always return a class definition, if any. 1654 if (Def && Def->getDefinition()) 1655 Def = Def->getDefinition(); 1656 return Def; 1657 } 1658 1659 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1660 /// from S, where a non-field would be declared. This routine copes 1661 /// with the difference between C and C++ scoping rules in structs and 1662 /// unions. For example, the following code is well-formed in C but 1663 /// ill-formed in C++: 1664 /// @code 1665 /// struct S6 { 1666 /// enum { BAR } e; 1667 /// }; 1668 /// 1669 /// void test_S6() { 1670 /// struct S6 a; 1671 /// a.e = BAR; 1672 /// } 1673 /// @endcode 1674 /// For the declaration of BAR, this routine will return a different 1675 /// scope. The scope S will be the scope of the unnamed enumeration 1676 /// within S6. In C++, this routine will return the scope associated 1677 /// with S6, because the enumeration's scope is a transparent 1678 /// context but structures can contain non-field names. In C, this 1679 /// routine will return the translation unit scope, since the 1680 /// enumeration's scope is a transparent context and structures cannot 1681 /// contain non-field names. 1682 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1683 while (((S->getFlags() & Scope::DeclScope) == 0) || 1684 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1685 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1686 S = S->getParent(); 1687 return S; 1688 } 1689 1690 /// \brief Looks up the declaration of "struct objc_super" and 1691 /// saves it for later use in building builtin declaration of 1692 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1693 /// pre-existing declaration exists no action takes place. 1694 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1695 IdentifierInfo *II) { 1696 if (!II->isStr("objc_msgSendSuper")) 1697 return; 1698 ASTContext &Context = ThisSema.Context; 1699 1700 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1701 SourceLocation(), Sema::LookupTagName); 1702 ThisSema.LookupName(Result, S); 1703 if (Result.getResultKind() == LookupResult::Found) 1704 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1705 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1706 } 1707 1708 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1709 switch (Error) { 1710 case ASTContext::GE_None: 1711 return ""; 1712 case ASTContext::GE_Missing_stdio: 1713 return "stdio.h"; 1714 case ASTContext::GE_Missing_setjmp: 1715 return "setjmp.h"; 1716 case ASTContext::GE_Missing_ucontext: 1717 return "ucontext.h"; 1718 } 1719 llvm_unreachable("unhandled error kind"); 1720 } 1721 1722 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1723 /// file scope. lazily create a decl for it. ForRedeclaration is true 1724 /// if we're creating this built-in in anticipation of redeclaring the 1725 /// built-in. 1726 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1727 Scope *S, bool ForRedeclaration, 1728 SourceLocation Loc) { 1729 LookupPredefedObjCSuperType(*this, S, II); 1730 1731 ASTContext::GetBuiltinTypeError Error; 1732 QualType R = Context.GetBuiltinType(ID, Error); 1733 if (Error) { 1734 if (ForRedeclaration) 1735 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1736 << getHeaderName(Error) 1737 << Context.BuiltinInfo.GetName(ID); 1738 return nullptr; 1739 } 1740 1741 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1742 Diag(Loc, diag::ext_implicit_lib_function_decl) 1743 << Context.BuiltinInfo.GetName(ID) 1744 << R; 1745 if (Context.BuiltinInfo.getHeaderName(ID) && 1746 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1747 Diag(Loc, diag::note_include_header_or_declare) 1748 << Context.BuiltinInfo.getHeaderName(ID) 1749 << Context.BuiltinInfo.GetName(ID); 1750 } 1751 1752 DeclContext *Parent = Context.getTranslationUnitDecl(); 1753 if (getLangOpts().CPlusPlus) { 1754 LinkageSpecDecl *CLinkageDecl = 1755 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1756 LinkageSpecDecl::lang_c, false); 1757 CLinkageDecl->setImplicit(); 1758 Parent->addDecl(CLinkageDecl); 1759 Parent = CLinkageDecl; 1760 } 1761 1762 FunctionDecl *New = FunctionDecl::Create(Context, 1763 Parent, 1764 Loc, Loc, II, R, /*TInfo=*/nullptr, 1765 SC_Extern, 1766 false, 1767 R->isFunctionProtoType()); 1768 New->setImplicit(); 1769 1770 // Create Decl objects for each parameter, adding them to the 1771 // FunctionDecl. 1772 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1773 SmallVector<ParmVarDecl*, 16> Params; 1774 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1775 ParmVarDecl *parm = 1776 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1777 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1778 SC_None, nullptr); 1779 parm->setScopeInfo(0, i); 1780 Params.push_back(parm); 1781 } 1782 New->setParams(Params); 1783 } 1784 1785 AddKnownFunctionAttributes(New); 1786 RegisterLocallyScopedExternCDecl(New, S); 1787 1788 // TUScope is the translation-unit scope to insert this function into. 1789 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1790 // relate Scopes to DeclContexts, and probably eliminate CurContext 1791 // entirely, but we're not there yet. 1792 DeclContext *SavedContext = CurContext; 1793 CurContext = Parent; 1794 PushOnScopeChains(New, TUScope); 1795 CurContext = SavedContext; 1796 return New; 1797 } 1798 1799 /// \brief Filter out any previous declarations that the given declaration 1800 /// should not consider because they are not permitted to conflict, e.g., 1801 /// because they come from hidden sub-modules and do not refer to the same 1802 /// entity. 1803 static void filterNonConflictingPreviousDecls(Sema &S, 1804 NamedDecl *decl, 1805 LookupResult &previous){ 1806 // This is only interesting when modules are enabled. 1807 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1808 return; 1809 1810 // Empty sets are uninteresting. 1811 if (previous.empty()) 1812 return; 1813 1814 LookupResult::Filter filter = previous.makeFilter(); 1815 while (filter.hasNext()) { 1816 NamedDecl *old = filter.next(); 1817 1818 // Non-hidden declarations are never ignored. 1819 if (S.isVisible(old)) 1820 continue; 1821 1822 if (!old->isExternallyVisible()) 1823 filter.erase(); 1824 } 1825 1826 filter.done(); 1827 } 1828 1829 /// Typedef declarations don't have linkage, but they still denote the same 1830 /// entity if their types are the same. 1831 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1832 /// isSameEntity. 1833 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1834 TypedefNameDecl *Decl, 1835 LookupResult &Previous) { 1836 // This is only interesting when modules are enabled. 1837 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1838 return; 1839 1840 // Empty sets are uninteresting. 1841 if (Previous.empty()) 1842 return; 1843 1844 LookupResult::Filter Filter = Previous.makeFilter(); 1845 while (Filter.hasNext()) { 1846 NamedDecl *Old = Filter.next(); 1847 1848 // Non-hidden declarations are never ignored. 1849 if (S.isVisible(Old)) 1850 continue; 1851 1852 // Declarations of the same entity are not ignored, even if they have 1853 // different linkages. 1854 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1855 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1856 Decl->getUnderlyingType())) 1857 continue; 1858 1859 // If both declarations give a tag declaration a typedef name for linkage 1860 // purposes, then they declare the same entity. 1861 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1862 Decl->getAnonDeclWithTypedefName()) 1863 continue; 1864 } 1865 1866 if (!Old->isExternallyVisible()) 1867 Filter.erase(); 1868 } 1869 1870 Filter.done(); 1871 } 1872 1873 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1874 QualType OldType; 1875 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1876 OldType = OldTypedef->getUnderlyingType(); 1877 else 1878 OldType = Context.getTypeDeclType(Old); 1879 QualType NewType = New->getUnderlyingType(); 1880 1881 if (NewType->isVariablyModifiedType()) { 1882 // Must not redefine a typedef with a variably-modified type. 1883 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1884 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1885 << Kind << NewType; 1886 if (Old->getLocation().isValid()) 1887 Diag(Old->getLocation(), diag::note_previous_definition); 1888 New->setInvalidDecl(); 1889 return true; 1890 } 1891 1892 if (OldType != NewType && 1893 !OldType->isDependentType() && 1894 !NewType->isDependentType() && 1895 !Context.hasSameType(OldType, NewType)) { 1896 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1897 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1898 << Kind << NewType << OldType; 1899 if (Old->getLocation().isValid()) 1900 Diag(Old->getLocation(), diag::note_previous_definition); 1901 New->setInvalidDecl(); 1902 return true; 1903 } 1904 return false; 1905 } 1906 1907 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1908 /// same name and scope as a previous declaration 'Old'. Figure out 1909 /// how to resolve this situation, merging decls or emitting 1910 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1911 /// 1912 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1913 // If the new decl is known invalid already, don't bother doing any 1914 // merging checks. 1915 if (New->isInvalidDecl()) return; 1916 1917 // Allow multiple definitions for ObjC built-in typedefs. 1918 // FIXME: Verify the underlying types are equivalent! 1919 if (getLangOpts().ObjC1) { 1920 const IdentifierInfo *TypeID = New->getIdentifier(); 1921 switch (TypeID->getLength()) { 1922 default: break; 1923 case 2: 1924 { 1925 if (!TypeID->isStr("id")) 1926 break; 1927 QualType T = New->getUnderlyingType(); 1928 if (!T->isPointerType()) 1929 break; 1930 if (!T->isVoidPointerType()) { 1931 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1932 if (!PT->isStructureType()) 1933 break; 1934 } 1935 Context.setObjCIdRedefinitionType(T); 1936 // Install the built-in type for 'id', ignoring the current definition. 1937 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1938 return; 1939 } 1940 case 5: 1941 if (!TypeID->isStr("Class")) 1942 break; 1943 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1944 // Install the built-in type for 'Class', ignoring the current definition. 1945 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1946 return; 1947 case 3: 1948 if (!TypeID->isStr("SEL")) 1949 break; 1950 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1951 // Install the built-in type for 'SEL', ignoring the current definition. 1952 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1953 return; 1954 } 1955 // Fall through - the typedef name was not a builtin type. 1956 } 1957 1958 // Verify the old decl was also a type. 1959 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1960 if (!Old) { 1961 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1962 << New->getDeclName(); 1963 1964 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1965 if (OldD->getLocation().isValid()) 1966 Diag(OldD->getLocation(), diag::note_previous_definition); 1967 1968 return New->setInvalidDecl(); 1969 } 1970 1971 // If the old declaration is invalid, just give up here. 1972 if (Old->isInvalidDecl()) 1973 return New->setInvalidDecl(); 1974 1975 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1976 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 1977 auto *NewTag = New->getAnonDeclWithTypedefName(); 1978 NamedDecl *Hidden = nullptr; 1979 if (getLangOpts().CPlusPlus && OldTag && NewTag && 1980 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 1981 !hasVisibleDefinition(OldTag, &Hidden)) { 1982 // There is a definition of this tag, but it is not visible. Use it 1983 // instead of our tag. 1984 New->setTypeForDecl(OldTD->getTypeForDecl()); 1985 if (OldTD->isModed()) 1986 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 1987 OldTD->getUnderlyingType()); 1988 else 1989 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 1990 1991 // Make the old tag definition visible. 1992 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 1993 } 1994 } 1995 1996 // If the typedef types are not identical, reject them in all languages and 1997 // with any extensions enabled. 1998 if (isIncompatibleTypedef(Old, New)) 1999 return; 2000 2001 // The types match. Link up the redeclaration chain and merge attributes if 2002 // the old declaration was a typedef. 2003 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2004 New->setPreviousDecl(Typedef); 2005 mergeDeclAttributes(New, Old); 2006 } 2007 2008 if (getLangOpts().MicrosoftExt) 2009 return; 2010 2011 if (getLangOpts().CPlusPlus) { 2012 // C++ [dcl.typedef]p2: 2013 // In a given non-class scope, a typedef specifier can be used to 2014 // redefine the name of any type declared in that scope to refer 2015 // to the type to which it already refers. 2016 if (!isa<CXXRecordDecl>(CurContext)) 2017 return; 2018 2019 // C++0x [dcl.typedef]p4: 2020 // In a given class scope, a typedef specifier can be used to redefine 2021 // any class-name declared in that scope that is not also a typedef-name 2022 // to refer to the type to which it already refers. 2023 // 2024 // This wording came in via DR424, which was a correction to the 2025 // wording in DR56, which accidentally banned code like: 2026 // 2027 // struct S { 2028 // typedef struct A { } A; 2029 // }; 2030 // 2031 // in the C++03 standard. We implement the C++0x semantics, which 2032 // allow the above but disallow 2033 // 2034 // struct S { 2035 // typedef int I; 2036 // typedef int I; 2037 // }; 2038 // 2039 // since that was the intent of DR56. 2040 if (!isa<TypedefNameDecl>(Old)) 2041 return; 2042 2043 Diag(New->getLocation(), diag::err_redefinition) 2044 << New->getDeclName(); 2045 Diag(Old->getLocation(), diag::note_previous_definition); 2046 return New->setInvalidDecl(); 2047 } 2048 2049 // Modules always permit redefinition of typedefs, as does C11. 2050 if (getLangOpts().Modules || getLangOpts().C11) 2051 return; 2052 2053 // If we have a redefinition of a typedef in C, emit a warning. This warning 2054 // is normally mapped to an error, but can be controlled with 2055 // -Wtypedef-redefinition. If either the original or the redefinition is 2056 // in a system header, don't emit this for compatibility with GCC. 2057 if (getDiagnostics().getSuppressSystemWarnings() && 2058 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2059 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2060 return; 2061 2062 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2063 << New->getDeclName(); 2064 Diag(Old->getLocation(), diag::note_previous_definition); 2065 } 2066 2067 /// DeclhasAttr - returns true if decl Declaration already has the target 2068 /// attribute. 2069 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2070 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2071 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2072 for (const auto *i : D->attrs()) 2073 if (i->getKind() == A->getKind()) { 2074 if (Ann) { 2075 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2076 return true; 2077 continue; 2078 } 2079 // FIXME: Don't hardcode this check 2080 if (OA && isa<OwnershipAttr>(i)) 2081 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2082 return true; 2083 } 2084 2085 return false; 2086 } 2087 2088 static bool isAttributeTargetADefinition(Decl *D) { 2089 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2090 return VD->isThisDeclarationADefinition(); 2091 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2092 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2093 return true; 2094 } 2095 2096 /// Merge alignment attributes from \p Old to \p New, taking into account the 2097 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2098 /// 2099 /// \return \c true if any attributes were added to \p New. 2100 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2101 // Look for alignas attributes on Old, and pick out whichever attribute 2102 // specifies the strictest alignment requirement. 2103 AlignedAttr *OldAlignasAttr = nullptr; 2104 AlignedAttr *OldStrictestAlignAttr = nullptr; 2105 unsigned OldAlign = 0; 2106 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2107 // FIXME: We have no way of representing inherited dependent alignments 2108 // in a case like: 2109 // template<int A, int B> struct alignas(A) X; 2110 // template<int A, int B> struct alignas(B) X {}; 2111 // For now, we just ignore any alignas attributes which are not on the 2112 // definition in such a case. 2113 if (I->isAlignmentDependent()) 2114 return false; 2115 2116 if (I->isAlignas()) 2117 OldAlignasAttr = I; 2118 2119 unsigned Align = I->getAlignment(S.Context); 2120 if (Align > OldAlign) { 2121 OldAlign = Align; 2122 OldStrictestAlignAttr = I; 2123 } 2124 } 2125 2126 // Look for alignas attributes on New. 2127 AlignedAttr *NewAlignasAttr = nullptr; 2128 unsigned NewAlign = 0; 2129 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2130 if (I->isAlignmentDependent()) 2131 return false; 2132 2133 if (I->isAlignas()) 2134 NewAlignasAttr = I; 2135 2136 unsigned Align = I->getAlignment(S.Context); 2137 if (Align > NewAlign) 2138 NewAlign = Align; 2139 } 2140 2141 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2142 // Both declarations have 'alignas' attributes. We require them to match. 2143 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2144 // fall short. (If two declarations both have alignas, they must both match 2145 // every definition, and so must match each other if there is a definition.) 2146 2147 // If either declaration only contains 'alignas(0)' specifiers, then it 2148 // specifies the natural alignment for the type. 2149 if (OldAlign == 0 || NewAlign == 0) { 2150 QualType Ty; 2151 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2152 Ty = VD->getType(); 2153 else 2154 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2155 2156 if (OldAlign == 0) 2157 OldAlign = S.Context.getTypeAlign(Ty); 2158 if (NewAlign == 0) 2159 NewAlign = S.Context.getTypeAlign(Ty); 2160 } 2161 2162 if (OldAlign != NewAlign) { 2163 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2164 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2165 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2166 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2167 } 2168 } 2169 2170 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2171 // C++11 [dcl.align]p6: 2172 // if any declaration of an entity has an alignment-specifier, 2173 // every defining declaration of that entity shall specify an 2174 // equivalent alignment. 2175 // C11 6.7.5/7: 2176 // If the definition of an object does not have an alignment 2177 // specifier, any other declaration of that object shall also 2178 // have no alignment specifier. 2179 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2180 << OldAlignasAttr; 2181 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2182 << OldAlignasAttr; 2183 } 2184 2185 bool AnyAdded = false; 2186 2187 // Ensure we have an attribute representing the strictest alignment. 2188 if (OldAlign > NewAlign) { 2189 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2190 Clone->setInherited(true); 2191 New->addAttr(Clone); 2192 AnyAdded = true; 2193 } 2194 2195 // Ensure we have an alignas attribute if the old declaration had one. 2196 if (OldAlignasAttr && !NewAlignasAttr && 2197 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2198 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2199 Clone->setInherited(true); 2200 New->addAttr(Clone); 2201 AnyAdded = true; 2202 } 2203 2204 return AnyAdded; 2205 } 2206 2207 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2208 const InheritableAttr *Attr, bool Override) { 2209 InheritableAttr *NewAttr = nullptr; 2210 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2211 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2212 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2213 AA->getIntroduced(), AA->getDeprecated(), 2214 AA->getObsoleted(), AA->getUnavailable(), 2215 AA->getMessage(), Override, 2216 AttrSpellingListIndex); 2217 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2218 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2219 AttrSpellingListIndex); 2220 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2221 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2222 AttrSpellingListIndex); 2223 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2224 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2225 AttrSpellingListIndex); 2226 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2227 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2228 AttrSpellingListIndex); 2229 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2230 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2231 FA->getFormatIdx(), FA->getFirstArg(), 2232 AttrSpellingListIndex); 2233 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2234 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2235 AttrSpellingListIndex); 2236 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2237 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2238 AttrSpellingListIndex, 2239 IA->getSemanticSpelling()); 2240 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2241 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2242 &S.Context.Idents.get(AA->getSpelling()), 2243 AttrSpellingListIndex); 2244 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2245 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2246 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2247 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2248 else if (isa<AlignedAttr>(Attr)) 2249 // AlignedAttrs are handled separately, because we need to handle all 2250 // such attributes on a declaration at the same time. 2251 NewAttr = nullptr; 2252 else if (isa<DeprecatedAttr>(Attr) && Override) 2253 NewAttr = nullptr; 2254 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2255 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2256 2257 if (NewAttr) { 2258 NewAttr->setInherited(true); 2259 D->addAttr(NewAttr); 2260 return true; 2261 } 2262 2263 return false; 2264 } 2265 2266 static const Decl *getDefinition(const Decl *D) { 2267 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2268 return TD->getDefinition(); 2269 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2270 const VarDecl *Def = VD->getDefinition(); 2271 if (Def) 2272 return Def; 2273 return VD->getActingDefinition(); 2274 } 2275 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2276 const FunctionDecl* Def; 2277 if (FD->isDefined(Def)) 2278 return Def; 2279 } 2280 return nullptr; 2281 } 2282 2283 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2284 for (const auto *Attribute : D->attrs()) 2285 if (Attribute->getKind() == Kind) 2286 return true; 2287 return false; 2288 } 2289 2290 /// checkNewAttributesAfterDef - If we already have a definition, check that 2291 /// there are no new attributes in this declaration. 2292 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2293 if (!New->hasAttrs()) 2294 return; 2295 2296 const Decl *Def = getDefinition(Old); 2297 if (!Def || Def == New) 2298 return; 2299 2300 AttrVec &NewAttributes = New->getAttrs(); 2301 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2302 const Attr *NewAttribute = NewAttributes[I]; 2303 2304 if (isa<AliasAttr>(NewAttribute)) { 2305 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2306 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2307 else { 2308 VarDecl *VD = cast<VarDecl>(New); 2309 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2310 VarDecl::TentativeDefinition 2311 ? diag::err_alias_after_tentative 2312 : diag::err_redefinition; 2313 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2314 S.Diag(Def->getLocation(), diag::note_previous_definition); 2315 VD->setInvalidDecl(); 2316 } 2317 ++I; 2318 continue; 2319 } 2320 2321 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2322 // Tentative definitions are only interesting for the alias check above. 2323 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2324 ++I; 2325 continue; 2326 } 2327 } 2328 2329 if (hasAttribute(Def, NewAttribute->getKind())) { 2330 ++I; 2331 continue; // regular attr merging will take care of validating this. 2332 } 2333 2334 if (isa<C11NoReturnAttr>(NewAttribute)) { 2335 // C's _Noreturn is allowed to be added to a function after it is defined. 2336 ++I; 2337 continue; 2338 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2339 if (AA->isAlignas()) { 2340 // C++11 [dcl.align]p6: 2341 // if any declaration of an entity has an alignment-specifier, 2342 // every defining declaration of that entity shall specify an 2343 // equivalent alignment. 2344 // C11 6.7.5/7: 2345 // If the definition of an object does not have an alignment 2346 // specifier, any other declaration of that object shall also 2347 // have no alignment specifier. 2348 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2349 << AA; 2350 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2351 << AA; 2352 NewAttributes.erase(NewAttributes.begin() + I); 2353 --E; 2354 continue; 2355 } 2356 } 2357 2358 S.Diag(NewAttribute->getLocation(), 2359 diag::warn_attribute_precede_definition); 2360 S.Diag(Def->getLocation(), diag::note_previous_definition); 2361 NewAttributes.erase(NewAttributes.begin() + I); 2362 --E; 2363 } 2364 } 2365 2366 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2367 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2368 AvailabilityMergeKind AMK) { 2369 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2370 UsedAttr *NewAttr = OldAttr->clone(Context); 2371 NewAttr->setInherited(true); 2372 New->addAttr(NewAttr); 2373 } 2374 2375 if (!Old->hasAttrs() && !New->hasAttrs()) 2376 return; 2377 2378 // attributes declared post-definition are currently ignored 2379 checkNewAttributesAfterDef(*this, New, Old); 2380 2381 if (!Old->hasAttrs()) 2382 return; 2383 2384 bool foundAny = New->hasAttrs(); 2385 2386 // Ensure that any moving of objects within the allocated map is done before 2387 // we process them. 2388 if (!foundAny) New->setAttrs(AttrVec()); 2389 2390 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2391 bool Override = false; 2392 // Ignore deprecated/unavailable/availability attributes if requested. 2393 if (isa<DeprecatedAttr>(I) || 2394 isa<UnavailableAttr>(I) || 2395 isa<AvailabilityAttr>(I)) { 2396 switch (AMK) { 2397 case AMK_None: 2398 continue; 2399 2400 case AMK_Redeclaration: 2401 break; 2402 2403 case AMK_Override: 2404 Override = true; 2405 break; 2406 } 2407 } 2408 2409 // Already handled. 2410 if (isa<UsedAttr>(I)) 2411 continue; 2412 2413 if (mergeDeclAttribute(*this, New, I, Override)) 2414 foundAny = true; 2415 } 2416 2417 if (mergeAlignedAttrs(*this, New, Old)) 2418 foundAny = true; 2419 2420 if (!foundAny) New->dropAttrs(); 2421 } 2422 2423 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2424 /// to the new one. 2425 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2426 const ParmVarDecl *oldDecl, 2427 Sema &S) { 2428 // C++11 [dcl.attr.depend]p2: 2429 // The first declaration of a function shall specify the 2430 // carries_dependency attribute for its declarator-id if any declaration 2431 // of the function specifies the carries_dependency attribute. 2432 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2433 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2434 S.Diag(CDA->getLocation(), 2435 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2436 // Find the first declaration of the parameter. 2437 // FIXME: Should we build redeclaration chains for function parameters? 2438 const FunctionDecl *FirstFD = 2439 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2440 const ParmVarDecl *FirstVD = 2441 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2442 S.Diag(FirstVD->getLocation(), 2443 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2444 } 2445 2446 if (!oldDecl->hasAttrs()) 2447 return; 2448 2449 bool foundAny = newDecl->hasAttrs(); 2450 2451 // Ensure that any moving of objects within the allocated map is 2452 // done before we process them. 2453 if (!foundAny) newDecl->setAttrs(AttrVec()); 2454 2455 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2456 if (!DeclHasAttr(newDecl, I)) { 2457 InheritableAttr *newAttr = 2458 cast<InheritableParamAttr>(I->clone(S.Context)); 2459 newAttr->setInherited(true); 2460 newDecl->addAttr(newAttr); 2461 foundAny = true; 2462 } 2463 } 2464 2465 if (!foundAny) newDecl->dropAttrs(); 2466 } 2467 2468 namespace { 2469 2470 /// Used in MergeFunctionDecl to keep track of function parameters in 2471 /// C. 2472 struct GNUCompatibleParamWarning { 2473 ParmVarDecl *OldParm; 2474 ParmVarDecl *NewParm; 2475 QualType PromotedType; 2476 }; 2477 2478 } 2479 2480 /// getSpecialMember - get the special member enum for a method. 2481 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2482 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2483 if (Ctor->isDefaultConstructor()) 2484 return Sema::CXXDefaultConstructor; 2485 2486 if (Ctor->isCopyConstructor()) 2487 return Sema::CXXCopyConstructor; 2488 2489 if (Ctor->isMoveConstructor()) 2490 return Sema::CXXMoveConstructor; 2491 } else if (isa<CXXDestructorDecl>(MD)) { 2492 return Sema::CXXDestructor; 2493 } else if (MD->isCopyAssignmentOperator()) { 2494 return Sema::CXXCopyAssignment; 2495 } else if (MD->isMoveAssignmentOperator()) { 2496 return Sema::CXXMoveAssignment; 2497 } 2498 2499 return Sema::CXXInvalid; 2500 } 2501 2502 // Determine whether the previous declaration was a definition, implicit 2503 // declaration, or a declaration. 2504 template <typename T> 2505 static std::pair<diag::kind, SourceLocation> 2506 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2507 diag::kind PrevDiag; 2508 SourceLocation OldLocation = Old->getLocation(); 2509 if (Old->isThisDeclarationADefinition()) 2510 PrevDiag = diag::note_previous_definition; 2511 else if (Old->isImplicit()) { 2512 PrevDiag = diag::note_previous_implicit_declaration; 2513 if (OldLocation.isInvalid()) 2514 OldLocation = New->getLocation(); 2515 } else 2516 PrevDiag = diag::note_previous_declaration; 2517 return std::make_pair(PrevDiag, OldLocation); 2518 } 2519 2520 /// canRedefineFunction - checks if a function can be redefined. Currently, 2521 /// only extern inline functions can be redefined, and even then only in 2522 /// GNU89 mode. 2523 static bool canRedefineFunction(const FunctionDecl *FD, 2524 const LangOptions& LangOpts) { 2525 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2526 !LangOpts.CPlusPlus && 2527 FD->isInlineSpecified() && 2528 FD->getStorageClass() == SC_Extern); 2529 } 2530 2531 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2532 const AttributedType *AT = T->getAs<AttributedType>(); 2533 while (AT && !AT->isCallingConv()) 2534 AT = AT->getModifiedType()->getAs<AttributedType>(); 2535 return AT; 2536 } 2537 2538 template <typename T> 2539 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2540 const DeclContext *DC = Old->getDeclContext(); 2541 if (DC->isRecord()) 2542 return false; 2543 2544 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2545 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2546 return true; 2547 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2548 return true; 2549 return false; 2550 } 2551 2552 /// MergeFunctionDecl - We just parsed a function 'New' from 2553 /// declarator D which has the same name and scope as a previous 2554 /// declaration 'Old'. Figure out how to resolve this situation, 2555 /// merging decls or emitting diagnostics as appropriate. 2556 /// 2557 /// In C++, New and Old must be declarations that are not 2558 /// overloaded. Use IsOverload to determine whether New and Old are 2559 /// overloaded, and to select the Old declaration that New should be 2560 /// merged with. 2561 /// 2562 /// Returns true if there was an error, false otherwise. 2563 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2564 Scope *S, bool MergeTypeWithOld) { 2565 // Verify the old decl was also a function. 2566 FunctionDecl *Old = OldD->getAsFunction(); 2567 if (!Old) { 2568 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2569 if (New->getFriendObjectKind()) { 2570 Diag(New->getLocation(), diag::err_using_decl_friend); 2571 Diag(Shadow->getTargetDecl()->getLocation(), 2572 diag::note_using_decl_target); 2573 Diag(Shadow->getUsingDecl()->getLocation(), 2574 diag::note_using_decl) << 0; 2575 return true; 2576 } 2577 2578 // C++11 [namespace.udecl]p14: 2579 // If a function declaration in namespace scope or block scope has the 2580 // same name and the same parameter-type-list as a function introduced 2581 // by a using-declaration, and the declarations do not declare the same 2582 // function, the program is ill-formed. 2583 2584 // Check whether the two declarations might declare the same function. 2585 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2586 if (Old && 2587 !Old->getDeclContext()->getRedeclContext()->Equals( 2588 New->getDeclContext()->getRedeclContext()) && 2589 !(Old->isExternC() && New->isExternC())) 2590 Old = nullptr; 2591 2592 if (!Old) { 2593 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2594 Diag(Shadow->getTargetDecl()->getLocation(), 2595 diag::note_using_decl_target); 2596 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2597 return true; 2598 } 2599 OldD = Old; 2600 } else { 2601 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2602 << New->getDeclName(); 2603 Diag(OldD->getLocation(), diag::note_previous_definition); 2604 return true; 2605 } 2606 } 2607 2608 // If the old declaration is invalid, just give up here. 2609 if (Old->isInvalidDecl()) 2610 return true; 2611 2612 diag::kind PrevDiag; 2613 SourceLocation OldLocation; 2614 std::tie(PrevDiag, OldLocation) = 2615 getNoteDiagForInvalidRedeclaration(Old, New); 2616 2617 // Don't complain about this if we're in GNU89 mode and the old function 2618 // is an extern inline function. 2619 // Don't complain about specializations. They are not supposed to have 2620 // storage classes. 2621 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2622 New->getStorageClass() == SC_Static && 2623 Old->hasExternalFormalLinkage() && 2624 !New->getTemplateSpecializationInfo() && 2625 !canRedefineFunction(Old, getLangOpts())) { 2626 if (getLangOpts().MicrosoftExt) { 2627 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2628 Diag(OldLocation, PrevDiag); 2629 } else { 2630 Diag(New->getLocation(), diag::err_static_non_static) << New; 2631 Diag(OldLocation, PrevDiag); 2632 return true; 2633 } 2634 } 2635 2636 2637 // If a function is first declared with a calling convention, but is later 2638 // declared or defined without one, all following decls assume the calling 2639 // convention of the first. 2640 // 2641 // It's OK if a function is first declared without a calling convention, 2642 // but is later declared or defined with the default calling convention. 2643 // 2644 // To test if either decl has an explicit calling convention, we look for 2645 // AttributedType sugar nodes on the type as written. If they are missing or 2646 // were canonicalized away, we assume the calling convention was implicit. 2647 // 2648 // Note also that we DO NOT return at this point, because we still have 2649 // other tests to run. 2650 QualType OldQType = Context.getCanonicalType(Old->getType()); 2651 QualType NewQType = Context.getCanonicalType(New->getType()); 2652 const FunctionType *OldType = cast<FunctionType>(OldQType); 2653 const FunctionType *NewType = cast<FunctionType>(NewQType); 2654 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2655 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2656 bool RequiresAdjustment = false; 2657 2658 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2659 FunctionDecl *First = Old->getFirstDecl(); 2660 const FunctionType *FT = 2661 First->getType().getCanonicalType()->castAs<FunctionType>(); 2662 FunctionType::ExtInfo FI = FT->getExtInfo(); 2663 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2664 if (!NewCCExplicit) { 2665 // Inherit the CC from the previous declaration if it was specified 2666 // there but not here. 2667 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2668 RequiresAdjustment = true; 2669 } else { 2670 // Calling conventions aren't compatible, so complain. 2671 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2672 Diag(New->getLocation(), diag::err_cconv_change) 2673 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2674 << !FirstCCExplicit 2675 << (!FirstCCExplicit ? "" : 2676 FunctionType::getNameForCallConv(FI.getCC())); 2677 2678 // Put the note on the first decl, since it is the one that matters. 2679 Diag(First->getLocation(), diag::note_previous_declaration); 2680 return true; 2681 } 2682 } 2683 2684 // FIXME: diagnose the other way around? 2685 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2686 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2687 RequiresAdjustment = true; 2688 } 2689 2690 // Merge regparm attribute. 2691 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2692 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2693 if (NewTypeInfo.getHasRegParm()) { 2694 Diag(New->getLocation(), diag::err_regparm_mismatch) 2695 << NewType->getRegParmType() 2696 << OldType->getRegParmType(); 2697 Diag(OldLocation, diag::note_previous_declaration); 2698 return true; 2699 } 2700 2701 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2702 RequiresAdjustment = true; 2703 } 2704 2705 // Merge ns_returns_retained attribute. 2706 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2707 if (NewTypeInfo.getProducesResult()) { 2708 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2709 Diag(OldLocation, diag::note_previous_declaration); 2710 return true; 2711 } 2712 2713 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2714 RequiresAdjustment = true; 2715 } 2716 2717 if (RequiresAdjustment) { 2718 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2719 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2720 New->setType(QualType(AdjustedType, 0)); 2721 NewQType = Context.getCanonicalType(New->getType()); 2722 NewType = cast<FunctionType>(NewQType); 2723 } 2724 2725 // If this redeclaration makes the function inline, we may need to add it to 2726 // UndefinedButUsed. 2727 if (!Old->isInlined() && New->isInlined() && 2728 !New->hasAttr<GNUInlineAttr>() && 2729 !getLangOpts().GNUInline && 2730 Old->isUsed(false) && 2731 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2732 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2733 SourceLocation())); 2734 2735 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2736 // about it. 2737 if (New->hasAttr<GNUInlineAttr>() && 2738 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2739 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2740 } 2741 2742 if (getLangOpts().CPlusPlus) { 2743 // (C++98 13.1p2): 2744 // Certain function declarations cannot be overloaded: 2745 // -- Function declarations that differ only in the return type 2746 // cannot be overloaded. 2747 2748 // Go back to the type source info to compare the declared return types, 2749 // per C++1y [dcl.type.auto]p13: 2750 // Redeclarations or specializations of a function or function template 2751 // with a declared return type that uses a placeholder type shall also 2752 // use that placeholder, not a deduced type. 2753 QualType OldDeclaredReturnType = 2754 (Old->getTypeSourceInfo() 2755 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2756 : OldType)->getReturnType(); 2757 QualType NewDeclaredReturnType = 2758 (New->getTypeSourceInfo() 2759 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2760 : NewType)->getReturnType(); 2761 QualType ResQT; 2762 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2763 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2764 New->isLocalExternDecl())) { 2765 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2766 OldDeclaredReturnType->isObjCObjectPointerType()) 2767 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2768 if (ResQT.isNull()) { 2769 if (New->isCXXClassMember() && New->isOutOfLine()) 2770 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2771 << New << New->getReturnTypeSourceRange(); 2772 else 2773 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2774 << New->getReturnTypeSourceRange(); 2775 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2776 << Old->getReturnTypeSourceRange(); 2777 return true; 2778 } 2779 else 2780 NewQType = ResQT; 2781 } 2782 2783 QualType OldReturnType = OldType->getReturnType(); 2784 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2785 if (OldReturnType != NewReturnType) { 2786 // If this function has a deduced return type and has already been 2787 // defined, copy the deduced value from the old declaration. 2788 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2789 if (OldAT && OldAT->isDeduced()) { 2790 New->setType( 2791 SubstAutoType(New->getType(), 2792 OldAT->isDependentType() ? Context.DependentTy 2793 : OldAT->getDeducedType())); 2794 NewQType = Context.getCanonicalType( 2795 SubstAutoType(NewQType, 2796 OldAT->isDependentType() ? Context.DependentTy 2797 : OldAT->getDeducedType())); 2798 } 2799 } 2800 2801 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2802 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2803 if (OldMethod && NewMethod) { 2804 // Preserve triviality. 2805 NewMethod->setTrivial(OldMethod->isTrivial()); 2806 2807 // MSVC allows explicit template specialization at class scope: 2808 // 2 CXXMethodDecls referring to the same function will be injected. 2809 // We don't want a redeclaration error. 2810 bool IsClassScopeExplicitSpecialization = 2811 OldMethod->isFunctionTemplateSpecialization() && 2812 NewMethod->isFunctionTemplateSpecialization(); 2813 bool isFriend = NewMethod->getFriendObjectKind(); 2814 2815 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2816 !IsClassScopeExplicitSpecialization) { 2817 // -- Member function declarations with the same name and the 2818 // same parameter types cannot be overloaded if any of them 2819 // is a static member function declaration. 2820 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2821 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2822 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2823 return true; 2824 } 2825 2826 // C++ [class.mem]p1: 2827 // [...] A member shall not be declared twice in the 2828 // member-specification, except that a nested class or member 2829 // class template can be declared and then later defined. 2830 if (ActiveTemplateInstantiations.empty()) { 2831 unsigned NewDiag; 2832 if (isa<CXXConstructorDecl>(OldMethod)) 2833 NewDiag = diag::err_constructor_redeclared; 2834 else if (isa<CXXDestructorDecl>(NewMethod)) 2835 NewDiag = diag::err_destructor_redeclared; 2836 else if (isa<CXXConversionDecl>(NewMethod)) 2837 NewDiag = diag::err_conv_function_redeclared; 2838 else 2839 NewDiag = diag::err_member_redeclared; 2840 2841 Diag(New->getLocation(), NewDiag); 2842 } else { 2843 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2844 << New << New->getType(); 2845 } 2846 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2847 return true; 2848 2849 // Complain if this is an explicit declaration of a special 2850 // member that was initially declared implicitly. 2851 // 2852 // As an exception, it's okay to befriend such methods in order 2853 // to permit the implicit constructor/destructor/operator calls. 2854 } else if (OldMethod->isImplicit()) { 2855 if (isFriend) { 2856 NewMethod->setImplicit(); 2857 } else { 2858 Diag(NewMethod->getLocation(), 2859 diag::err_definition_of_implicitly_declared_member) 2860 << New << getSpecialMember(OldMethod); 2861 return true; 2862 } 2863 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2864 Diag(NewMethod->getLocation(), 2865 diag::err_definition_of_explicitly_defaulted_member) 2866 << getSpecialMember(OldMethod); 2867 return true; 2868 } 2869 } 2870 2871 // C++11 [dcl.attr.noreturn]p1: 2872 // The first declaration of a function shall specify the noreturn 2873 // attribute if any declaration of that function specifies the noreturn 2874 // attribute. 2875 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2876 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2877 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2878 Diag(Old->getFirstDecl()->getLocation(), 2879 diag::note_noreturn_missing_first_decl); 2880 } 2881 2882 // C++11 [dcl.attr.depend]p2: 2883 // The first declaration of a function shall specify the 2884 // carries_dependency attribute for its declarator-id if any declaration 2885 // of the function specifies the carries_dependency attribute. 2886 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2887 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2888 Diag(CDA->getLocation(), 2889 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2890 Diag(Old->getFirstDecl()->getLocation(), 2891 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2892 } 2893 2894 // (C++98 8.3.5p3): 2895 // All declarations for a function shall agree exactly in both the 2896 // return type and the parameter-type-list. 2897 // We also want to respect all the extended bits except noreturn. 2898 2899 // noreturn should now match unless the old type info didn't have it. 2900 QualType OldQTypeForComparison = OldQType; 2901 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2902 assert(OldQType == QualType(OldType, 0)); 2903 const FunctionType *OldTypeForComparison 2904 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2905 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2906 assert(OldQTypeForComparison.isCanonical()); 2907 } 2908 2909 if (haveIncompatibleLanguageLinkages(Old, New)) { 2910 // As a special case, retain the language linkage from previous 2911 // declarations of a friend function as an extension. 2912 // 2913 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2914 // and is useful because there's otherwise no way to specify language 2915 // linkage within class scope. 2916 // 2917 // Check cautiously as the friend object kind isn't yet complete. 2918 if (New->getFriendObjectKind() != Decl::FOK_None) { 2919 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2920 Diag(OldLocation, PrevDiag); 2921 } else { 2922 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2923 Diag(OldLocation, PrevDiag); 2924 return true; 2925 } 2926 } 2927 2928 if (OldQTypeForComparison == NewQType) 2929 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2930 2931 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2932 New->isLocalExternDecl()) { 2933 // It's OK if we couldn't merge types for a local function declaraton 2934 // if either the old or new type is dependent. We'll merge the types 2935 // when we instantiate the function. 2936 return false; 2937 } 2938 2939 // Fall through for conflicting redeclarations and redefinitions. 2940 } 2941 2942 // C: Function types need to be compatible, not identical. This handles 2943 // duplicate function decls like "void f(int); void f(enum X);" properly. 2944 if (!getLangOpts().CPlusPlus && 2945 Context.typesAreCompatible(OldQType, NewQType)) { 2946 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2947 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2948 const FunctionProtoType *OldProto = nullptr; 2949 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2950 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2951 // The old declaration provided a function prototype, but the 2952 // new declaration does not. Merge in the prototype. 2953 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2954 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2955 NewQType = 2956 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2957 OldProto->getExtProtoInfo()); 2958 New->setType(NewQType); 2959 New->setHasInheritedPrototype(); 2960 2961 // Synthesize parameters with the same types. 2962 SmallVector<ParmVarDecl*, 16> Params; 2963 for (const auto &ParamType : OldProto->param_types()) { 2964 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2965 SourceLocation(), nullptr, 2966 ParamType, /*TInfo=*/nullptr, 2967 SC_None, nullptr); 2968 Param->setScopeInfo(0, Params.size()); 2969 Param->setImplicit(); 2970 Params.push_back(Param); 2971 } 2972 2973 New->setParams(Params); 2974 } 2975 2976 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2977 } 2978 2979 // GNU C permits a K&R definition to follow a prototype declaration 2980 // if the declared types of the parameters in the K&R definition 2981 // match the types in the prototype declaration, even when the 2982 // promoted types of the parameters from the K&R definition differ 2983 // from the types in the prototype. GCC then keeps the types from 2984 // the prototype. 2985 // 2986 // If a variadic prototype is followed by a non-variadic K&R definition, 2987 // the K&R definition becomes variadic. This is sort of an edge case, but 2988 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2989 // C99 6.9.1p8. 2990 if (!getLangOpts().CPlusPlus && 2991 Old->hasPrototype() && !New->hasPrototype() && 2992 New->getType()->getAs<FunctionProtoType>() && 2993 Old->getNumParams() == New->getNumParams()) { 2994 SmallVector<QualType, 16> ArgTypes; 2995 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2996 const FunctionProtoType *OldProto 2997 = Old->getType()->getAs<FunctionProtoType>(); 2998 const FunctionProtoType *NewProto 2999 = New->getType()->getAs<FunctionProtoType>(); 3000 3001 // Determine whether this is the GNU C extension. 3002 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3003 NewProto->getReturnType()); 3004 bool LooseCompatible = !MergedReturn.isNull(); 3005 for (unsigned Idx = 0, End = Old->getNumParams(); 3006 LooseCompatible && Idx != End; ++Idx) { 3007 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3008 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3009 if (Context.typesAreCompatible(OldParm->getType(), 3010 NewProto->getParamType(Idx))) { 3011 ArgTypes.push_back(NewParm->getType()); 3012 } else if (Context.typesAreCompatible(OldParm->getType(), 3013 NewParm->getType(), 3014 /*CompareUnqualified=*/true)) { 3015 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3016 NewProto->getParamType(Idx) }; 3017 Warnings.push_back(Warn); 3018 ArgTypes.push_back(NewParm->getType()); 3019 } else 3020 LooseCompatible = false; 3021 } 3022 3023 if (LooseCompatible) { 3024 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3025 Diag(Warnings[Warn].NewParm->getLocation(), 3026 diag::ext_param_promoted_not_compatible_with_prototype) 3027 << Warnings[Warn].PromotedType 3028 << Warnings[Warn].OldParm->getType(); 3029 if (Warnings[Warn].OldParm->getLocation().isValid()) 3030 Diag(Warnings[Warn].OldParm->getLocation(), 3031 diag::note_previous_declaration); 3032 } 3033 3034 if (MergeTypeWithOld) 3035 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3036 OldProto->getExtProtoInfo())); 3037 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3038 } 3039 3040 // Fall through to diagnose conflicting types. 3041 } 3042 3043 // A function that has already been declared has been redeclared or 3044 // defined with a different type; show an appropriate diagnostic. 3045 3046 // If the previous declaration was an implicitly-generated builtin 3047 // declaration, then at the very least we should use a specialized note. 3048 unsigned BuiltinID; 3049 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3050 // If it's actually a library-defined builtin function like 'malloc' 3051 // or 'printf', just warn about the incompatible redeclaration. 3052 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3053 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3054 Diag(OldLocation, diag::note_previous_builtin_declaration) 3055 << Old << Old->getType(); 3056 3057 // If this is a global redeclaration, just forget hereafter 3058 // about the "builtin-ness" of the function. 3059 // 3060 // Doing this for local extern declarations is problematic. If 3061 // the builtin declaration remains visible, a second invalid 3062 // local declaration will produce a hard error; if it doesn't 3063 // remain visible, a single bogus local redeclaration (which is 3064 // actually only a warning) could break all the downstream code. 3065 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3066 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 3067 3068 return false; 3069 } 3070 3071 PrevDiag = diag::note_previous_builtin_declaration; 3072 } 3073 3074 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3075 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3076 return true; 3077 } 3078 3079 /// \brief Completes the merge of two function declarations that are 3080 /// known to be compatible. 3081 /// 3082 /// This routine handles the merging of attributes and other 3083 /// properties of function declarations from the old declaration to 3084 /// the new declaration, once we know that New is in fact a 3085 /// redeclaration of Old. 3086 /// 3087 /// \returns false 3088 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3089 Scope *S, bool MergeTypeWithOld) { 3090 // Merge the attributes 3091 mergeDeclAttributes(New, Old); 3092 3093 // Merge "pure" flag. 3094 if (Old->isPure()) 3095 New->setPure(); 3096 3097 // Merge "used" flag. 3098 if (Old->getMostRecentDecl()->isUsed(false)) 3099 New->setIsUsed(); 3100 3101 // Merge attributes from the parameters. These can mismatch with K&R 3102 // declarations. 3103 if (New->getNumParams() == Old->getNumParams()) 3104 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 3105 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 3106 *this); 3107 3108 if (getLangOpts().CPlusPlus) 3109 return MergeCXXFunctionDecl(New, Old, S); 3110 3111 // Merge the function types so the we get the composite types for the return 3112 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3113 // was visible. 3114 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3115 if (!Merged.isNull() && MergeTypeWithOld) 3116 New->setType(Merged); 3117 3118 return false; 3119 } 3120 3121 3122 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3123 ObjCMethodDecl *oldMethod) { 3124 3125 // Merge the attributes, including deprecated/unavailable 3126 AvailabilityMergeKind MergeKind = 3127 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3128 : AMK_Override; 3129 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3130 3131 // Merge attributes from the parameters. 3132 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3133 oe = oldMethod->param_end(); 3134 for (ObjCMethodDecl::param_iterator 3135 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3136 ni != ne && oi != oe; ++ni, ++oi) 3137 mergeParamDeclAttributes(*ni, *oi, *this); 3138 3139 CheckObjCMethodOverride(newMethod, oldMethod); 3140 } 3141 3142 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3143 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3144 /// emitting diagnostics as appropriate. 3145 /// 3146 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3147 /// to here in AddInitializerToDecl. We can't check them before the initializer 3148 /// is attached. 3149 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3150 bool MergeTypeWithOld) { 3151 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3152 return; 3153 3154 QualType MergedT; 3155 if (getLangOpts().CPlusPlus) { 3156 if (New->getType()->isUndeducedType()) { 3157 // We don't know what the new type is until the initializer is attached. 3158 return; 3159 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3160 // These could still be something that needs exception specs checked. 3161 return MergeVarDeclExceptionSpecs(New, Old); 3162 } 3163 // C++ [basic.link]p10: 3164 // [...] the types specified by all declarations referring to a given 3165 // object or function shall be identical, except that declarations for an 3166 // array object can specify array types that differ by the presence or 3167 // absence of a major array bound (8.3.4). 3168 else if (Old->getType()->isIncompleteArrayType() && 3169 New->getType()->isArrayType()) { 3170 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3171 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3172 if (Context.hasSameType(OldArray->getElementType(), 3173 NewArray->getElementType())) 3174 MergedT = New->getType(); 3175 } else if (Old->getType()->isArrayType() && 3176 New->getType()->isIncompleteArrayType()) { 3177 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3178 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3179 if (Context.hasSameType(OldArray->getElementType(), 3180 NewArray->getElementType())) 3181 MergedT = Old->getType(); 3182 } else if (New->getType()->isObjCObjectPointerType() && 3183 Old->getType()->isObjCObjectPointerType()) { 3184 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3185 Old->getType()); 3186 } 3187 } else { 3188 // C 6.2.7p2: 3189 // All declarations that refer to the same object or function shall have 3190 // compatible type. 3191 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3192 } 3193 if (MergedT.isNull()) { 3194 // It's OK if we couldn't merge types if either type is dependent, for a 3195 // block-scope variable. In other cases (static data members of class 3196 // templates, variable templates, ...), we require the types to be 3197 // equivalent. 3198 // FIXME: The C++ standard doesn't say anything about this. 3199 if ((New->getType()->isDependentType() || 3200 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3201 // If the old type was dependent, we can't merge with it, so the new type 3202 // becomes dependent for now. We'll reproduce the original type when we 3203 // instantiate the TypeSourceInfo for the variable. 3204 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3205 New->setType(Context.DependentTy); 3206 return; 3207 } 3208 3209 // FIXME: Even if this merging succeeds, some other non-visible declaration 3210 // of this variable might have an incompatible type. For instance: 3211 // 3212 // extern int arr[]; 3213 // void f() { extern int arr[2]; } 3214 // void g() { extern int arr[3]; } 3215 // 3216 // Neither C nor C++ requires a diagnostic for this, but we should still try 3217 // to diagnose it. 3218 Diag(New->getLocation(), diag::err_redefinition_different_type) 3219 << New->getDeclName() << New->getType() << Old->getType(); 3220 Diag(Old->getLocation(), diag::note_previous_definition); 3221 return New->setInvalidDecl(); 3222 } 3223 3224 // Don't actually update the type on the new declaration if the old 3225 // declaration was an extern declaration in a different scope. 3226 if (MergeTypeWithOld) 3227 New->setType(MergedT); 3228 } 3229 3230 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3231 LookupResult &Previous) { 3232 // C11 6.2.7p4: 3233 // For an identifier with internal or external linkage declared 3234 // in a scope in which a prior declaration of that identifier is 3235 // visible, if the prior declaration specifies internal or 3236 // external linkage, the type of the identifier at the later 3237 // declaration becomes the composite type. 3238 // 3239 // If the variable isn't visible, we do not merge with its type. 3240 if (Previous.isShadowed()) 3241 return false; 3242 3243 if (S.getLangOpts().CPlusPlus) { 3244 // C++11 [dcl.array]p3: 3245 // If there is a preceding declaration of the entity in the same 3246 // scope in which the bound was specified, an omitted array bound 3247 // is taken to be the same as in that earlier declaration. 3248 return NewVD->isPreviousDeclInSameBlockScope() || 3249 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3250 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3251 } else { 3252 // If the old declaration was function-local, don't merge with its 3253 // type unless we're in the same function. 3254 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3255 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3256 } 3257 } 3258 3259 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3260 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3261 /// situation, merging decls or emitting diagnostics as appropriate. 3262 /// 3263 /// Tentative definition rules (C99 6.9.2p2) are checked by 3264 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3265 /// definitions here, since the initializer hasn't been attached. 3266 /// 3267 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3268 // If the new decl is already invalid, don't do any other checking. 3269 if (New->isInvalidDecl()) 3270 return; 3271 3272 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3273 3274 // Verify the old decl was also a variable or variable template. 3275 VarDecl *Old = nullptr; 3276 VarTemplateDecl *OldTemplate = nullptr; 3277 if (Previous.isSingleResult()) { 3278 if (NewTemplate) { 3279 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3280 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3281 } else 3282 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3283 } 3284 if (!Old) { 3285 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3286 << New->getDeclName(); 3287 Diag(Previous.getRepresentativeDecl()->getLocation(), 3288 diag::note_previous_definition); 3289 return New->setInvalidDecl(); 3290 } 3291 3292 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3293 return; 3294 3295 // Ensure the template parameters are compatible. 3296 if (NewTemplate && 3297 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3298 OldTemplate->getTemplateParameters(), 3299 /*Complain=*/true, TPL_TemplateMatch)) 3300 return; 3301 3302 // C++ [class.mem]p1: 3303 // A member shall not be declared twice in the member-specification [...] 3304 // 3305 // Here, we need only consider static data members. 3306 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3307 Diag(New->getLocation(), diag::err_duplicate_member) 3308 << New->getIdentifier(); 3309 Diag(Old->getLocation(), diag::note_previous_declaration); 3310 New->setInvalidDecl(); 3311 } 3312 3313 mergeDeclAttributes(New, Old); 3314 // Warn if an already-declared variable is made a weak_import in a subsequent 3315 // declaration 3316 if (New->hasAttr<WeakImportAttr>() && 3317 Old->getStorageClass() == SC_None && 3318 !Old->hasAttr<WeakImportAttr>()) { 3319 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3320 Diag(Old->getLocation(), diag::note_previous_definition); 3321 // Remove weak_import attribute on new declaration. 3322 New->dropAttr<WeakImportAttr>(); 3323 } 3324 3325 // Merge the types. 3326 VarDecl *MostRecent = Old->getMostRecentDecl(); 3327 if (MostRecent != Old) { 3328 MergeVarDeclTypes(New, MostRecent, 3329 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3330 if (New->isInvalidDecl()) 3331 return; 3332 } 3333 3334 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3335 if (New->isInvalidDecl()) 3336 return; 3337 3338 diag::kind PrevDiag; 3339 SourceLocation OldLocation; 3340 std::tie(PrevDiag, OldLocation) = 3341 getNoteDiagForInvalidRedeclaration(Old, New); 3342 3343 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3344 if (New->getStorageClass() == SC_Static && 3345 !New->isStaticDataMember() && 3346 Old->hasExternalFormalLinkage()) { 3347 if (getLangOpts().MicrosoftExt) { 3348 Diag(New->getLocation(), diag::ext_static_non_static) 3349 << New->getDeclName(); 3350 Diag(OldLocation, PrevDiag); 3351 } else { 3352 Diag(New->getLocation(), diag::err_static_non_static) 3353 << New->getDeclName(); 3354 Diag(OldLocation, PrevDiag); 3355 return New->setInvalidDecl(); 3356 } 3357 } 3358 // C99 6.2.2p4: 3359 // For an identifier declared with the storage-class specifier 3360 // extern in a scope in which a prior declaration of that 3361 // identifier is visible,23) if the prior declaration specifies 3362 // internal or external linkage, the linkage of the identifier at 3363 // the later declaration is the same as the linkage specified at 3364 // the prior declaration. If no prior declaration is visible, or 3365 // if the prior declaration specifies no linkage, then the 3366 // identifier has external linkage. 3367 if (New->hasExternalStorage() && Old->hasLinkage()) 3368 /* Okay */; 3369 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3370 !New->isStaticDataMember() && 3371 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3372 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3373 Diag(OldLocation, PrevDiag); 3374 return New->setInvalidDecl(); 3375 } 3376 3377 // Check if extern is followed by non-extern and vice-versa. 3378 if (New->hasExternalStorage() && 3379 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3380 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3381 Diag(OldLocation, PrevDiag); 3382 return New->setInvalidDecl(); 3383 } 3384 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3385 !New->hasExternalStorage()) { 3386 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3387 Diag(OldLocation, PrevDiag); 3388 return New->setInvalidDecl(); 3389 } 3390 3391 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3392 3393 // FIXME: The test for external storage here seems wrong? We still 3394 // need to check for mismatches. 3395 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3396 // Don't complain about out-of-line definitions of static members. 3397 !(Old->getLexicalDeclContext()->isRecord() && 3398 !New->getLexicalDeclContext()->isRecord())) { 3399 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3400 Diag(OldLocation, PrevDiag); 3401 return New->setInvalidDecl(); 3402 } 3403 3404 if (New->getTLSKind() != Old->getTLSKind()) { 3405 if (!Old->getTLSKind()) { 3406 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3407 Diag(OldLocation, PrevDiag); 3408 } else if (!New->getTLSKind()) { 3409 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3410 Diag(OldLocation, PrevDiag); 3411 } else { 3412 // Do not allow redeclaration to change the variable between requiring 3413 // static and dynamic initialization. 3414 // FIXME: GCC allows this, but uses the TLS keyword on the first 3415 // declaration to determine the kind. Do we need to be compatible here? 3416 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3417 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3418 Diag(OldLocation, PrevDiag); 3419 } 3420 } 3421 3422 // C++ doesn't have tentative definitions, so go right ahead and check here. 3423 VarDecl *Def; 3424 if (getLangOpts().CPlusPlus && 3425 New->isThisDeclarationADefinition() == VarDecl::Definition && 3426 (Def = Old->getDefinition())) { 3427 NamedDecl *Hidden = nullptr; 3428 if (!hasVisibleDefinition(Def, &Hidden) && 3429 (New->getDescribedVarTemplate() || 3430 New->getNumTemplateParameterLists() || 3431 New->getDeclContext()->isDependentContext())) { 3432 // The previous definition is hidden, and multiple definitions are 3433 // permitted (in separate TUs). Form another definition of it. 3434 } else { 3435 Diag(New->getLocation(), diag::err_redefinition) << New; 3436 Diag(Def->getLocation(), diag::note_previous_definition); 3437 New->setInvalidDecl(); 3438 return; 3439 } 3440 } 3441 3442 if (haveIncompatibleLanguageLinkages(Old, New)) { 3443 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3444 Diag(OldLocation, PrevDiag); 3445 New->setInvalidDecl(); 3446 return; 3447 } 3448 3449 // Merge "used" flag. 3450 if (Old->getMostRecentDecl()->isUsed(false)) 3451 New->setIsUsed(); 3452 3453 // Keep a chain of previous declarations. 3454 New->setPreviousDecl(Old); 3455 if (NewTemplate) 3456 NewTemplate->setPreviousDecl(OldTemplate); 3457 3458 // Inherit access appropriately. 3459 New->setAccess(Old->getAccess()); 3460 if (NewTemplate) 3461 NewTemplate->setAccess(New->getAccess()); 3462 } 3463 3464 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3465 /// no declarator (e.g. "struct foo;") is parsed. 3466 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3467 DeclSpec &DS) { 3468 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3469 } 3470 3471 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3472 // disambiguate entities defined in different scopes. 3473 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3474 // compatibility. 3475 // We will pick our mangling number depending on which version of MSVC is being 3476 // targeted. 3477 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3478 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3479 ? S->getMSCurManglingNumber() 3480 : S->getMSLastManglingNumber(); 3481 } 3482 3483 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3484 if (!Context.getLangOpts().CPlusPlus) 3485 return; 3486 3487 if (isa<CXXRecordDecl>(Tag->getParent())) { 3488 // If this tag is the direct child of a class, number it if 3489 // it is anonymous. 3490 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3491 return; 3492 MangleNumberingContext &MCtx = 3493 Context.getManglingNumberContext(Tag->getParent()); 3494 Context.setManglingNumber( 3495 Tag, MCtx.getManglingNumber( 3496 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3497 return; 3498 } 3499 3500 // If this tag isn't a direct child of a class, number it if it is local. 3501 Decl *ManglingContextDecl; 3502 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3503 Tag->getDeclContext(), ManglingContextDecl)) { 3504 Context.setManglingNumber( 3505 Tag, MCtx->getManglingNumber( 3506 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3507 } 3508 } 3509 3510 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3511 TypedefNameDecl *NewTD) { 3512 // Do nothing if the tag is not anonymous or already has an 3513 // associated typedef (from an earlier typedef in this decl group). 3514 if (TagFromDeclSpec->getIdentifier()) 3515 return; 3516 if (TagFromDeclSpec->getTypedefNameForAnonDecl()) 3517 return; 3518 3519 // A well-formed anonymous tag must always be a TUK_Definition. 3520 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3521 3522 // The type must match the tag exactly; no qualifiers allowed. 3523 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3524 Context.getTagDeclType(TagFromDeclSpec))) 3525 return; 3526 3527 // If we've already computed linkage for the anonymous tag, then 3528 // adding a typedef name for the anonymous decl can change that 3529 // linkage, which might be a serious problem. Diagnose this as 3530 // unsupported and ignore the typedef name. TODO: we should 3531 // pursue this as a language defect and establish a formal rule 3532 // for how to handle it. 3533 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3534 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3535 3536 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3537 tagLoc = getLocForEndOfToken(tagLoc); 3538 3539 llvm::SmallString<40> textToInsert; 3540 textToInsert += ' '; 3541 textToInsert += NewTD->getIdentifier()->getName(); 3542 Diag(tagLoc, diag::note_typedef_changes_linkage) 3543 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3544 return; 3545 } 3546 3547 // Otherwise, set this is the anon-decl typedef for the tag. 3548 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3549 } 3550 3551 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3552 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3553 /// parameters to cope with template friend declarations. 3554 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3555 DeclSpec &DS, 3556 MultiTemplateParamsArg TemplateParams, 3557 bool IsExplicitInstantiation) { 3558 Decl *TagD = nullptr; 3559 TagDecl *Tag = nullptr; 3560 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3561 DS.getTypeSpecType() == DeclSpec::TST_struct || 3562 DS.getTypeSpecType() == DeclSpec::TST_interface || 3563 DS.getTypeSpecType() == DeclSpec::TST_union || 3564 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3565 TagD = DS.getRepAsDecl(); 3566 3567 if (!TagD) // We probably had an error 3568 return nullptr; 3569 3570 // Note that the above type specs guarantee that the 3571 // type rep is a Decl, whereas in many of the others 3572 // it's a Type. 3573 if (isa<TagDecl>(TagD)) 3574 Tag = cast<TagDecl>(TagD); 3575 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3576 Tag = CTD->getTemplatedDecl(); 3577 } 3578 3579 if (Tag) { 3580 handleTagNumbering(Tag, S); 3581 Tag->setFreeStanding(); 3582 if (Tag->isInvalidDecl()) 3583 return Tag; 3584 } 3585 3586 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3587 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3588 // or incomplete types shall not be restrict-qualified." 3589 if (TypeQuals & DeclSpec::TQ_restrict) 3590 Diag(DS.getRestrictSpecLoc(), 3591 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3592 << DS.getSourceRange(); 3593 } 3594 3595 if (DS.isConstexprSpecified()) { 3596 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3597 // and definitions of functions and variables. 3598 if (Tag) 3599 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3600 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3601 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3602 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3603 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3604 else 3605 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3606 // Don't emit warnings after this error. 3607 return TagD; 3608 } 3609 3610 DiagnoseFunctionSpecifiers(DS); 3611 3612 if (DS.isFriendSpecified()) { 3613 // If we're dealing with a decl but not a TagDecl, assume that 3614 // whatever routines created it handled the friendship aspect. 3615 if (TagD && !Tag) 3616 return nullptr; 3617 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3618 } 3619 3620 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3621 bool IsExplicitSpecialization = 3622 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3623 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3624 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3625 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3626 // nested-name-specifier unless it is an explicit instantiation 3627 // or an explicit specialization. 3628 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3629 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3630 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3631 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3632 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3633 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3634 << SS.getRange(); 3635 return nullptr; 3636 } 3637 3638 // Track whether this decl-specifier declares anything. 3639 bool DeclaresAnything = true; 3640 3641 // Handle anonymous struct definitions. 3642 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3643 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3644 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3645 if (getLangOpts().CPlusPlus || 3646 Record->getDeclContext()->isRecord()) 3647 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3648 Context.getPrintingPolicy()); 3649 3650 DeclaresAnything = false; 3651 } 3652 } 3653 3654 // C11 6.7.2.1p2: 3655 // A struct-declaration that does not declare an anonymous structure or 3656 // anonymous union shall contain a struct-declarator-list. 3657 // 3658 // This rule also existed in C89 and C99; the grammar for struct-declaration 3659 // did not permit a struct-declaration without a struct-declarator-list. 3660 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3661 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3662 // Check for Microsoft C extension: anonymous struct/union member. 3663 // Handle 2 kinds of anonymous struct/union: 3664 // struct STRUCT; 3665 // union UNION; 3666 // and 3667 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3668 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3669 if ((Tag && Tag->getDeclName()) || 3670 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3671 RecordDecl *Record = nullptr; 3672 if (Tag) 3673 Record = dyn_cast<RecordDecl>(Tag); 3674 else if (const RecordType *RT = 3675 DS.getRepAsType().get()->getAsStructureType()) 3676 Record = RT->getDecl(); 3677 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3678 Record = UT->getDecl(); 3679 3680 if (Record && getLangOpts().MicrosoftExt) { 3681 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3682 << Record->isUnion() << DS.getSourceRange(); 3683 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3684 } 3685 3686 DeclaresAnything = false; 3687 } 3688 } 3689 3690 // Skip all the checks below if we have a type error. 3691 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3692 (TagD && TagD->isInvalidDecl())) 3693 return TagD; 3694 3695 if (getLangOpts().CPlusPlus && 3696 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3697 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3698 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3699 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3700 DeclaresAnything = false; 3701 3702 if (!DS.isMissingDeclaratorOk()) { 3703 // Customize diagnostic for a typedef missing a name. 3704 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3705 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3706 << DS.getSourceRange(); 3707 else 3708 DeclaresAnything = false; 3709 } 3710 3711 if (DS.isModulePrivateSpecified() && 3712 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3713 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3714 << Tag->getTagKind() 3715 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3716 3717 ActOnDocumentableDecl(TagD); 3718 3719 // C 6.7/2: 3720 // A declaration [...] shall declare at least a declarator [...], a tag, 3721 // or the members of an enumeration. 3722 // C++ [dcl.dcl]p3: 3723 // [If there are no declarators], and except for the declaration of an 3724 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3725 // names into the program, or shall redeclare a name introduced by a 3726 // previous declaration. 3727 if (!DeclaresAnything) { 3728 // In C, we allow this as a (popular) extension / bug. Don't bother 3729 // producing further diagnostics for redundant qualifiers after this. 3730 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3731 return TagD; 3732 } 3733 3734 // C++ [dcl.stc]p1: 3735 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3736 // init-declarator-list of the declaration shall not be empty. 3737 // C++ [dcl.fct.spec]p1: 3738 // If a cv-qualifier appears in a decl-specifier-seq, the 3739 // init-declarator-list of the declaration shall not be empty. 3740 // 3741 // Spurious qualifiers here appear to be valid in C. 3742 unsigned DiagID = diag::warn_standalone_specifier; 3743 if (getLangOpts().CPlusPlus) 3744 DiagID = diag::ext_standalone_specifier; 3745 3746 // Note that a linkage-specification sets a storage class, but 3747 // 'extern "C" struct foo;' is actually valid and not theoretically 3748 // useless. 3749 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3750 if (SCS == DeclSpec::SCS_mutable) 3751 // Since mutable is not a viable storage class specifier in C, there is 3752 // no reason to treat it as an extension. Instead, diagnose as an error. 3753 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3754 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3755 Diag(DS.getStorageClassSpecLoc(), DiagID) 3756 << DeclSpec::getSpecifierName(SCS); 3757 } 3758 3759 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3760 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3761 << DeclSpec::getSpecifierName(TSCS); 3762 if (DS.getTypeQualifiers()) { 3763 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3764 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3765 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3766 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3767 // Restrict is covered above. 3768 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3769 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3770 } 3771 3772 // Warn about ignored type attributes, for example: 3773 // __attribute__((aligned)) struct A; 3774 // Attributes should be placed after tag to apply to type declaration. 3775 if (!DS.getAttributes().empty()) { 3776 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3777 if (TypeSpecType == DeclSpec::TST_class || 3778 TypeSpecType == DeclSpec::TST_struct || 3779 TypeSpecType == DeclSpec::TST_interface || 3780 TypeSpecType == DeclSpec::TST_union || 3781 TypeSpecType == DeclSpec::TST_enum) { 3782 AttributeList* attrs = DS.getAttributes().getList(); 3783 while (attrs) { 3784 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3785 << attrs->getName() 3786 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3787 TypeSpecType == DeclSpec::TST_struct ? 1 : 3788 TypeSpecType == DeclSpec::TST_union ? 2 : 3789 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3790 attrs = attrs->getNext(); 3791 } 3792 } 3793 } 3794 3795 return TagD; 3796 } 3797 3798 /// We are trying to inject an anonymous member into the given scope; 3799 /// check if there's an existing declaration that can't be overloaded. 3800 /// 3801 /// \return true if this is a forbidden redeclaration 3802 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3803 Scope *S, 3804 DeclContext *Owner, 3805 DeclarationName Name, 3806 SourceLocation NameLoc, 3807 unsigned diagnostic) { 3808 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3809 Sema::ForRedeclaration); 3810 if (!SemaRef.LookupName(R, S)) return false; 3811 3812 if (R.getAsSingle<TagDecl>()) 3813 return false; 3814 3815 // Pick a representative declaration. 3816 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3817 assert(PrevDecl && "Expected a non-null Decl"); 3818 3819 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3820 return false; 3821 3822 SemaRef.Diag(NameLoc, diagnostic) << Name; 3823 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3824 3825 return true; 3826 } 3827 3828 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3829 /// anonymous struct or union AnonRecord into the owning context Owner 3830 /// and scope S. This routine will be invoked just after we realize 3831 /// that an unnamed union or struct is actually an anonymous union or 3832 /// struct, e.g., 3833 /// 3834 /// @code 3835 /// union { 3836 /// int i; 3837 /// float f; 3838 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3839 /// // f into the surrounding scope.x 3840 /// @endcode 3841 /// 3842 /// This routine is recursive, injecting the names of nested anonymous 3843 /// structs/unions into the owning context and scope as well. 3844 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3845 DeclContext *Owner, 3846 RecordDecl *AnonRecord, 3847 AccessSpecifier AS, 3848 SmallVectorImpl<NamedDecl *> &Chaining, 3849 bool MSAnonStruct) { 3850 unsigned diagKind 3851 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3852 : diag::err_anonymous_struct_member_redecl; 3853 3854 bool Invalid = false; 3855 3856 // Look every FieldDecl and IndirectFieldDecl with a name. 3857 for (auto *D : AnonRecord->decls()) { 3858 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3859 cast<NamedDecl>(D)->getDeclName()) { 3860 ValueDecl *VD = cast<ValueDecl>(D); 3861 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3862 VD->getLocation(), diagKind)) { 3863 // C++ [class.union]p2: 3864 // The names of the members of an anonymous union shall be 3865 // distinct from the names of any other entity in the 3866 // scope in which the anonymous union is declared. 3867 Invalid = true; 3868 } else { 3869 // C++ [class.union]p2: 3870 // For the purpose of name lookup, after the anonymous union 3871 // definition, the members of the anonymous union are 3872 // considered to have been defined in the scope in which the 3873 // anonymous union is declared. 3874 unsigned OldChainingSize = Chaining.size(); 3875 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3876 Chaining.append(IF->chain_begin(), IF->chain_end()); 3877 else 3878 Chaining.push_back(VD); 3879 3880 assert(Chaining.size() >= 2); 3881 NamedDecl **NamedChain = 3882 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3883 for (unsigned i = 0; i < Chaining.size(); i++) 3884 NamedChain[i] = Chaining[i]; 3885 3886 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 3887 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 3888 VD->getType(), NamedChain, Chaining.size()); 3889 3890 for (const auto *Attr : VD->attrs()) 3891 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 3892 3893 IndirectField->setAccess(AS); 3894 IndirectField->setImplicit(); 3895 SemaRef.PushOnScopeChains(IndirectField, S); 3896 3897 // That includes picking up the appropriate access specifier. 3898 if (AS != AS_none) IndirectField->setAccess(AS); 3899 3900 Chaining.resize(OldChainingSize); 3901 } 3902 } 3903 } 3904 3905 return Invalid; 3906 } 3907 3908 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3909 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3910 /// illegal input values are mapped to SC_None. 3911 static StorageClass 3912 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3913 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3914 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3915 "Parser allowed 'typedef' as storage class VarDecl."); 3916 switch (StorageClassSpec) { 3917 case DeclSpec::SCS_unspecified: return SC_None; 3918 case DeclSpec::SCS_extern: 3919 if (DS.isExternInLinkageSpec()) 3920 return SC_None; 3921 return SC_Extern; 3922 case DeclSpec::SCS_static: return SC_Static; 3923 case DeclSpec::SCS_auto: return SC_Auto; 3924 case DeclSpec::SCS_register: return SC_Register; 3925 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3926 // Illegal SCSs map to None: error reporting is up to the caller. 3927 case DeclSpec::SCS_mutable: // Fall through. 3928 case DeclSpec::SCS_typedef: return SC_None; 3929 } 3930 llvm_unreachable("unknown storage class specifier"); 3931 } 3932 3933 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3934 assert(Record->hasInClassInitializer()); 3935 3936 for (const auto *I : Record->decls()) { 3937 const auto *FD = dyn_cast<FieldDecl>(I); 3938 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3939 FD = IFD->getAnonField(); 3940 if (FD && FD->hasInClassInitializer()) 3941 return FD->getLocation(); 3942 } 3943 3944 llvm_unreachable("couldn't find in-class initializer"); 3945 } 3946 3947 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3948 SourceLocation DefaultInitLoc) { 3949 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3950 return; 3951 3952 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3953 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3954 } 3955 3956 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3957 CXXRecordDecl *AnonUnion) { 3958 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3959 return; 3960 3961 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3962 } 3963 3964 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3965 /// anonymous structure or union. Anonymous unions are a C++ feature 3966 /// (C++ [class.union]) and a C11 feature; anonymous structures 3967 /// are a C11 feature and GNU C++ extension. 3968 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3969 AccessSpecifier AS, 3970 RecordDecl *Record, 3971 const PrintingPolicy &Policy) { 3972 DeclContext *Owner = Record->getDeclContext(); 3973 3974 // Diagnose whether this anonymous struct/union is an extension. 3975 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3976 Diag(Record->getLocation(), diag::ext_anonymous_union); 3977 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3978 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3979 else if (!Record->isUnion() && !getLangOpts().C11) 3980 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3981 3982 // C and C++ require different kinds of checks for anonymous 3983 // structs/unions. 3984 bool Invalid = false; 3985 if (getLangOpts().CPlusPlus) { 3986 const char *PrevSpec = nullptr; 3987 unsigned DiagID; 3988 if (Record->isUnion()) { 3989 // C++ [class.union]p6: 3990 // Anonymous unions declared in a named namespace or in the 3991 // global namespace shall be declared static. 3992 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3993 (isa<TranslationUnitDecl>(Owner) || 3994 (isa<NamespaceDecl>(Owner) && 3995 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3996 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3997 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3998 3999 // Recover by adding 'static'. 4000 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4001 PrevSpec, DiagID, Policy); 4002 } 4003 // C++ [class.union]p6: 4004 // A storage class is not allowed in a declaration of an 4005 // anonymous union in a class scope. 4006 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4007 isa<RecordDecl>(Owner)) { 4008 Diag(DS.getStorageClassSpecLoc(), 4009 diag::err_anonymous_union_with_storage_spec) 4010 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4011 4012 // Recover by removing the storage specifier. 4013 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4014 SourceLocation(), 4015 PrevSpec, DiagID, Context.getPrintingPolicy()); 4016 } 4017 } 4018 4019 // Ignore const/volatile/restrict qualifiers. 4020 if (DS.getTypeQualifiers()) { 4021 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4022 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4023 << Record->isUnion() << "const" 4024 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4025 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4026 Diag(DS.getVolatileSpecLoc(), 4027 diag::ext_anonymous_struct_union_qualified) 4028 << Record->isUnion() << "volatile" 4029 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4030 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4031 Diag(DS.getRestrictSpecLoc(), 4032 diag::ext_anonymous_struct_union_qualified) 4033 << Record->isUnion() << "restrict" 4034 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4035 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4036 Diag(DS.getAtomicSpecLoc(), 4037 diag::ext_anonymous_struct_union_qualified) 4038 << Record->isUnion() << "_Atomic" 4039 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4040 4041 DS.ClearTypeQualifiers(); 4042 } 4043 4044 // C++ [class.union]p2: 4045 // The member-specification of an anonymous union shall only 4046 // define non-static data members. [Note: nested types and 4047 // functions cannot be declared within an anonymous union. ] 4048 for (auto *Mem : Record->decls()) { 4049 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4050 // C++ [class.union]p3: 4051 // An anonymous union shall not have private or protected 4052 // members (clause 11). 4053 assert(FD->getAccess() != AS_none); 4054 if (FD->getAccess() != AS_public) { 4055 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4056 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 4057 Invalid = true; 4058 } 4059 4060 // C++ [class.union]p1 4061 // An object of a class with a non-trivial constructor, a non-trivial 4062 // copy constructor, a non-trivial destructor, or a non-trivial copy 4063 // assignment operator cannot be a member of a union, nor can an 4064 // array of such objects. 4065 if (CheckNontrivialField(FD)) 4066 Invalid = true; 4067 } else if (Mem->isImplicit()) { 4068 // Any implicit members are fine. 4069 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4070 // This is a type that showed up in an 4071 // elaborated-type-specifier inside the anonymous struct or 4072 // union, but which actually declares a type outside of the 4073 // anonymous struct or union. It's okay. 4074 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4075 if (!MemRecord->isAnonymousStructOrUnion() && 4076 MemRecord->getDeclName()) { 4077 // Visual C++ allows type definition in anonymous struct or union. 4078 if (getLangOpts().MicrosoftExt) 4079 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4080 << (int)Record->isUnion(); 4081 else { 4082 // This is a nested type declaration. 4083 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4084 << (int)Record->isUnion(); 4085 Invalid = true; 4086 } 4087 } else { 4088 // This is an anonymous type definition within another anonymous type. 4089 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4090 // not part of standard C++. 4091 Diag(MemRecord->getLocation(), 4092 diag::ext_anonymous_record_with_anonymous_type) 4093 << (int)Record->isUnion(); 4094 } 4095 } else if (isa<AccessSpecDecl>(Mem)) { 4096 // Any access specifier is fine. 4097 } else if (isa<StaticAssertDecl>(Mem)) { 4098 // In C++1z, static_assert declarations are also fine. 4099 } else { 4100 // We have something that isn't a non-static data 4101 // member. Complain about it. 4102 unsigned DK = diag::err_anonymous_record_bad_member; 4103 if (isa<TypeDecl>(Mem)) 4104 DK = diag::err_anonymous_record_with_type; 4105 else if (isa<FunctionDecl>(Mem)) 4106 DK = diag::err_anonymous_record_with_function; 4107 else if (isa<VarDecl>(Mem)) 4108 DK = diag::err_anonymous_record_with_static; 4109 4110 // Visual C++ allows type definition in anonymous struct or union. 4111 if (getLangOpts().MicrosoftExt && 4112 DK == diag::err_anonymous_record_with_type) 4113 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4114 << (int)Record->isUnion(); 4115 else { 4116 Diag(Mem->getLocation(), DK) 4117 << (int)Record->isUnion(); 4118 Invalid = true; 4119 } 4120 } 4121 } 4122 4123 // C++11 [class.union]p8 (DR1460): 4124 // At most one variant member of a union may have a 4125 // brace-or-equal-initializer. 4126 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4127 Owner->isRecord()) 4128 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4129 cast<CXXRecordDecl>(Record)); 4130 } 4131 4132 if (!Record->isUnion() && !Owner->isRecord()) { 4133 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4134 << (int)getLangOpts().CPlusPlus; 4135 Invalid = true; 4136 } 4137 4138 // Mock up a declarator. 4139 Declarator Dc(DS, Declarator::MemberContext); 4140 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4141 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4142 4143 // Create a declaration for this anonymous struct/union. 4144 NamedDecl *Anon = nullptr; 4145 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4146 Anon = FieldDecl::Create(Context, OwningClass, 4147 DS.getLocStart(), 4148 Record->getLocation(), 4149 /*IdentifierInfo=*/nullptr, 4150 Context.getTypeDeclType(Record), 4151 TInfo, 4152 /*BitWidth=*/nullptr, /*Mutable=*/false, 4153 /*InitStyle=*/ICIS_NoInit); 4154 Anon->setAccess(AS); 4155 if (getLangOpts().CPlusPlus) 4156 FieldCollector->Add(cast<FieldDecl>(Anon)); 4157 } else { 4158 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4159 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4160 if (SCSpec == DeclSpec::SCS_mutable) { 4161 // mutable can only appear on non-static class members, so it's always 4162 // an error here 4163 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4164 Invalid = true; 4165 SC = SC_None; 4166 } 4167 4168 Anon = VarDecl::Create(Context, Owner, 4169 DS.getLocStart(), 4170 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4171 Context.getTypeDeclType(Record), 4172 TInfo, SC); 4173 4174 // Default-initialize the implicit variable. This initialization will be 4175 // trivial in almost all cases, except if a union member has an in-class 4176 // initializer: 4177 // union { int n = 0; }; 4178 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4179 } 4180 Anon->setImplicit(); 4181 4182 // Mark this as an anonymous struct/union type. 4183 Record->setAnonymousStructOrUnion(true); 4184 4185 // Add the anonymous struct/union object to the current 4186 // context. We'll be referencing this object when we refer to one of 4187 // its members. 4188 Owner->addDecl(Anon); 4189 4190 // Inject the members of the anonymous struct/union into the owning 4191 // context and into the identifier resolver chain for name lookup 4192 // purposes. 4193 SmallVector<NamedDecl*, 2> Chain; 4194 Chain.push_back(Anon); 4195 4196 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 4197 Chain, false)) 4198 Invalid = true; 4199 4200 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4201 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4202 Decl *ManglingContextDecl; 4203 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4204 NewVD->getDeclContext(), ManglingContextDecl)) { 4205 Context.setManglingNumber( 4206 NewVD, MCtx->getManglingNumber( 4207 NewVD, getMSManglingNumber(getLangOpts(), S))); 4208 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4209 } 4210 } 4211 } 4212 4213 if (Invalid) 4214 Anon->setInvalidDecl(); 4215 4216 return Anon; 4217 } 4218 4219 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4220 /// Microsoft C anonymous structure. 4221 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4222 /// Example: 4223 /// 4224 /// struct A { int a; }; 4225 /// struct B { struct A; int b; }; 4226 /// 4227 /// void foo() { 4228 /// B var; 4229 /// var.a = 3; 4230 /// } 4231 /// 4232 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4233 RecordDecl *Record) { 4234 assert(Record && "expected a record!"); 4235 4236 // Mock up a declarator. 4237 Declarator Dc(DS, Declarator::TypeNameContext); 4238 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4239 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4240 4241 auto *ParentDecl = cast<RecordDecl>(CurContext); 4242 QualType RecTy = Context.getTypeDeclType(Record); 4243 4244 // Create a declaration for this anonymous struct. 4245 NamedDecl *Anon = FieldDecl::Create(Context, 4246 ParentDecl, 4247 DS.getLocStart(), 4248 DS.getLocStart(), 4249 /*IdentifierInfo=*/nullptr, 4250 RecTy, 4251 TInfo, 4252 /*BitWidth=*/nullptr, /*Mutable=*/false, 4253 /*InitStyle=*/ICIS_NoInit); 4254 Anon->setImplicit(); 4255 4256 // Add the anonymous struct object to the current context. 4257 CurContext->addDecl(Anon); 4258 4259 // Inject the members of the anonymous struct into the current 4260 // context and into the identifier resolver chain for name lookup 4261 // purposes. 4262 SmallVector<NamedDecl*, 2> Chain; 4263 Chain.push_back(Anon); 4264 4265 RecordDecl *RecordDef = Record->getDefinition(); 4266 if (RequireCompleteType(Anon->getLocation(), RecTy, 4267 diag::err_field_incomplete) || 4268 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4269 AS_none, Chain, true)) { 4270 Anon->setInvalidDecl(); 4271 ParentDecl->setInvalidDecl(); 4272 } 4273 4274 return Anon; 4275 } 4276 4277 /// GetNameForDeclarator - Determine the full declaration name for the 4278 /// given Declarator. 4279 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4280 return GetNameFromUnqualifiedId(D.getName()); 4281 } 4282 4283 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4284 DeclarationNameInfo 4285 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4286 DeclarationNameInfo NameInfo; 4287 NameInfo.setLoc(Name.StartLocation); 4288 4289 switch (Name.getKind()) { 4290 4291 case UnqualifiedId::IK_ImplicitSelfParam: 4292 case UnqualifiedId::IK_Identifier: 4293 NameInfo.setName(Name.Identifier); 4294 NameInfo.setLoc(Name.StartLocation); 4295 return NameInfo; 4296 4297 case UnqualifiedId::IK_OperatorFunctionId: 4298 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4299 Name.OperatorFunctionId.Operator)); 4300 NameInfo.setLoc(Name.StartLocation); 4301 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4302 = Name.OperatorFunctionId.SymbolLocations[0]; 4303 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4304 = Name.EndLocation.getRawEncoding(); 4305 return NameInfo; 4306 4307 case UnqualifiedId::IK_LiteralOperatorId: 4308 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4309 Name.Identifier)); 4310 NameInfo.setLoc(Name.StartLocation); 4311 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4312 return NameInfo; 4313 4314 case UnqualifiedId::IK_ConversionFunctionId: { 4315 TypeSourceInfo *TInfo; 4316 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4317 if (Ty.isNull()) 4318 return DeclarationNameInfo(); 4319 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4320 Context.getCanonicalType(Ty))); 4321 NameInfo.setLoc(Name.StartLocation); 4322 NameInfo.setNamedTypeInfo(TInfo); 4323 return NameInfo; 4324 } 4325 4326 case UnqualifiedId::IK_ConstructorName: { 4327 TypeSourceInfo *TInfo; 4328 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4329 if (Ty.isNull()) 4330 return DeclarationNameInfo(); 4331 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4332 Context.getCanonicalType(Ty))); 4333 NameInfo.setLoc(Name.StartLocation); 4334 NameInfo.setNamedTypeInfo(TInfo); 4335 return NameInfo; 4336 } 4337 4338 case UnqualifiedId::IK_ConstructorTemplateId: { 4339 // In well-formed code, we can only have a constructor 4340 // template-id that refers to the current context, so go there 4341 // to find the actual type being constructed. 4342 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4343 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4344 return DeclarationNameInfo(); 4345 4346 // Determine the type of the class being constructed. 4347 QualType CurClassType = Context.getTypeDeclType(CurClass); 4348 4349 // FIXME: Check two things: that the template-id names the same type as 4350 // CurClassType, and that the template-id does not occur when the name 4351 // was qualified. 4352 4353 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4354 Context.getCanonicalType(CurClassType))); 4355 NameInfo.setLoc(Name.StartLocation); 4356 // FIXME: should we retrieve TypeSourceInfo? 4357 NameInfo.setNamedTypeInfo(nullptr); 4358 return NameInfo; 4359 } 4360 4361 case UnqualifiedId::IK_DestructorName: { 4362 TypeSourceInfo *TInfo; 4363 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4364 if (Ty.isNull()) 4365 return DeclarationNameInfo(); 4366 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4367 Context.getCanonicalType(Ty))); 4368 NameInfo.setLoc(Name.StartLocation); 4369 NameInfo.setNamedTypeInfo(TInfo); 4370 return NameInfo; 4371 } 4372 4373 case UnqualifiedId::IK_TemplateId: { 4374 TemplateName TName = Name.TemplateId->Template.get(); 4375 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4376 return Context.getNameForTemplate(TName, TNameLoc); 4377 } 4378 4379 } // switch (Name.getKind()) 4380 4381 llvm_unreachable("Unknown name kind"); 4382 } 4383 4384 static QualType getCoreType(QualType Ty) { 4385 do { 4386 if (Ty->isPointerType() || Ty->isReferenceType()) 4387 Ty = Ty->getPointeeType(); 4388 else if (Ty->isArrayType()) 4389 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4390 else 4391 return Ty.withoutLocalFastQualifiers(); 4392 } while (true); 4393 } 4394 4395 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4396 /// and Definition have "nearly" matching parameters. This heuristic is 4397 /// used to improve diagnostics in the case where an out-of-line function 4398 /// definition doesn't match any declaration within the class or namespace. 4399 /// Also sets Params to the list of indices to the parameters that differ 4400 /// between the declaration and the definition. If hasSimilarParameters 4401 /// returns true and Params is empty, then all of the parameters match. 4402 static bool hasSimilarParameters(ASTContext &Context, 4403 FunctionDecl *Declaration, 4404 FunctionDecl *Definition, 4405 SmallVectorImpl<unsigned> &Params) { 4406 Params.clear(); 4407 if (Declaration->param_size() != Definition->param_size()) 4408 return false; 4409 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4410 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4411 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4412 4413 // The parameter types are identical 4414 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4415 continue; 4416 4417 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4418 QualType DefParamBaseTy = getCoreType(DefParamTy); 4419 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4420 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4421 4422 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4423 (DeclTyName && DeclTyName == DefTyName)) 4424 Params.push_back(Idx); 4425 else // The two parameters aren't even close 4426 return false; 4427 } 4428 4429 return true; 4430 } 4431 4432 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4433 /// declarator needs to be rebuilt in the current instantiation. 4434 /// Any bits of declarator which appear before the name are valid for 4435 /// consideration here. That's specifically the type in the decl spec 4436 /// and the base type in any member-pointer chunks. 4437 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4438 DeclarationName Name) { 4439 // The types we specifically need to rebuild are: 4440 // - typenames, typeofs, and decltypes 4441 // - types which will become injected class names 4442 // Of course, we also need to rebuild any type referencing such a 4443 // type. It's safest to just say "dependent", but we call out a 4444 // few cases here. 4445 4446 DeclSpec &DS = D.getMutableDeclSpec(); 4447 switch (DS.getTypeSpecType()) { 4448 case DeclSpec::TST_typename: 4449 case DeclSpec::TST_typeofType: 4450 case DeclSpec::TST_underlyingType: 4451 case DeclSpec::TST_atomic: { 4452 // Grab the type from the parser. 4453 TypeSourceInfo *TSI = nullptr; 4454 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4455 if (T.isNull() || !T->isDependentType()) break; 4456 4457 // Make sure there's a type source info. This isn't really much 4458 // of a waste; most dependent types should have type source info 4459 // attached already. 4460 if (!TSI) 4461 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4462 4463 // Rebuild the type in the current instantiation. 4464 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4465 if (!TSI) return true; 4466 4467 // Store the new type back in the decl spec. 4468 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4469 DS.UpdateTypeRep(LocType); 4470 break; 4471 } 4472 4473 case DeclSpec::TST_decltype: 4474 case DeclSpec::TST_typeofExpr: { 4475 Expr *E = DS.getRepAsExpr(); 4476 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4477 if (Result.isInvalid()) return true; 4478 DS.UpdateExprRep(Result.get()); 4479 break; 4480 } 4481 4482 default: 4483 // Nothing to do for these decl specs. 4484 break; 4485 } 4486 4487 // It doesn't matter what order we do this in. 4488 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4489 DeclaratorChunk &Chunk = D.getTypeObject(I); 4490 4491 // The only type information in the declarator which can come 4492 // before the declaration name is the base type of a member 4493 // pointer. 4494 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4495 continue; 4496 4497 // Rebuild the scope specifier in-place. 4498 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4499 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4500 return true; 4501 } 4502 4503 return false; 4504 } 4505 4506 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4507 D.setFunctionDefinitionKind(FDK_Declaration); 4508 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4509 4510 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4511 Dcl && Dcl->getDeclContext()->isFileContext()) 4512 Dcl->setTopLevelDeclInObjCContainer(); 4513 4514 return Dcl; 4515 } 4516 4517 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4518 /// If T is the name of a class, then each of the following shall have a 4519 /// name different from T: 4520 /// - every static data member of class T; 4521 /// - every member function of class T 4522 /// - every member of class T that is itself a type; 4523 /// \returns true if the declaration name violates these rules. 4524 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4525 DeclarationNameInfo NameInfo) { 4526 DeclarationName Name = NameInfo.getName(); 4527 4528 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4529 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4530 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4531 return true; 4532 } 4533 4534 return false; 4535 } 4536 4537 /// \brief Diagnose a declaration whose declarator-id has the given 4538 /// nested-name-specifier. 4539 /// 4540 /// \param SS The nested-name-specifier of the declarator-id. 4541 /// 4542 /// \param DC The declaration context to which the nested-name-specifier 4543 /// resolves. 4544 /// 4545 /// \param Name The name of the entity being declared. 4546 /// 4547 /// \param Loc The location of the name of the entity being declared. 4548 /// 4549 /// \returns true if we cannot safely recover from this error, false otherwise. 4550 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4551 DeclarationName Name, 4552 SourceLocation Loc) { 4553 DeclContext *Cur = CurContext; 4554 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4555 Cur = Cur->getParent(); 4556 4557 // If the user provided a superfluous scope specifier that refers back to the 4558 // class in which the entity is already declared, diagnose and ignore it. 4559 // 4560 // class X { 4561 // void X::f(); 4562 // }; 4563 // 4564 // Note, it was once ill-formed to give redundant qualification in all 4565 // contexts, but that rule was removed by DR482. 4566 if (Cur->Equals(DC)) { 4567 if (Cur->isRecord()) { 4568 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4569 : diag::err_member_extra_qualification) 4570 << Name << FixItHint::CreateRemoval(SS.getRange()); 4571 SS.clear(); 4572 } else { 4573 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4574 } 4575 return false; 4576 } 4577 4578 // Check whether the qualifying scope encloses the scope of the original 4579 // declaration. 4580 if (!Cur->Encloses(DC)) { 4581 if (Cur->isRecord()) 4582 Diag(Loc, diag::err_member_qualification) 4583 << Name << SS.getRange(); 4584 else if (isa<TranslationUnitDecl>(DC)) 4585 Diag(Loc, diag::err_invalid_declarator_global_scope) 4586 << Name << SS.getRange(); 4587 else if (isa<FunctionDecl>(Cur)) 4588 Diag(Loc, diag::err_invalid_declarator_in_function) 4589 << Name << SS.getRange(); 4590 else if (isa<BlockDecl>(Cur)) 4591 Diag(Loc, diag::err_invalid_declarator_in_block) 4592 << Name << SS.getRange(); 4593 else 4594 Diag(Loc, diag::err_invalid_declarator_scope) 4595 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4596 4597 return true; 4598 } 4599 4600 if (Cur->isRecord()) { 4601 // Cannot qualify members within a class. 4602 Diag(Loc, diag::err_member_qualification) 4603 << Name << SS.getRange(); 4604 SS.clear(); 4605 4606 // C++ constructors and destructors with incorrect scopes can break 4607 // our AST invariants by having the wrong underlying types. If 4608 // that's the case, then drop this declaration entirely. 4609 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4610 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4611 !Context.hasSameType(Name.getCXXNameType(), 4612 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4613 return true; 4614 4615 return false; 4616 } 4617 4618 // C++11 [dcl.meaning]p1: 4619 // [...] "The nested-name-specifier of the qualified declarator-id shall 4620 // not begin with a decltype-specifer" 4621 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4622 while (SpecLoc.getPrefix()) 4623 SpecLoc = SpecLoc.getPrefix(); 4624 if (dyn_cast_or_null<DecltypeType>( 4625 SpecLoc.getNestedNameSpecifier()->getAsType())) 4626 Diag(Loc, diag::err_decltype_in_declarator) 4627 << SpecLoc.getTypeLoc().getSourceRange(); 4628 4629 return false; 4630 } 4631 4632 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4633 MultiTemplateParamsArg TemplateParamLists) { 4634 // TODO: consider using NameInfo for diagnostic. 4635 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4636 DeclarationName Name = NameInfo.getName(); 4637 4638 // All of these full declarators require an identifier. If it doesn't have 4639 // one, the ParsedFreeStandingDeclSpec action should be used. 4640 if (!Name) { 4641 if (!D.isInvalidType()) // Reject this if we think it is valid. 4642 Diag(D.getDeclSpec().getLocStart(), 4643 diag::err_declarator_need_ident) 4644 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4645 return nullptr; 4646 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4647 return nullptr; 4648 4649 // The scope passed in may not be a decl scope. Zip up the scope tree until 4650 // we find one that is. 4651 while ((S->getFlags() & Scope::DeclScope) == 0 || 4652 (S->getFlags() & Scope::TemplateParamScope) != 0) 4653 S = S->getParent(); 4654 4655 DeclContext *DC = CurContext; 4656 if (D.getCXXScopeSpec().isInvalid()) 4657 D.setInvalidType(); 4658 else if (D.getCXXScopeSpec().isSet()) { 4659 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4660 UPPC_DeclarationQualifier)) 4661 return nullptr; 4662 4663 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4664 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4665 if (!DC || isa<EnumDecl>(DC)) { 4666 // If we could not compute the declaration context, it's because the 4667 // declaration context is dependent but does not refer to a class, 4668 // class template, or class template partial specialization. Complain 4669 // and return early, to avoid the coming semantic disaster. 4670 Diag(D.getIdentifierLoc(), 4671 diag::err_template_qualified_declarator_no_match) 4672 << D.getCXXScopeSpec().getScopeRep() 4673 << D.getCXXScopeSpec().getRange(); 4674 return nullptr; 4675 } 4676 bool IsDependentContext = DC->isDependentContext(); 4677 4678 if (!IsDependentContext && 4679 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4680 return nullptr; 4681 4682 // If a class is incomplete, do not parse entities inside it. 4683 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4684 Diag(D.getIdentifierLoc(), 4685 diag::err_member_def_undefined_record) 4686 << Name << DC << D.getCXXScopeSpec().getRange(); 4687 return nullptr; 4688 } 4689 if (!D.getDeclSpec().isFriendSpecified()) { 4690 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4691 Name, D.getIdentifierLoc())) { 4692 if (DC->isRecord()) 4693 return nullptr; 4694 4695 D.setInvalidType(); 4696 } 4697 } 4698 4699 // Check whether we need to rebuild the type of the given 4700 // declaration in the current instantiation. 4701 if (EnteringContext && IsDependentContext && 4702 TemplateParamLists.size() != 0) { 4703 ContextRAII SavedContext(*this, DC); 4704 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4705 D.setInvalidType(); 4706 } 4707 } 4708 4709 if (DiagnoseClassNameShadow(DC, NameInfo)) 4710 // If this is a typedef, we'll end up spewing multiple diagnostics. 4711 // Just return early; it's safer. 4712 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4713 return nullptr; 4714 4715 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4716 QualType R = TInfo->getType(); 4717 4718 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4719 UPPC_DeclarationType)) 4720 D.setInvalidType(); 4721 4722 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4723 ForRedeclaration); 4724 4725 // See if this is a redefinition of a variable in the same scope. 4726 if (!D.getCXXScopeSpec().isSet()) { 4727 bool IsLinkageLookup = false; 4728 bool CreateBuiltins = false; 4729 4730 // If the declaration we're planning to build will be a function 4731 // or object with linkage, then look for another declaration with 4732 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4733 // 4734 // If the declaration we're planning to build will be declared with 4735 // external linkage in the translation unit, create any builtin with 4736 // the same name. 4737 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4738 /* Do nothing*/; 4739 else if (CurContext->isFunctionOrMethod() && 4740 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4741 R->isFunctionType())) { 4742 IsLinkageLookup = true; 4743 CreateBuiltins = 4744 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4745 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4746 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4747 CreateBuiltins = true; 4748 4749 if (IsLinkageLookup) 4750 Previous.clear(LookupRedeclarationWithLinkage); 4751 4752 LookupName(Previous, S, CreateBuiltins); 4753 } else { // Something like "int foo::x;" 4754 LookupQualifiedName(Previous, DC); 4755 4756 // C++ [dcl.meaning]p1: 4757 // When the declarator-id is qualified, the declaration shall refer to a 4758 // previously declared member of the class or namespace to which the 4759 // qualifier refers (or, in the case of a namespace, of an element of the 4760 // inline namespace set of that namespace (7.3.1)) or to a specialization 4761 // thereof; [...] 4762 // 4763 // Note that we already checked the context above, and that we do not have 4764 // enough information to make sure that Previous contains the declaration 4765 // we want to match. For example, given: 4766 // 4767 // class X { 4768 // void f(); 4769 // void f(float); 4770 // }; 4771 // 4772 // void X::f(int) { } // ill-formed 4773 // 4774 // In this case, Previous will point to the overload set 4775 // containing the two f's declared in X, but neither of them 4776 // matches. 4777 4778 // C++ [dcl.meaning]p1: 4779 // [...] the member shall not merely have been introduced by a 4780 // using-declaration in the scope of the class or namespace nominated by 4781 // the nested-name-specifier of the declarator-id. 4782 RemoveUsingDecls(Previous); 4783 } 4784 4785 if (Previous.isSingleResult() && 4786 Previous.getFoundDecl()->isTemplateParameter()) { 4787 // Maybe we will complain about the shadowed template parameter. 4788 if (!D.isInvalidType()) 4789 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4790 Previous.getFoundDecl()); 4791 4792 // Just pretend that we didn't see the previous declaration. 4793 Previous.clear(); 4794 } 4795 4796 // In C++, the previous declaration we find might be a tag type 4797 // (class or enum). In this case, the new declaration will hide the 4798 // tag type. Note that this does does not apply if we're declaring a 4799 // typedef (C++ [dcl.typedef]p4). 4800 if (Previous.isSingleTagDecl() && 4801 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4802 Previous.clear(); 4803 4804 // Check that there are no default arguments other than in the parameters 4805 // of a function declaration (C++ only). 4806 if (getLangOpts().CPlusPlus) 4807 CheckExtraCXXDefaultArguments(D); 4808 4809 NamedDecl *New; 4810 4811 bool AddToScope = true; 4812 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4813 if (TemplateParamLists.size()) { 4814 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4815 return nullptr; 4816 } 4817 4818 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4819 } else if (R->isFunctionType()) { 4820 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4821 TemplateParamLists, 4822 AddToScope); 4823 } else { 4824 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4825 AddToScope); 4826 } 4827 4828 if (!New) 4829 return nullptr; 4830 4831 // If this has an identifier and is not an invalid redeclaration or 4832 // function template specialization, add it to the scope stack. 4833 if (New->getDeclName() && AddToScope && 4834 !(D.isRedeclaration() && New->isInvalidDecl())) { 4835 // Only make a locally-scoped extern declaration visible if it is the first 4836 // declaration of this entity. Qualified lookup for such an entity should 4837 // only find this declaration if there is no visible declaration of it. 4838 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4839 PushOnScopeChains(New, S, AddToContext); 4840 if (!AddToContext) 4841 CurContext->addHiddenDecl(New); 4842 } 4843 4844 return New; 4845 } 4846 4847 /// Helper method to turn variable array types into constant array 4848 /// types in certain situations which would otherwise be errors (for 4849 /// GCC compatibility). 4850 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4851 ASTContext &Context, 4852 bool &SizeIsNegative, 4853 llvm::APSInt &Oversized) { 4854 // This method tries to turn a variable array into a constant 4855 // array even when the size isn't an ICE. This is necessary 4856 // for compatibility with code that depends on gcc's buggy 4857 // constant expression folding, like struct {char x[(int)(char*)2];} 4858 SizeIsNegative = false; 4859 Oversized = 0; 4860 4861 if (T->isDependentType()) 4862 return QualType(); 4863 4864 QualifierCollector Qs; 4865 const Type *Ty = Qs.strip(T); 4866 4867 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4868 QualType Pointee = PTy->getPointeeType(); 4869 QualType FixedType = 4870 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4871 Oversized); 4872 if (FixedType.isNull()) return FixedType; 4873 FixedType = Context.getPointerType(FixedType); 4874 return Qs.apply(Context, FixedType); 4875 } 4876 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4877 QualType Inner = PTy->getInnerType(); 4878 QualType FixedType = 4879 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4880 Oversized); 4881 if (FixedType.isNull()) return FixedType; 4882 FixedType = Context.getParenType(FixedType); 4883 return Qs.apply(Context, FixedType); 4884 } 4885 4886 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4887 if (!VLATy) 4888 return QualType(); 4889 // FIXME: We should probably handle this case 4890 if (VLATy->getElementType()->isVariablyModifiedType()) 4891 return QualType(); 4892 4893 llvm::APSInt Res; 4894 if (!VLATy->getSizeExpr() || 4895 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4896 return QualType(); 4897 4898 // Check whether the array size is negative. 4899 if (Res.isSigned() && Res.isNegative()) { 4900 SizeIsNegative = true; 4901 return QualType(); 4902 } 4903 4904 // Check whether the array is too large to be addressed. 4905 unsigned ActiveSizeBits 4906 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4907 Res); 4908 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4909 Oversized = Res; 4910 return QualType(); 4911 } 4912 4913 return Context.getConstantArrayType(VLATy->getElementType(), 4914 Res, ArrayType::Normal, 0); 4915 } 4916 4917 static void 4918 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4919 SrcTL = SrcTL.getUnqualifiedLoc(); 4920 DstTL = DstTL.getUnqualifiedLoc(); 4921 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4922 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4923 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4924 DstPTL.getPointeeLoc()); 4925 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4926 return; 4927 } 4928 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4929 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4930 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4931 DstPTL.getInnerLoc()); 4932 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4933 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4934 return; 4935 } 4936 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4937 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4938 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4939 TypeLoc DstElemTL = DstATL.getElementLoc(); 4940 DstElemTL.initializeFullCopy(SrcElemTL); 4941 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4942 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4943 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4944 } 4945 4946 /// Helper method to turn variable array types into constant array 4947 /// types in certain situations which would otherwise be errors (for 4948 /// GCC compatibility). 4949 static TypeSourceInfo* 4950 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4951 ASTContext &Context, 4952 bool &SizeIsNegative, 4953 llvm::APSInt &Oversized) { 4954 QualType FixedTy 4955 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4956 SizeIsNegative, Oversized); 4957 if (FixedTy.isNull()) 4958 return nullptr; 4959 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4960 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4961 FixedTInfo->getTypeLoc()); 4962 return FixedTInfo; 4963 } 4964 4965 /// \brief Register the given locally-scoped extern "C" declaration so 4966 /// that it can be found later for redeclarations. We include any extern "C" 4967 /// declaration that is not visible in the translation unit here, not just 4968 /// function-scope declarations. 4969 void 4970 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4971 if (!getLangOpts().CPlusPlus && 4972 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4973 // Don't need to track declarations in the TU in C. 4974 return; 4975 4976 // Note that we have a locally-scoped external with this name. 4977 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 4978 } 4979 4980 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4981 // FIXME: We can have multiple results via __attribute__((overloadable)). 4982 auto Result = Context.getExternCContextDecl()->lookup(Name); 4983 return Result.empty() ? nullptr : *Result.begin(); 4984 } 4985 4986 /// \brief Diagnose function specifiers on a declaration of an identifier that 4987 /// does not identify a function. 4988 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4989 // FIXME: We should probably indicate the identifier in question to avoid 4990 // confusion for constructs like "inline int a(), b;" 4991 if (DS.isInlineSpecified()) 4992 Diag(DS.getInlineSpecLoc(), 4993 diag::err_inline_non_function); 4994 4995 if (DS.isVirtualSpecified()) 4996 Diag(DS.getVirtualSpecLoc(), 4997 diag::err_virtual_non_function); 4998 4999 if (DS.isExplicitSpecified()) 5000 Diag(DS.getExplicitSpecLoc(), 5001 diag::err_explicit_non_function); 5002 5003 if (DS.isNoreturnSpecified()) 5004 Diag(DS.getNoreturnSpecLoc(), 5005 diag::err_noreturn_non_function); 5006 } 5007 5008 NamedDecl* 5009 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5010 TypeSourceInfo *TInfo, LookupResult &Previous) { 5011 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5012 if (D.getCXXScopeSpec().isSet()) { 5013 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5014 << D.getCXXScopeSpec().getRange(); 5015 D.setInvalidType(); 5016 // Pretend we didn't see the scope specifier. 5017 DC = CurContext; 5018 Previous.clear(); 5019 } 5020 5021 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5022 5023 if (D.getDeclSpec().isConstexprSpecified()) 5024 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5025 << 1; 5026 5027 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5028 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5029 << D.getName().getSourceRange(); 5030 return nullptr; 5031 } 5032 5033 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5034 if (!NewTD) return nullptr; 5035 5036 // Handle attributes prior to checking for duplicates in MergeVarDecl 5037 ProcessDeclAttributes(S, NewTD, D); 5038 5039 CheckTypedefForVariablyModifiedType(S, NewTD); 5040 5041 bool Redeclaration = D.isRedeclaration(); 5042 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5043 D.setRedeclaration(Redeclaration); 5044 return ND; 5045 } 5046 5047 void 5048 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5049 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5050 // then it shall have block scope. 5051 // Note that variably modified types must be fixed before merging the decl so 5052 // that redeclarations will match. 5053 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5054 QualType T = TInfo->getType(); 5055 if (T->isVariablyModifiedType()) { 5056 getCurFunction()->setHasBranchProtectedScope(); 5057 5058 if (S->getFnParent() == nullptr) { 5059 bool SizeIsNegative; 5060 llvm::APSInt Oversized; 5061 TypeSourceInfo *FixedTInfo = 5062 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5063 SizeIsNegative, 5064 Oversized); 5065 if (FixedTInfo) { 5066 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5067 NewTD->setTypeSourceInfo(FixedTInfo); 5068 } else { 5069 if (SizeIsNegative) 5070 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5071 else if (T->isVariableArrayType()) 5072 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5073 else if (Oversized.getBoolValue()) 5074 Diag(NewTD->getLocation(), diag::err_array_too_large) 5075 << Oversized.toString(10); 5076 else 5077 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5078 NewTD->setInvalidDecl(); 5079 } 5080 } 5081 } 5082 } 5083 5084 5085 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5086 /// declares a typedef-name, either using the 'typedef' type specifier or via 5087 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5088 NamedDecl* 5089 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5090 LookupResult &Previous, bool &Redeclaration) { 5091 // Merge the decl with the existing one if appropriate. If the decl is 5092 // in an outer scope, it isn't the same thing. 5093 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5094 /*AllowInlineNamespace*/false); 5095 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5096 if (!Previous.empty()) { 5097 Redeclaration = true; 5098 MergeTypedefNameDecl(NewTD, Previous); 5099 } 5100 5101 // If this is the C FILE type, notify the AST context. 5102 if (IdentifierInfo *II = NewTD->getIdentifier()) 5103 if (!NewTD->isInvalidDecl() && 5104 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5105 if (II->isStr("FILE")) 5106 Context.setFILEDecl(NewTD); 5107 else if (II->isStr("jmp_buf")) 5108 Context.setjmp_bufDecl(NewTD); 5109 else if (II->isStr("sigjmp_buf")) 5110 Context.setsigjmp_bufDecl(NewTD); 5111 else if (II->isStr("ucontext_t")) 5112 Context.setucontext_tDecl(NewTD); 5113 } 5114 5115 return NewTD; 5116 } 5117 5118 /// \brief Determines whether the given declaration is an out-of-scope 5119 /// previous declaration. 5120 /// 5121 /// This routine should be invoked when name lookup has found a 5122 /// previous declaration (PrevDecl) that is not in the scope where a 5123 /// new declaration by the same name is being introduced. If the new 5124 /// declaration occurs in a local scope, previous declarations with 5125 /// linkage may still be considered previous declarations (C99 5126 /// 6.2.2p4-5, C++ [basic.link]p6). 5127 /// 5128 /// \param PrevDecl the previous declaration found by name 5129 /// lookup 5130 /// 5131 /// \param DC the context in which the new declaration is being 5132 /// declared. 5133 /// 5134 /// \returns true if PrevDecl is an out-of-scope previous declaration 5135 /// for a new delcaration with the same name. 5136 static bool 5137 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5138 ASTContext &Context) { 5139 if (!PrevDecl) 5140 return false; 5141 5142 if (!PrevDecl->hasLinkage()) 5143 return false; 5144 5145 if (Context.getLangOpts().CPlusPlus) { 5146 // C++ [basic.link]p6: 5147 // If there is a visible declaration of an entity with linkage 5148 // having the same name and type, ignoring entities declared 5149 // outside the innermost enclosing namespace scope, the block 5150 // scope declaration declares that same entity and receives the 5151 // linkage of the previous declaration. 5152 DeclContext *OuterContext = DC->getRedeclContext(); 5153 if (!OuterContext->isFunctionOrMethod()) 5154 // This rule only applies to block-scope declarations. 5155 return false; 5156 5157 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5158 if (PrevOuterContext->isRecord()) 5159 // We found a member function: ignore it. 5160 return false; 5161 5162 // Find the innermost enclosing namespace for the new and 5163 // previous declarations. 5164 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5165 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5166 5167 // The previous declaration is in a different namespace, so it 5168 // isn't the same function. 5169 if (!OuterContext->Equals(PrevOuterContext)) 5170 return false; 5171 } 5172 5173 return true; 5174 } 5175 5176 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5177 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5178 if (!SS.isSet()) return; 5179 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5180 } 5181 5182 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5183 QualType type = decl->getType(); 5184 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5185 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5186 // Various kinds of declaration aren't allowed to be __autoreleasing. 5187 unsigned kind = -1U; 5188 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5189 if (var->hasAttr<BlocksAttr>()) 5190 kind = 0; // __block 5191 else if (!var->hasLocalStorage()) 5192 kind = 1; // global 5193 } else if (isa<ObjCIvarDecl>(decl)) { 5194 kind = 3; // ivar 5195 } else if (isa<FieldDecl>(decl)) { 5196 kind = 2; // field 5197 } 5198 5199 if (kind != -1U) { 5200 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5201 << kind; 5202 } 5203 } else if (lifetime == Qualifiers::OCL_None) { 5204 // Try to infer lifetime. 5205 if (!type->isObjCLifetimeType()) 5206 return false; 5207 5208 lifetime = type->getObjCARCImplicitLifetime(); 5209 type = Context.getLifetimeQualifiedType(type, lifetime); 5210 decl->setType(type); 5211 } 5212 5213 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5214 // Thread-local variables cannot have lifetime. 5215 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5216 var->getTLSKind()) { 5217 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5218 << var->getType(); 5219 return true; 5220 } 5221 } 5222 5223 return false; 5224 } 5225 5226 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5227 // Ensure that an auto decl is deduced otherwise the checks below might cache 5228 // the wrong linkage. 5229 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5230 5231 // 'weak' only applies to declarations with external linkage. 5232 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5233 if (!ND.isExternallyVisible()) { 5234 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5235 ND.dropAttr<WeakAttr>(); 5236 } 5237 } 5238 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5239 if (ND.isExternallyVisible()) { 5240 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5241 ND.dropAttr<WeakRefAttr>(); 5242 ND.dropAttr<AliasAttr>(); 5243 } 5244 } 5245 5246 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5247 if (VD->hasInit()) { 5248 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5249 assert(VD->isThisDeclarationADefinition() && 5250 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5251 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD; 5252 VD->dropAttr<AliasAttr>(); 5253 } 5254 } 5255 } 5256 5257 // 'selectany' only applies to externally visible variable declarations. 5258 // It does not apply to functions. 5259 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5260 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5261 S.Diag(Attr->getLocation(), 5262 diag::err_attribute_selectany_non_extern_data); 5263 ND.dropAttr<SelectAnyAttr>(); 5264 } 5265 } 5266 5267 // dll attributes require external linkage. 5268 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5269 if (!ND.isExternallyVisible()) { 5270 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5271 << &ND << Attr; 5272 ND.setInvalidDecl(); 5273 } 5274 } 5275 } 5276 5277 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5278 NamedDecl *NewDecl, 5279 bool IsSpecialization) { 5280 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5281 OldDecl = OldTD->getTemplatedDecl(); 5282 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5283 NewDecl = NewTD->getTemplatedDecl(); 5284 5285 if (!OldDecl || !NewDecl) 5286 return; 5287 5288 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5289 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5290 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5291 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5292 5293 // dllimport and dllexport are inheritable attributes so we have to exclude 5294 // inherited attribute instances. 5295 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5296 (NewExportAttr && !NewExportAttr->isInherited()); 5297 5298 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5299 // the only exception being explicit specializations. 5300 // Implicitly generated declarations are also excluded for now because there 5301 // is no other way to switch these to use dllimport or dllexport. 5302 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5303 5304 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5305 // If the declaration hasn't been used yet, allow with a warning for 5306 // free functions and global variables. 5307 bool JustWarn = false; 5308 if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) { 5309 auto *VD = dyn_cast<VarDecl>(OldDecl); 5310 if (VD && !VD->getDescribedVarTemplate()) 5311 JustWarn = true; 5312 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5313 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5314 JustWarn = true; 5315 } 5316 5317 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5318 : diag::err_attribute_dll_redeclaration; 5319 S.Diag(NewDecl->getLocation(), DiagID) 5320 << NewDecl 5321 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5322 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5323 if (!JustWarn) { 5324 NewDecl->setInvalidDecl(); 5325 return; 5326 } 5327 } 5328 5329 // A redeclaration is not allowed to drop a dllimport attribute, the only 5330 // exceptions being inline function definitions, local extern declarations, 5331 // and qualified friend declarations. 5332 // NB: MSVC converts such a declaration to dllexport. 5333 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5334 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5335 // Ignore static data because out-of-line definitions are diagnosed 5336 // separately. 5337 IsStaticDataMember = VD->isStaticDataMember(); 5338 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5339 IsInline = FD->isInlined(); 5340 IsQualifiedFriend = FD->getQualifier() && 5341 FD->getFriendObjectKind() == Decl::FOK_Declared; 5342 } 5343 5344 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5345 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5346 S.Diag(NewDecl->getLocation(), 5347 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5348 << NewDecl << OldImportAttr; 5349 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5350 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5351 OldDecl->dropAttr<DLLImportAttr>(); 5352 NewDecl->dropAttr<DLLImportAttr>(); 5353 } else if (IsInline && OldImportAttr && 5354 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5355 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5356 OldDecl->dropAttr<DLLImportAttr>(); 5357 NewDecl->dropAttr<DLLImportAttr>(); 5358 S.Diag(NewDecl->getLocation(), 5359 diag::warn_dllimport_dropped_from_inline_function) 5360 << NewDecl << OldImportAttr; 5361 } 5362 } 5363 5364 /// Given that we are within the definition of the given function, 5365 /// will that definition behave like C99's 'inline', where the 5366 /// definition is discarded except for optimization purposes? 5367 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5368 // Try to avoid calling GetGVALinkageForFunction. 5369 5370 // All cases of this require the 'inline' keyword. 5371 if (!FD->isInlined()) return false; 5372 5373 // This is only possible in C++ with the gnu_inline attribute. 5374 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5375 return false; 5376 5377 // Okay, go ahead and call the relatively-more-expensive function. 5378 5379 #ifndef NDEBUG 5380 // AST quite reasonably asserts that it's working on a function 5381 // definition. We don't really have a way to tell it that we're 5382 // currently defining the function, so just lie to it in +Asserts 5383 // builds. This is an awful hack. 5384 FD->setLazyBody(1); 5385 #endif 5386 5387 bool isC99Inline = 5388 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5389 5390 #ifndef NDEBUG 5391 FD->setLazyBody(0); 5392 #endif 5393 5394 return isC99Inline; 5395 } 5396 5397 /// Determine whether a variable is extern "C" prior to attaching 5398 /// an initializer. We can't just call isExternC() here, because that 5399 /// will also compute and cache whether the declaration is externally 5400 /// visible, which might change when we attach the initializer. 5401 /// 5402 /// This can only be used if the declaration is known to not be a 5403 /// redeclaration of an internal linkage declaration. 5404 /// 5405 /// For instance: 5406 /// 5407 /// auto x = []{}; 5408 /// 5409 /// Attaching the initializer here makes this declaration not externally 5410 /// visible, because its type has internal linkage. 5411 /// 5412 /// FIXME: This is a hack. 5413 template<typename T> 5414 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5415 if (S.getLangOpts().CPlusPlus) { 5416 // In C++, the overloadable attribute negates the effects of extern "C". 5417 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5418 return false; 5419 } 5420 return D->isExternC(); 5421 } 5422 5423 static bool shouldConsiderLinkage(const VarDecl *VD) { 5424 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5425 if (DC->isFunctionOrMethod()) 5426 return VD->hasExternalStorage(); 5427 if (DC->isFileContext()) 5428 return true; 5429 if (DC->isRecord()) 5430 return false; 5431 llvm_unreachable("Unexpected context"); 5432 } 5433 5434 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5435 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5436 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5437 return true; 5438 if (DC->isRecord()) 5439 return false; 5440 llvm_unreachable("Unexpected context"); 5441 } 5442 5443 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5444 AttributeList::Kind Kind) { 5445 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5446 if (L->getKind() == Kind) 5447 return true; 5448 return false; 5449 } 5450 5451 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5452 AttributeList::Kind Kind) { 5453 // Check decl attributes on the DeclSpec. 5454 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5455 return true; 5456 5457 // Walk the declarator structure, checking decl attributes that were in a type 5458 // position to the decl itself. 5459 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5460 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5461 return true; 5462 } 5463 5464 // Finally, check attributes on the decl itself. 5465 return hasParsedAttr(S, PD.getAttributes(), Kind); 5466 } 5467 5468 /// Adjust the \c DeclContext for a function or variable that might be a 5469 /// function-local external declaration. 5470 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5471 if (!DC->isFunctionOrMethod()) 5472 return false; 5473 5474 // If this is a local extern function or variable declared within a function 5475 // template, don't add it into the enclosing namespace scope until it is 5476 // instantiated; it might have a dependent type right now. 5477 if (DC->isDependentContext()) 5478 return true; 5479 5480 // C++11 [basic.link]p7: 5481 // When a block scope declaration of an entity with linkage is not found to 5482 // refer to some other declaration, then that entity is a member of the 5483 // innermost enclosing namespace. 5484 // 5485 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5486 // semantically-enclosing namespace, not a lexically-enclosing one. 5487 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5488 DC = DC->getParent(); 5489 return true; 5490 } 5491 5492 NamedDecl * 5493 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5494 TypeSourceInfo *TInfo, LookupResult &Previous, 5495 MultiTemplateParamsArg TemplateParamLists, 5496 bool &AddToScope) { 5497 QualType R = TInfo->getType(); 5498 DeclarationName Name = GetNameForDeclarator(D).getName(); 5499 5500 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5501 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5502 5503 // dllimport globals without explicit storage class are treated as extern. We 5504 // have to change the storage class this early to get the right DeclContext. 5505 if (SC == SC_None && !DC->isRecord() && 5506 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5507 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5508 SC = SC_Extern; 5509 5510 DeclContext *OriginalDC = DC; 5511 bool IsLocalExternDecl = SC == SC_Extern && 5512 adjustContextForLocalExternDecl(DC); 5513 5514 if (getLangOpts().OpenCL) { 5515 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5516 QualType NR = R; 5517 while (NR->isPointerType()) { 5518 if (NR->isFunctionPointerType()) { 5519 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5520 D.setInvalidType(); 5521 break; 5522 } 5523 NR = NR->getPointeeType(); 5524 } 5525 5526 if (!getOpenCLOptions().cl_khr_fp16) { 5527 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5528 // half array type (unless the cl_khr_fp16 extension is enabled). 5529 if (Context.getBaseElementType(R)->isHalfType()) { 5530 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5531 D.setInvalidType(); 5532 } 5533 } 5534 } 5535 5536 if (SCSpec == DeclSpec::SCS_mutable) { 5537 // mutable can only appear on non-static class members, so it's always 5538 // an error here 5539 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5540 D.setInvalidType(); 5541 SC = SC_None; 5542 } 5543 5544 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5545 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5546 D.getDeclSpec().getStorageClassSpecLoc())) { 5547 // In C++11, the 'register' storage class specifier is deprecated. 5548 // Suppress the warning in system macros, it's used in macros in some 5549 // popular C system headers, such as in glibc's htonl() macro. 5550 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5551 diag::warn_deprecated_register) 5552 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5553 } 5554 5555 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5556 if (!II) { 5557 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5558 << Name; 5559 return nullptr; 5560 } 5561 5562 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5563 5564 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5565 // C99 6.9p2: The storage-class specifiers auto and register shall not 5566 // appear in the declaration specifiers in an external declaration. 5567 // Global Register+Asm is a GNU extension we support. 5568 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5569 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5570 D.setInvalidType(); 5571 } 5572 } 5573 5574 if (getLangOpts().OpenCL) { 5575 // Set up the special work-group-local storage class for variables in the 5576 // OpenCL __local address space. 5577 if (R.getAddressSpace() == LangAS::opencl_local) { 5578 SC = SC_OpenCLWorkGroupLocal; 5579 } 5580 5581 // OpenCL v1.2 s6.9.b p4: 5582 // The sampler type cannot be used with the __local and __global address 5583 // space qualifiers. 5584 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5585 R.getAddressSpace() == LangAS::opencl_global)) { 5586 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5587 } 5588 5589 // OpenCL 1.2 spec, p6.9 r: 5590 // The event type cannot be used to declare a program scope variable. 5591 // The event type cannot be used with the __local, __constant and __global 5592 // address space qualifiers. 5593 if (R->isEventT()) { 5594 if (S->getParent() == nullptr) { 5595 Diag(D.getLocStart(), diag::err_event_t_global_var); 5596 D.setInvalidType(); 5597 } 5598 5599 if (R.getAddressSpace()) { 5600 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5601 D.setInvalidType(); 5602 } 5603 } 5604 } 5605 5606 bool IsExplicitSpecialization = false; 5607 bool IsVariableTemplateSpecialization = false; 5608 bool IsPartialSpecialization = false; 5609 bool IsVariableTemplate = false; 5610 VarDecl *NewVD = nullptr; 5611 VarTemplateDecl *NewTemplate = nullptr; 5612 TemplateParameterList *TemplateParams = nullptr; 5613 if (!getLangOpts().CPlusPlus) { 5614 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5615 D.getIdentifierLoc(), II, 5616 R, TInfo, SC); 5617 5618 if (D.isInvalidType()) 5619 NewVD->setInvalidDecl(); 5620 } else { 5621 bool Invalid = false; 5622 5623 if (DC->isRecord() && !CurContext->isRecord()) { 5624 // This is an out-of-line definition of a static data member. 5625 switch (SC) { 5626 case SC_None: 5627 break; 5628 case SC_Static: 5629 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5630 diag::err_static_out_of_line) 5631 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5632 break; 5633 case SC_Auto: 5634 case SC_Register: 5635 case SC_Extern: 5636 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5637 // to names of variables declared in a block or to function parameters. 5638 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5639 // of class members 5640 5641 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5642 diag::err_storage_class_for_static_member) 5643 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5644 break; 5645 case SC_PrivateExtern: 5646 llvm_unreachable("C storage class in c++!"); 5647 case SC_OpenCLWorkGroupLocal: 5648 llvm_unreachable("OpenCL storage class in c++!"); 5649 } 5650 } 5651 5652 if (SC == SC_Static && CurContext->isRecord()) { 5653 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5654 if (RD->isLocalClass()) 5655 Diag(D.getIdentifierLoc(), 5656 diag::err_static_data_member_not_allowed_in_local_class) 5657 << Name << RD->getDeclName(); 5658 5659 // C++98 [class.union]p1: If a union contains a static data member, 5660 // the program is ill-formed. C++11 drops this restriction. 5661 if (RD->isUnion()) 5662 Diag(D.getIdentifierLoc(), 5663 getLangOpts().CPlusPlus11 5664 ? diag::warn_cxx98_compat_static_data_member_in_union 5665 : diag::ext_static_data_member_in_union) << Name; 5666 // We conservatively disallow static data members in anonymous structs. 5667 else if (!RD->getDeclName()) 5668 Diag(D.getIdentifierLoc(), 5669 diag::err_static_data_member_not_allowed_in_anon_struct) 5670 << Name << RD->isUnion(); 5671 } 5672 } 5673 5674 // Match up the template parameter lists with the scope specifier, then 5675 // determine whether we have a template or a template specialization. 5676 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5677 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5678 D.getCXXScopeSpec(), 5679 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5680 ? D.getName().TemplateId 5681 : nullptr, 5682 TemplateParamLists, 5683 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5684 5685 if (TemplateParams) { 5686 if (!TemplateParams->size() && 5687 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5688 // There is an extraneous 'template<>' for this variable. Complain 5689 // about it, but allow the declaration of the variable. 5690 Diag(TemplateParams->getTemplateLoc(), 5691 diag::err_template_variable_noparams) 5692 << II 5693 << SourceRange(TemplateParams->getTemplateLoc(), 5694 TemplateParams->getRAngleLoc()); 5695 TemplateParams = nullptr; 5696 } else { 5697 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5698 // This is an explicit specialization or a partial specialization. 5699 // FIXME: Check that we can declare a specialization here. 5700 IsVariableTemplateSpecialization = true; 5701 IsPartialSpecialization = TemplateParams->size() > 0; 5702 } else { // if (TemplateParams->size() > 0) 5703 // This is a template declaration. 5704 IsVariableTemplate = true; 5705 5706 // Check that we can declare a template here. 5707 if (CheckTemplateDeclScope(S, TemplateParams)) 5708 return nullptr; 5709 5710 // Only C++1y supports variable templates (N3651). 5711 Diag(D.getIdentifierLoc(), 5712 getLangOpts().CPlusPlus14 5713 ? diag::warn_cxx11_compat_variable_template 5714 : diag::ext_variable_template); 5715 } 5716 } 5717 } else { 5718 assert( 5719 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 5720 "should have a 'template<>' for this decl"); 5721 } 5722 5723 if (IsVariableTemplateSpecialization) { 5724 SourceLocation TemplateKWLoc = 5725 TemplateParamLists.size() > 0 5726 ? TemplateParamLists[0]->getTemplateLoc() 5727 : SourceLocation(); 5728 DeclResult Res = ActOnVarTemplateSpecialization( 5729 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5730 IsPartialSpecialization); 5731 if (Res.isInvalid()) 5732 return nullptr; 5733 NewVD = cast<VarDecl>(Res.get()); 5734 AddToScope = false; 5735 } else 5736 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5737 D.getIdentifierLoc(), II, R, TInfo, SC); 5738 5739 // If this is supposed to be a variable template, create it as such. 5740 if (IsVariableTemplate) { 5741 NewTemplate = 5742 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5743 TemplateParams, NewVD); 5744 NewVD->setDescribedVarTemplate(NewTemplate); 5745 } 5746 5747 // If this decl has an auto type in need of deduction, make a note of the 5748 // Decl so we can diagnose uses of it in its own initializer. 5749 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5750 ParsingInitForAutoVars.insert(NewVD); 5751 5752 if (D.isInvalidType() || Invalid) { 5753 NewVD->setInvalidDecl(); 5754 if (NewTemplate) 5755 NewTemplate->setInvalidDecl(); 5756 } 5757 5758 SetNestedNameSpecifier(NewVD, D); 5759 5760 // If we have any template parameter lists that don't directly belong to 5761 // the variable (matching the scope specifier), store them. 5762 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5763 if (TemplateParamLists.size() > VDTemplateParamLists) 5764 NewVD->setTemplateParameterListsInfo( 5765 Context, TemplateParamLists.size() - VDTemplateParamLists, 5766 TemplateParamLists.data()); 5767 5768 if (D.getDeclSpec().isConstexprSpecified()) 5769 NewVD->setConstexpr(true); 5770 } 5771 5772 // Set the lexical context. If the declarator has a C++ scope specifier, the 5773 // lexical context will be different from the semantic context. 5774 NewVD->setLexicalDeclContext(CurContext); 5775 if (NewTemplate) 5776 NewTemplate->setLexicalDeclContext(CurContext); 5777 5778 if (IsLocalExternDecl) 5779 NewVD->setLocalExternDecl(); 5780 5781 bool EmitTLSUnsupportedError = false; 5782 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5783 // C++11 [dcl.stc]p4: 5784 // When thread_local is applied to a variable of block scope the 5785 // storage-class-specifier static is implied if it does not appear 5786 // explicitly. 5787 // Core issue: 'static' is not implied if the variable is declared 5788 // 'extern'. 5789 if (NewVD->hasLocalStorage() && 5790 (SCSpec != DeclSpec::SCS_unspecified || 5791 TSCS != DeclSpec::TSCS_thread_local || 5792 !DC->isFunctionOrMethod())) 5793 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5794 diag::err_thread_non_global) 5795 << DeclSpec::getSpecifierName(TSCS); 5796 else if (!Context.getTargetInfo().isTLSSupported()) { 5797 if (getLangOpts().CUDA) { 5798 // Postpone error emission until we've collected attributes required to 5799 // figure out whether it's a host or device variable and whether the 5800 // error should be ignored. 5801 EmitTLSUnsupportedError = true; 5802 // We still need to mark the variable as TLS so it shows up in AST with 5803 // proper storage class for other tools to use even if we're not going 5804 // to emit any code for it. 5805 NewVD->setTSCSpec(TSCS); 5806 } else 5807 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5808 diag::err_thread_unsupported); 5809 } else 5810 NewVD->setTSCSpec(TSCS); 5811 } 5812 5813 // C99 6.7.4p3 5814 // An inline definition of a function with external linkage shall 5815 // not contain a definition of a modifiable object with static or 5816 // thread storage duration... 5817 // We only apply this when the function is required to be defined 5818 // elsewhere, i.e. when the function is not 'extern inline'. Note 5819 // that a local variable with thread storage duration still has to 5820 // be marked 'static'. Also note that it's possible to get these 5821 // semantics in C++ using __attribute__((gnu_inline)). 5822 if (SC == SC_Static && S->getFnParent() != nullptr && 5823 !NewVD->getType().isConstQualified()) { 5824 FunctionDecl *CurFD = getCurFunctionDecl(); 5825 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5826 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5827 diag::warn_static_local_in_extern_inline); 5828 MaybeSuggestAddingStaticToDecl(CurFD); 5829 } 5830 } 5831 5832 if (D.getDeclSpec().isModulePrivateSpecified()) { 5833 if (IsVariableTemplateSpecialization) 5834 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5835 << (IsPartialSpecialization ? 1 : 0) 5836 << FixItHint::CreateRemoval( 5837 D.getDeclSpec().getModulePrivateSpecLoc()); 5838 else if (IsExplicitSpecialization) 5839 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5840 << 2 5841 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5842 else if (NewVD->hasLocalStorage()) 5843 Diag(NewVD->getLocation(), diag::err_module_private_local) 5844 << 0 << NewVD->getDeclName() 5845 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5846 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5847 else { 5848 NewVD->setModulePrivate(); 5849 if (NewTemplate) 5850 NewTemplate->setModulePrivate(); 5851 } 5852 } 5853 5854 // Handle attributes prior to checking for duplicates in MergeVarDecl 5855 ProcessDeclAttributes(S, NewVD, D); 5856 5857 if (getLangOpts().CUDA) { 5858 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 5859 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5860 diag::err_thread_unsupported); 5861 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5862 // storage [duration]." 5863 if (SC == SC_None && S->getFnParent() != nullptr && 5864 (NewVD->hasAttr<CUDASharedAttr>() || 5865 NewVD->hasAttr<CUDAConstantAttr>())) { 5866 NewVD->setStorageClass(SC_Static); 5867 } 5868 } 5869 5870 // Ensure that dllimport globals without explicit storage class are treated as 5871 // extern. The storage class is set above using parsed attributes. Now we can 5872 // check the VarDecl itself. 5873 assert(!NewVD->hasAttr<DLLImportAttr>() || 5874 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5875 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5876 5877 // In auto-retain/release, infer strong retension for variables of 5878 // retainable type. 5879 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5880 NewVD->setInvalidDecl(); 5881 5882 // Handle GNU asm-label extension (encoded as an attribute). 5883 if (Expr *E = (Expr*)D.getAsmLabel()) { 5884 // The parser guarantees this is a string. 5885 StringLiteral *SE = cast<StringLiteral>(E); 5886 StringRef Label = SE->getString(); 5887 if (S->getFnParent() != nullptr) { 5888 switch (SC) { 5889 case SC_None: 5890 case SC_Auto: 5891 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5892 break; 5893 case SC_Register: 5894 // Local Named register 5895 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5896 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5897 break; 5898 case SC_Static: 5899 case SC_Extern: 5900 case SC_PrivateExtern: 5901 case SC_OpenCLWorkGroupLocal: 5902 break; 5903 } 5904 } else if (SC == SC_Register) { 5905 // Global Named register 5906 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5907 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5908 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5909 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5910 NewVD->setInvalidDecl(true); 5911 } 5912 } 5913 5914 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5915 Context, Label, 0)); 5916 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5917 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5918 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5919 if (I != ExtnameUndeclaredIdentifiers.end()) { 5920 NewVD->addAttr(I->second); 5921 ExtnameUndeclaredIdentifiers.erase(I); 5922 } 5923 } 5924 5925 // Diagnose shadowed variables before filtering for scope. 5926 if (D.getCXXScopeSpec().isEmpty()) 5927 CheckShadow(S, NewVD, Previous); 5928 5929 // Don't consider existing declarations that are in a different 5930 // scope and are out-of-semantic-context declarations (if the new 5931 // declaration has linkage). 5932 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5933 D.getCXXScopeSpec().isNotEmpty() || 5934 IsExplicitSpecialization || 5935 IsVariableTemplateSpecialization); 5936 5937 // Check whether the previous declaration is in the same block scope. This 5938 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5939 if (getLangOpts().CPlusPlus && 5940 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5941 NewVD->setPreviousDeclInSameBlockScope( 5942 Previous.isSingleResult() && !Previous.isShadowed() && 5943 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5944 5945 if (!getLangOpts().CPlusPlus) { 5946 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5947 } else { 5948 // If this is an explicit specialization of a static data member, check it. 5949 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5950 CheckMemberSpecialization(NewVD, Previous)) 5951 NewVD->setInvalidDecl(); 5952 5953 // Merge the decl with the existing one if appropriate. 5954 if (!Previous.empty()) { 5955 if (Previous.isSingleResult() && 5956 isa<FieldDecl>(Previous.getFoundDecl()) && 5957 D.getCXXScopeSpec().isSet()) { 5958 // The user tried to define a non-static data member 5959 // out-of-line (C++ [dcl.meaning]p1). 5960 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5961 << D.getCXXScopeSpec().getRange(); 5962 Previous.clear(); 5963 NewVD->setInvalidDecl(); 5964 } 5965 } else if (D.getCXXScopeSpec().isSet()) { 5966 // No previous declaration in the qualifying scope. 5967 Diag(D.getIdentifierLoc(), diag::err_no_member) 5968 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5969 << D.getCXXScopeSpec().getRange(); 5970 NewVD->setInvalidDecl(); 5971 } 5972 5973 if (!IsVariableTemplateSpecialization) 5974 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5975 5976 if (NewTemplate) { 5977 VarTemplateDecl *PrevVarTemplate = 5978 NewVD->getPreviousDecl() 5979 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5980 : nullptr; 5981 5982 // Check the template parameter list of this declaration, possibly 5983 // merging in the template parameter list from the previous variable 5984 // template declaration. 5985 if (CheckTemplateParameterList( 5986 TemplateParams, 5987 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5988 : nullptr, 5989 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5990 DC->isDependentContext()) 5991 ? TPC_ClassTemplateMember 5992 : TPC_VarTemplate)) 5993 NewVD->setInvalidDecl(); 5994 5995 // If we are providing an explicit specialization of a static variable 5996 // template, make a note of that. 5997 if (PrevVarTemplate && 5998 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5999 PrevVarTemplate->setMemberSpecialization(); 6000 } 6001 } 6002 6003 ProcessPragmaWeak(S, NewVD); 6004 6005 // If this is the first declaration of an extern C variable, update 6006 // the map of such variables. 6007 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6008 isIncompleteDeclExternC(*this, NewVD)) 6009 RegisterLocallyScopedExternCDecl(NewVD, S); 6010 6011 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6012 Decl *ManglingContextDecl; 6013 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6014 NewVD->getDeclContext(), ManglingContextDecl)) { 6015 Context.setManglingNumber( 6016 NewVD, MCtx->getManglingNumber( 6017 NewVD, getMSManglingNumber(getLangOpts(), S))); 6018 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6019 } 6020 } 6021 6022 if (D.isRedeclaration() && !Previous.empty()) { 6023 checkDLLAttributeRedeclaration( 6024 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6025 IsExplicitSpecialization); 6026 } 6027 6028 if (NewTemplate) { 6029 if (NewVD->isInvalidDecl()) 6030 NewTemplate->setInvalidDecl(); 6031 ActOnDocumentableDecl(NewTemplate); 6032 return NewTemplate; 6033 } 6034 6035 return NewVD; 6036 } 6037 6038 /// \brief Diagnose variable or built-in function shadowing. Implements 6039 /// -Wshadow. 6040 /// 6041 /// This method is called whenever a VarDecl is added to a "useful" 6042 /// scope. 6043 /// 6044 /// \param S the scope in which the shadowing name is being declared 6045 /// \param R the lookup of the name 6046 /// 6047 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6048 // Return if warning is ignored. 6049 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6050 return; 6051 6052 // Don't diagnose declarations at file scope. 6053 if (D->hasGlobalStorage()) 6054 return; 6055 6056 DeclContext *NewDC = D->getDeclContext(); 6057 6058 // Only diagnose if we're shadowing an unambiguous field or variable. 6059 if (R.getResultKind() != LookupResult::Found) 6060 return; 6061 6062 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6063 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6064 return; 6065 6066 // Fields are not shadowed by variables in C++ static methods. 6067 if (isa<FieldDecl>(ShadowedDecl)) 6068 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6069 if (MD->isStatic()) 6070 return; 6071 6072 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6073 if (shadowedVar->isExternC()) { 6074 // For shadowing external vars, make sure that we point to the global 6075 // declaration, not a locally scoped extern declaration. 6076 for (auto I : shadowedVar->redecls()) 6077 if (I->isFileVarDecl()) { 6078 ShadowedDecl = I; 6079 break; 6080 } 6081 } 6082 6083 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6084 6085 // Only warn about certain kinds of shadowing for class members. 6086 if (NewDC && NewDC->isRecord()) { 6087 // In particular, don't warn about shadowing non-class members. 6088 if (!OldDC->isRecord()) 6089 return; 6090 6091 // TODO: should we warn about static data members shadowing 6092 // static data members from base classes? 6093 6094 // TODO: don't diagnose for inaccessible shadowed members. 6095 // This is hard to do perfectly because we might friend the 6096 // shadowing context, but that's just a false negative. 6097 } 6098 6099 // Determine what kind of declaration we're shadowing. 6100 unsigned Kind; 6101 if (isa<RecordDecl>(OldDC)) { 6102 if (isa<FieldDecl>(ShadowedDecl)) 6103 Kind = 3; // field 6104 else 6105 Kind = 2; // static data member 6106 } else if (OldDC->isFileContext()) 6107 Kind = 1; // global 6108 else 6109 Kind = 0; // local 6110 6111 DeclarationName Name = R.getLookupName(); 6112 6113 // Emit warning and note. 6114 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6115 return; 6116 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6117 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6118 } 6119 6120 /// \brief Check -Wshadow without the advantage of a previous lookup. 6121 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6122 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6123 return; 6124 6125 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6126 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6127 LookupName(R, S); 6128 CheckShadow(S, D, R); 6129 } 6130 6131 /// Check for conflict between this global or extern "C" declaration and 6132 /// previous global or extern "C" declarations. This is only used in C++. 6133 template<typename T> 6134 static bool checkGlobalOrExternCConflict( 6135 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6136 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6137 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6138 6139 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6140 // The common case: this global doesn't conflict with any extern "C" 6141 // declaration. 6142 return false; 6143 } 6144 6145 if (Prev) { 6146 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6147 // Both the old and new declarations have C language linkage. This is a 6148 // redeclaration. 6149 Previous.clear(); 6150 Previous.addDecl(Prev); 6151 return true; 6152 } 6153 6154 // This is a global, non-extern "C" declaration, and there is a previous 6155 // non-global extern "C" declaration. Diagnose if this is a variable 6156 // declaration. 6157 if (!isa<VarDecl>(ND)) 6158 return false; 6159 } else { 6160 // The declaration is extern "C". Check for any declaration in the 6161 // translation unit which might conflict. 6162 if (IsGlobal) { 6163 // We have already performed the lookup into the translation unit. 6164 IsGlobal = false; 6165 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6166 I != E; ++I) { 6167 if (isa<VarDecl>(*I)) { 6168 Prev = *I; 6169 break; 6170 } 6171 } 6172 } else { 6173 DeclContext::lookup_result R = 6174 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6175 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6176 I != E; ++I) { 6177 if (isa<VarDecl>(*I)) { 6178 Prev = *I; 6179 break; 6180 } 6181 // FIXME: If we have any other entity with this name in global scope, 6182 // the declaration is ill-formed, but that is a defect: it breaks the 6183 // 'stat' hack, for instance. Only variables can have mangled name 6184 // clashes with extern "C" declarations, so only they deserve a 6185 // diagnostic. 6186 } 6187 } 6188 6189 if (!Prev) 6190 return false; 6191 } 6192 6193 // Use the first declaration's location to ensure we point at something which 6194 // is lexically inside an extern "C" linkage-spec. 6195 assert(Prev && "should have found a previous declaration to diagnose"); 6196 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6197 Prev = FD->getFirstDecl(); 6198 else 6199 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6200 6201 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6202 << IsGlobal << ND; 6203 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6204 << IsGlobal; 6205 return false; 6206 } 6207 6208 /// Apply special rules for handling extern "C" declarations. Returns \c true 6209 /// if we have found that this is a redeclaration of some prior entity. 6210 /// 6211 /// Per C++ [dcl.link]p6: 6212 /// Two declarations [for a function or variable] with C language linkage 6213 /// with the same name that appear in different scopes refer to the same 6214 /// [entity]. An entity with C language linkage shall not be declared with 6215 /// the same name as an entity in global scope. 6216 template<typename T> 6217 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6218 LookupResult &Previous) { 6219 if (!S.getLangOpts().CPlusPlus) { 6220 // In C, when declaring a global variable, look for a corresponding 'extern' 6221 // variable declared in function scope. We don't need this in C++, because 6222 // we find local extern decls in the surrounding file-scope DeclContext. 6223 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6224 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6225 Previous.clear(); 6226 Previous.addDecl(Prev); 6227 return true; 6228 } 6229 } 6230 return false; 6231 } 6232 6233 // A declaration in the translation unit can conflict with an extern "C" 6234 // declaration. 6235 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6236 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6237 6238 // An extern "C" declaration can conflict with a declaration in the 6239 // translation unit or can be a redeclaration of an extern "C" declaration 6240 // in another scope. 6241 if (isIncompleteDeclExternC(S,ND)) 6242 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6243 6244 // Neither global nor extern "C": nothing to do. 6245 return false; 6246 } 6247 6248 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6249 // If the decl is already known invalid, don't check it. 6250 if (NewVD->isInvalidDecl()) 6251 return; 6252 6253 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6254 QualType T = TInfo->getType(); 6255 6256 // Defer checking an 'auto' type until its initializer is attached. 6257 if (T->isUndeducedType()) 6258 return; 6259 6260 if (NewVD->hasAttrs()) 6261 CheckAlignasUnderalignment(NewVD); 6262 6263 if (T->isObjCObjectType()) { 6264 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6265 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6266 T = Context.getObjCObjectPointerType(T); 6267 NewVD->setType(T); 6268 } 6269 6270 // Emit an error if an address space was applied to decl with local storage. 6271 // This includes arrays of objects with address space qualifiers, but not 6272 // automatic variables that point to other address spaces. 6273 // ISO/IEC TR 18037 S5.1.2 6274 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6275 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6276 NewVD->setInvalidDecl(); 6277 return; 6278 } 6279 6280 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6281 // __constant address space. 6282 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 6283 && T.getAddressSpace() != LangAS::opencl_constant 6284 && !T->isSamplerT()){ 6285 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 6286 NewVD->setInvalidDecl(); 6287 return; 6288 } 6289 6290 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6291 // scope. 6292 if ((getLangOpts().OpenCLVersion >= 120) 6293 && NewVD->isStaticLocal()) { 6294 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6295 NewVD->setInvalidDecl(); 6296 return; 6297 } 6298 6299 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6300 && !NewVD->hasAttr<BlocksAttr>()) { 6301 if (getLangOpts().getGC() != LangOptions::NonGC) 6302 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6303 else { 6304 assert(!getLangOpts().ObjCAutoRefCount); 6305 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6306 } 6307 } 6308 6309 bool isVM = T->isVariablyModifiedType(); 6310 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6311 NewVD->hasAttr<BlocksAttr>()) 6312 getCurFunction()->setHasBranchProtectedScope(); 6313 6314 if ((isVM && NewVD->hasLinkage()) || 6315 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6316 bool SizeIsNegative; 6317 llvm::APSInt Oversized; 6318 TypeSourceInfo *FixedTInfo = 6319 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6320 SizeIsNegative, Oversized); 6321 if (!FixedTInfo && T->isVariableArrayType()) { 6322 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6323 // FIXME: This won't give the correct result for 6324 // int a[10][n]; 6325 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6326 6327 if (NewVD->isFileVarDecl()) 6328 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6329 << SizeRange; 6330 else if (NewVD->isStaticLocal()) 6331 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6332 << SizeRange; 6333 else 6334 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6335 << SizeRange; 6336 NewVD->setInvalidDecl(); 6337 return; 6338 } 6339 6340 if (!FixedTInfo) { 6341 if (NewVD->isFileVarDecl()) 6342 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6343 else 6344 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6345 NewVD->setInvalidDecl(); 6346 return; 6347 } 6348 6349 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6350 NewVD->setType(FixedTInfo->getType()); 6351 NewVD->setTypeSourceInfo(FixedTInfo); 6352 } 6353 6354 if (T->isVoidType()) { 6355 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6356 // of objects and functions. 6357 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6358 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6359 << T; 6360 NewVD->setInvalidDecl(); 6361 return; 6362 } 6363 } 6364 6365 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6366 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6367 NewVD->setInvalidDecl(); 6368 return; 6369 } 6370 6371 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6372 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6373 NewVD->setInvalidDecl(); 6374 return; 6375 } 6376 6377 if (NewVD->isConstexpr() && !T->isDependentType() && 6378 RequireLiteralType(NewVD->getLocation(), T, 6379 diag::err_constexpr_var_non_literal)) { 6380 NewVD->setInvalidDecl(); 6381 return; 6382 } 6383 } 6384 6385 /// \brief Perform semantic checking on a newly-created variable 6386 /// declaration. 6387 /// 6388 /// This routine performs all of the type-checking required for a 6389 /// variable declaration once it has been built. It is used both to 6390 /// check variables after they have been parsed and their declarators 6391 /// have been translated into a declaration, and to check variables 6392 /// that have been instantiated from a template. 6393 /// 6394 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6395 /// 6396 /// Returns true if the variable declaration is a redeclaration. 6397 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6398 CheckVariableDeclarationType(NewVD); 6399 6400 // If the decl is already known invalid, don't check it. 6401 if (NewVD->isInvalidDecl()) 6402 return false; 6403 6404 // If we did not find anything by this name, look for a non-visible 6405 // extern "C" declaration with the same name. 6406 if (Previous.empty() && 6407 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6408 Previous.setShadowed(); 6409 6410 // Filter out any non-conflicting previous declarations. 6411 filterNonConflictingPreviousDecls(*this, NewVD, Previous); 6412 6413 if (!Previous.empty()) { 6414 MergeVarDecl(NewVD, Previous); 6415 return true; 6416 } 6417 return false; 6418 } 6419 6420 /// \brief Data used with FindOverriddenMethod 6421 struct FindOverriddenMethodData { 6422 Sema *S; 6423 CXXMethodDecl *Method; 6424 }; 6425 6426 /// \brief Member lookup function that determines whether a given C++ 6427 /// method overrides a method in a base class, to be used with 6428 /// CXXRecordDecl::lookupInBases(). 6429 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6430 CXXBasePath &Path, 6431 void *UserData) { 6432 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6433 6434 FindOverriddenMethodData *Data 6435 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6436 6437 DeclarationName Name = Data->Method->getDeclName(); 6438 6439 // FIXME: Do we care about other names here too? 6440 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6441 // We really want to find the base class destructor here. 6442 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6443 CanQualType CT = Data->S->Context.getCanonicalType(T); 6444 6445 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6446 } 6447 6448 for (Path.Decls = BaseRecord->lookup(Name); 6449 !Path.Decls.empty(); 6450 Path.Decls = Path.Decls.slice(1)) { 6451 NamedDecl *D = Path.Decls.front(); 6452 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6453 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6454 return true; 6455 } 6456 } 6457 6458 return false; 6459 } 6460 6461 namespace { 6462 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6463 } 6464 /// \brief Report an error regarding overriding, along with any relevant 6465 /// overriden methods. 6466 /// 6467 /// \param DiagID the primary error to report. 6468 /// \param MD the overriding method. 6469 /// \param OEK which overrides to include as notes. 6470 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6471 OverrideErrorKind OEK = OEK_All) { 6472 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6473 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6474 E = MD->end_overridden_methods(); 6475 I != E; ++I) { 6476 // This check (& the OEK parameter) could be replaced by a predicate, but 6477 // without lambdas that would be overkill. This is still nicer than writing 6478 // out the diag loop 3 times. 6479 if ((OEK == OEK_All) || 6480 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6481 (OEK == OEK_Deleted && (*I)->isDeleted())) 6482 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6483 } 6484 } 6485 6486 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6487 /// and if so, check that it's a valid override and remember it. 6488 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6489 // Look for methods in base classes that this method might override. 6490 CXXBasePaths Paths; 6491 FindOverriddenMethodData Data; 6492 Data.Method = MD; 6493 Data.S = this; 6494 bool hasDeletedOverridenMethods = false; 6495 bool hasNonDeletedOverridenMethods = false; 6496 bool AddedAny = false; 6497 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6498 for (auto *I : Paths.found_decls()) { 6499 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6500 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6501 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6502 !CheckOverridingFunctionAttributes(MD, OldMD) && 6503 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6504 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6505 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6506 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6507 AddedAny = true; 6508 } 6509 } 6510 } 6511 } 6512 6513 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6514 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6515 } 6516 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6517 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6518 } 6519 6520 return AddedAny; 6521 } 6522 6523 namespace { 6524 // Struct for holding all of the extra arguments needed by 6525 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6526 struct ActOnFDArgs { 6527 Scope *S; 6528 Declarator &D; 6529 MultiTemplateParamsArg TemplateParamLists; 6530 bool AddToScope; 6531 }; 6532 } 6533 6534 namespace { 6535 6536 // Callback to only accept typo corrections that have a non-zero edit distance. 6537 // Also only accept corrections that have the same parent decl. 6538 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6539 public: 6540 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6541 CXXRecordDecl *Parent) 6542 : Context(Context), OriginalFD(TypoFD), 6543 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6544 6545 bool ValidateCandidate(const TypoCorrection &candidate) override { 6546 if (candidate.getEditDistance() == 0) 6547 return false; 6548 6549 SmallVector<unsigned, 1> MismatchedParams; 6550 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6551 CDeclEnd = candidate.end(); 6552 CDecl != CDeclEnd; ++CDecl) { 6553 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6554 6555 if (FD && !FD->hasBody() && 6556 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6557 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6558 CXXRecordDecl *Parent = MD->getParent(); 6559 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6560 return true; 6561 } else if (!ExpectedParent) { 6562 return true; 6563 } 6564 } 6565 } 6566 6567 return false; 6568 } 6569 6570 private: 6571 ASTContext &Context; 6572 FunctionDecl *OriginalFD; 6573 CXXRecordDecl *ExpectedParent; 6574 }; 6575 6576 } 6577 6578 /// \brief Generate diagnostics for an invalid function redeclaration. 6579 /// 6580 /// This routine handles generating the diagnostic messages for an invalid 6581 /// function redeclaration, including finding possible similar declarations 6582 /// or performing typo correction if there are no previous declarations with 6583 /// the same name. 6584 /// 6585 /// Returns a NamedDecl iff typo correction was performed and substituting in 6586 /// the new declaration name does not cause new errors. 6587 static NamedDecl *DiagnoseInvalidRedeclaration( 6588 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6589 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6590 DeclarationName Name = NewFD->getDeclName(); 6591 DeclContext *NewDC = NewFD->getDeclContext(); 6592 SmallVector<unsigned, 1> MismatchedParams; 6593 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6594 TypoCorrection Correction; 6595 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6596 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6597 : diag::err_member_decl_does_not_match; 6598 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6599 IsLocalFriend ? Sema::LookupLocalFriendName 6600 : Sema::LookupOrdinaryName, 6601 Sema::ForRedeclaration); 6602 6603 NewFD->setInvalidDecl(); 6604 if (IsLocalFriend) 6605 SemaRef.LookupName(Prev, S); 6606 else 6607 SemaRef.LookupQualifiedName(Prev, NewDC); 6608 assert(!Prev.isAmbiguous() && 6609 "Cannot have an ambiguity in previous-declaration lookup"); 6610 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6611 if (!Prev.empty()) { 6612 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6613 Func != FuncEnd; ++Func) { 6614 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6615 if (FD && 6616 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6617 // Add 1 to the index so that 0 can mean the mismatch didn't 6618 // involve a parameter 6619 unsigned ParamNum = 6620 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6621 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6622 } 6623 } 6624 // If the qualified name lookup yielded nothing, try typo correction 6625 } else if ((Correction = SemaRef.CorrectTypo( 6626 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6627 &ExtraArgs.D.getCXXScopeSpec(), 6628 llvm::make_unique<DifferentNameValidatorCCC>( 6629 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 6630 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6631 // Set up everything for the call to ActOnFunctionDeclarator 6632 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6633 ExtraArgs.D.getIdentifierLoc()); 6634 Previous.clear(); 6635 Previous.setLookupName(Correction.getCorrection()); 6636 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6637 CDeclEnd = Correction.end(); 6638 CDecl != CDeclEnd; ++CDecl) { 6639 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6640 if (FD && !FD->hasBody() && 6641 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6642 Previous.addDecl(FD); 6643 } 6644 } 6645 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6646 6647 NamedDecl *Result; 6648 // Retry building the function declaration with the new previous 6649 // declarations, and with errors suppressed. 6650 { 6651 // Trap errors. 6652 Sema::SFINAETrap Trap(SemaRef); 6653 6654 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6655 // pieces need to verify the typo-corrected C++ declaration and hopefully 6656 // eliminate the need for the parameter pack ExtraArgs. 6657 Result = SemaRef.ActOnFunctionDeclarator( 6658 ExtraArgs.S, ExtraArgs.D, 6659 Correction.getCorrectionDecl()->getDeclContext(), 6660 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6661 ExtraArgs.AddToScope); 6662 6663 if (Trap.hasErrorOccurred()) 6664 Result = nullptr; 6665 } 6666 6667 if (Result) { 6668 // Determine which correction we picked. 6669 Decl *Canonical = Result->getCanonicalDecl(); 6670 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6671 I != E; ++I) 6672 if ((*I)->getCanonicalDecl() == Canonical) 6673 Correction.setCorrectionDecl(*I); 6674 6675 SemaRef.diagnoseTypo( 6676 Correction, 6677 SemaRef.PDiag(IsLocalFriend 6678 ? diag::err_no_matching_local_friend_suggest 6679 : diag::err_member_decl_does_not_match_suggest) 6680 << Name << NewDC << IsDefinition); 6681 return Result; 6682 } 6683 6684 // Pretend the typo correction never occurred 6685 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6686 ExtraArgs.D.getIdentifierLoc()); 6687 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6688 Previous.clear(); 6689 Previous.setLookupName(Name); 6690 } 6691 6692 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6693 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6694 6695 bool NewFDisConst = false; 6696 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6697 NewFDisConst = NewMD->isConst(); 6698 6699 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6700 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6701 NearMatch != NearMatchEnd; ++NearMatch) { 6702 FunctionDecl *FD = NearMatch->first; 6703 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6704 bool FDisConst = MD && MD->isConst(); 6705 bool IsMember = MD || !IsLocalFriend; 6706 6707 // FIXME: These notes are poorly worded for the local friend case. 6708 if (unsigned Idx = NearMatch->second) { 6709 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6710 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6711 if (Loc.isInvalid()) Loc = FD->getLocation(); 6712 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6713 : diag::note_local_decl_close_param_match) 6714 << Idx << FDParam->getType() 6715 << NewFD->getParamDecl(Idx - 1)->getType(); 6716 } else if (FDisConst != NewFDisConst) { 6717 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6718 << NewFDisConst << FD->getSourceRange().getEnd(); 6719 } else 6720 SemaRef.Diag(FD->getLocation(), 6721 IsMember ? diag::note_member_def_close_match 6722 : diag::note_local_decl_close_match); 6723 } 6724 return nullptr; 6725 } 6726 6727 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 6728 switch (D.getDeclSpec().getStorageClassSpec()) { 6729 default: llvm_unreachable("Unknown storage class!"); 6730 case DeclSpec::SCS_auto: 6731 case DeclSpec::SCS_register: 6732 case DeclSpec::SCS_mutable: 6733 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6734 diag::err_typecheck_sclass_func); 6735 D.setInvalidType(); 6736 break; 6737 case DeclSpec::SCS_unspecified: break; 6738 case DeclSpec::SCS_extern: 6739 if (D.getDeclSpec().isExternInLinkageSpec()) 6740 return SC_None; 6741 return SC_Extern; 6742 case DeclSpec::SCS_static: { 6743 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6744 // C99 6.7.1p5: 6745 // The declaration of an identifier for a function that has 6746 // block scope shall have no explicit storage-class specifier 6747 // other than extern 6748 // See also (C++ [dcl.stc]p4). 6749 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6750 diag::err_static_block_func); 6751 break; 6752 } else 6753 return SC_Static; 6754 } 6755 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6756 } 6757 6758 // No explicit storage class has already been returned 6759 return SC_None; 6760 } 6761 6762 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6763 DeclContext *DC, QualType &R, 6764 TypeSourceInfo *TInfo, 6765 StorageClass SC, 6766 bool &IsVirtualOkay) { 6767 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6768 DeclarationName Name = NameInfo.getName(); 6769 6770 FunctionDecl *NewFD = nullptr; 6771 bool isInline = D.getDeclSpec().isInlineSpecified(); 6772 6773 if (!SemaRef.getLangOpts().CPlusPlus) { 6774 // Determine whether the function was written with a 6775 // prototype. This true when: 6776 // - there is a prototype in the declarator, or 6777 // - the type R of the function is some kind of typedef or other reference 6778 // to a type name (which eventually refers to a function type). 6779 bool HasPrototype = 6780 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6781 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6782 6783 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6784 D.getLocStart(), NameInfo, R, 6785 TInfo, SC, isInline, 6786 HasPrototype, false); 6787 if (D.isInvalidType()) 6788 NewFD->setInvalidDecl(); 6789 6790 return NewFD; 6791 } 6792 6793 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6794 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6795 6796 // Check that the return type is not an abstract class type. 6797 // For record types, this is done by the AbstractClassUsageDiagnoser once 6798 // the class has been completely parsed. 6799 if (!DC->isRecord() && 6800 SemaRef.RequireNonAbstractType( 6801 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6802 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6803 D.setInvalidType(); 6804 6805 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6806 // This is a C++ constructor declaration. 6807 assert(DC->isRecord() && 6808 "Constructors can only be declared in a member context"); 6809 6810 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6811 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6812 D.getLocStart(), NameInfo, 6813 R, TInfo, isExplicit, isInline, 6814 /*isImplicitlyDeclared=*/false, 6815 isConstexpr); 6816 6817 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6818 // This is a C++ destructor declaration. 6819 if (DC->isRecord()) { 6820 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6821 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6822 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6823 SemaRef.Context, Record, 6824 D.getLocStart(), 6825 NameInfo, R, TInfo, isInline, 6826 /*isImplicitlyDeclared=*/false); 6827 6828 // If the class is complete, then we now create the implicit exception 6829 // specification. If the class is incomplete or dependent, we can't do 6830 // it yet. 6831 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6832 Record->getDefinition() && !Record->isBeingDefined() && 6833 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6834 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6835 } 6836 6837 IsVirtualOkay = true; 6838 return NewDD; 6839 6840 } else { 6841 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6842 D.setInvalidType(); 6843 6844 // Create a FunctionDecl to satisfy the function definition parsing 6845 // code path. 6846 return FunctionDecl::Create(SemaRef.Context, DC, 6847 D.getLocStart(), 6848 D.getIdentifierLoc(), Name, R, TInfo, 6849 SC, isInline, 6850 /*hasPrototype=*/true, isConstexpr); 6851 } 6852 6853 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6854 if (!DC->isRecord()) { 6855 SemaRef.Diag(D.getIdentifierLoc(), 6856 diag::err_conv_function_not_member); 6857 return nullptr; 6858 } 6859 6860 SemaRef.CheckConversionDeclarator(D, R, SC); 6861 IsVirtualOkay = true; 6862 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6863 D.getLocStart(), NameInfo, 6864 R, TInfo, isInline, isExplicit, 6865 isConstexpr, SourceLocation()); 6866 6867 } else if (DC->isRecord()) { 6868 // If the name of the function is the same as the name of the record, 6869 // then this must be an invalid constructor that has a return type. 6870 // (The parser checks for a return type and makes the declarator a 6871 // constructor if it has no return type). 6872 if (Name.getAsIdentifierInfo() && 6873 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6874 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6875 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6876 << SourceRange(D.getIdentifierLoc()); 6877 return nullptr; 6878 } 6879 6880 // This is a C++ method declaration. 6881 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6882 cast<CXXRecordDecl>(DC), 6883 D.getLocStart(), NameInfo, R, 6884 TInfo, SC, isInline, 6885 isConstexpr, SourceLocation()); 6886 IsVirtualOkay = !Ret->isStatic(); 6887 return Ret; 6888 } else { 6889 bool isFriend = 6890 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 6891 if (!isFriend && SemaRef.CurContext->isRecord()) 6892 return nullptr; 6893 6894 // Determine whether the function was written with a 6895 // prototype. This true when: 6896 // - we're in C++ (where every function has a prototype), 6897 return FunctionDecl::Create(SemaRef.Context, DC, 6898 D.getLocStart(), 6899 NameInfo, R, TInfo, SC, isInline, 6900 true/*HasPrototype*/, isConstexpr); 6901 } 6902 } 6903 6904 enum OpenCLParamType { 6905 ValidKernelParam, 6906 PtrPtrKernelParam, 6907 PtrKernelParam, 6908 PrivatePtrKernelParam, 6909 InvalidKernelParam, 6910 RecordKernelParam 6911 }; 6912 6913 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6914 if (PT->isPointerType()) { 6915 QualType PointeeType = PT->getPointeeType(); 6916 if (PointeeType->isPointerType()) 6917 return PtrPtrKernelParam; 6918 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6919 : PtrKernelParam; 6920 } 6921 6922 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6923 // be used as builtin types. 6924 6925 if (PT->isImageType()) 6926 return PtrKernelParam; 6927 6928 if (PT->isBooleanType()) 6929 return InvalidKernelParam; 6930 6931 if (PT->isEventT()) 6932 return InvalidKernelParam; 6933 6934 if (PT->isHalfType()) 6935 return InvalidKernelParam; 6936 6937 if (PT->isRecordType()) 6938 return RecordKernelParam; 6939 6940 return ValidKernelParam; 6941 } 6942 6943 static void checkIsValidOpenCLKernelParameter( 6944 Sema &S, 6945 Declarator &D, 6946 ParmVarDecl *Param, 6947 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 6948 QualType PT = Param->getType(); 6949 6950 // Cache the valid types we encounter to avoid rechecking structs that are 6951 // used again 6952 if (ValidTypes.count(PT.getTypePtr())) 6953 return; 6954 6955 switch (getOpenCLKernelParameterType(PT)) { 6956 case PtrPtrKernelParam: 6957 // OpenCL v1.2 s6.9.a: 6958 // A kernel function argument cannot be declared as a 6959 // pointer to a pointer type. 6960 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6961 D.setInvalidType(); 6962 return; 6963 6964 case PrivatePtrKernelParam: 6965 // OpenCL v1.2 s6.9.a: 6966 // A kernel function argument cannot be declared as a 6967 // pointer to the private address space. 6968 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6969 D.setInvalidType(); 6970 return; 6971 6972 // OpenCL v1.2 s6.9.k: 6973 // Arguments to kernel functions in a program cannot be declared with the 6974 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6975 // uintptr_t or a struct and/or union that contain fields declared to be 6976 // one of these built-in scalar types. 6977 6978 case InvalidKernelParam: 6979 // OpenCL v1.2 s6.8 n: 6980 // A kernel function argument cannot be declared 6981 // of event_t type. 6982 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6983 D.setInvalidType(); 6984 return; 6985 6986 case PtrKernelParam: 6987 case ValidKernelParam: 6988 ValidTypes.insert(PT.getTypePtr()); 6989 return; 6990 6991 case RecordKernelParam: 6992 break; 6993 } 6994 6995 // Track nested structs we will inspect 6996 SmallVector<const Decl *, 4> VisitStack; 6997 6998 // Track where we are in the nested structs. Items will migrate from 6999 // VisitStack to HistoryStack as we do the DFS for bad field. 7000 SmallVector<const FieldDecl *, 4> HistoryStack; 7001 HistoryStack.push_back(nullptr); 7002 7003 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7004 VisitStack.push_back(PD); 7005 7006 assert(VisitStack.back() && "First decl null?"); 7007 7008 do { 7009 const Decl *Next = VisitStack.pop_back_val(); 7010 if (!Next) { 7011 assert(!HistoryStack.empty()); 7012 // Found a marker, we have gone up a level 7013 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7014 ValidTypes.insert(Hist->getType().getTypePtr()); 7015 7016 continue; 7017 } 7018 7019 // Adds everything except the original parameter declaration (which is not a 7020 // field itself) to the history stack. 7021 const RecordDecl *RD; 7022 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7023 HistoryStack.push_back(Field); 7024 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7025 } else { 7026 RD = cast<RecordDecl>(Next); 7027 } 7028 7029 // Add a null marker so we know when we've gone back up a level 7030 VisitStack.push_back(nullptr); 7031 7032 for (const auto *FD : RD->fields()) { 7033 QualType QT = FD->getType(); 7034 7035 if (ValidTypes.count(QT.getTypePtr())) 7036 continue; 7037 7038 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 7039 if (ParamType == ValidKernelParam) 7040 continue; 7041 7042 if (ParamType == RecordKernelParam) { 7043 VisitStack.push_back(FD); 7044 continue; 7045 } 7046 7047 // OpenCL v1.2 s6.9.p: 7048 // Arguments to kernel functions that are declared to be a struct or union 7049 // do not allow OpenCL objects to be passed as elements of the struct or 7050 // union. 7051 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7052 ParamType == PrivatePtrKernelParam) { 7053 S.Diag(Param->getLocation(), 7054 diag::err_record_with_pointers_kernel_param) 7055 << PT->isUnionType() 7056 << PT; 7057 } else { 7058 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7059 } 7060 7061 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7062 << PD->getDeclName(); 7063 7064 // We have an error, now let's go back up through history and show where 7065 // the offending field came from 7066 for (ArrayRef<const FieldDecl *>::const_iterator 7067 I = HistoryStack.begin() + 1, 7068 E = HistoryStack.end(); 7069 I != E; ++I) { 7070 const FieldDecl *OuterField = *I; 7071 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7072 << OuterField->getType(); 7073 } 7074 7075 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7076 << QT->isPointerType() 7077 << QT; 7078 D.setInvalidType(); 7079 return; 7080 } 7081 } while (!VisitStack.empty()); 7082 } 7083 7084 NamedDecl* 7085 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7086 TypeSourceInfo *TInfo, LookupResult &Previous, 7087 MultiTemplateParamsArg TemplateParamLists, 7088 bool &AddToScope) { 7089 QualType R = TInfo->getType(); 7090 7091 assert(R.getTypePtr()->isFunctionType()); 7092 7093 // TODO: consider using NameInfo for diagnostic. 7094 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7095 DeclarationName Name = NameInfo.getName(); 7096 StorageClass SC = getFunctionStorageClass(*this, D); 7097 7098 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7099 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7100 diag::err_invalid_thread) 7101 << DeclSpec::getSpecifierName(TSCS); 7102 7103 if (D.isFirstDeclarationOfMember()) 7104 adjustMemberFunctionCC(R, D.isStaticMember()); 7105 7106 bool isFriend = false; 7107 FunctionTemplateDecl *FunctionTemplate = nullptr; 7108 bool isExplicitSpecialization = false; 7109 bool isFunctionTemplateSpecialization = false; 7110 7111 bool isDependentClassScopeExplicitSpecialization = false; 7112 bool HasExplicitTemplateArgs = false; 7113 TemplateArgumentListInfo TemplateArgs; 7114 7115 bool isVirtualOkay = false; 7116 7117 DeclContext *OriginalDC = DC; 7118 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7119 7120 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7121 isVirtualOkay); 7122 if (!NewFD) return nullptr; 7123 7124 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7125 NewFD->setTopLevelDeclInObjCContainer(); 7126 7127 // Set the lexical context. If this is a function-scope declaration, or has a 7128 // C++ scope specifier, or is the object of a friend declaration, the lexical 7129 // context will be different from the semantic context. 7130 NewFD->setLexicalDeclContext(CurContext); 7131 7132 if (IsLocalExternDecl) 7133 NewFD->setLocalExternDecl(); 7134 7135 if (getLangOpts().CPlusPlus) { 7136 bool isInline = D.getDeclSpec().isInlineSpecified(); 7137 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7138 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7139 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7140 isFriend = D.getDeclSpec().isFriendSpecified(); 7141 if (isFriend && !isInline && D.isFunctionDefinition()) { 7142 // C++ [class.friend]p5 7143 // A function can be defined in a friend declaration of a 7144 // class . . . . Such a function is implicitly inline. 7145 NewFD->setImplicitlyInline(); 7146 } 7147 7148 // If this is a method defined in an __interface, and is not a constructor 7149 // or an overloaded operator, then set the pure flag (isVirtual will already 7150 // return true). 7151 if (const CXXRecordDecl *Parent = 7152 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7153 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7154 NewFD->setPure(true); 7155 } 7156 7157 SetNestedNameSpecifier(NewFD, D); 7158 isExplicitSpecialization = false; 7159 isFunctionTemplateSpecialization = false; 7160 if (D.isInvalidType()) 7161 NewFD->setInvalidDecl(); 7162 7163 // Match up the template parameter lists with the scope specifier, then 7164 // determine whether we have a template or a template specialization. 7165 bool Invalid = false; 7166 if (TemplateParameterList *TemplateParams = 7167 MatchTemplateParametersToScopeSpecifier( 7168 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7169 D.getCXXScopeSpec(), 7170 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7171 ? D.getName().TemplateId 7172 : nullptr, 7173 TemplateParamLists, isFriend, isExplicitSpecialization, 7174 Invalid)) { 7175 if (TemplateParams->size() > 0) { 7176 // This is a function template 7177 7178 // Check that we can declare a template here. 7179 if (CheckTemplateDeclScope(S, TemplateParams)) 7180 NewFD->setInvalidDecl(); 7181 7182 // A destructor cannot be a template. 7183 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7184 Diag(NewFD->getLocation(), diag::err_destructor_template); 7185 NewFD->setInvalidDecl(); 7186 } 7187 7188 // If we're adding a template to a dependent context, we may need to 7189 // rebuilding some of the types used within the template parameter list, 7190 // now that we know what the current instantiation is. 7191 if (DC->isDependentContext()) { 7192 ContextRAII SavedContext(*this, DC); 7193 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7194 Invalid = true; 7195 } 7196 7197 7198 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7199 NewFD->getLocation(), 7200 Name, TemplateParams, 7201 NewFD); 7202 FunctionTemplate->setLexicalDeclContext(CurContext); 7203 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7204 7205 // For source fidelity, store the other template param lists. 7206 if (TemplateParamLists.size() > 1) { 7207 NewFD->setTemplateParameterListsInfo(Context, 7208 TemplateParamLists.size() - 1, 7209 TemplateParamLists.data()); 7210 } 7211 } else { 7212 // This is a function template specialization. 7213 isFunctionTemplateSpecialization = true; 7214 // For source fidelity, store all the template param lists. 7215 if (TemplateParamLists.size() > 0) 7216 NewFD->setTemplateParameterListsInfo(Context, 7217 TemplateParamLists.size(), 7218 TemplateParamLists.data()); 7219 7220 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7221 if (isFriend) { 7222 // We want to remove the "template<>", found here. 7223 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7224 7225 // If we remove the template<> and the name is not a 7226 // template-id, we're actually silently creating a problem: 7227 // the friend declaration will refer to an untemplated decl, 7228 // and clearly the user wants a template specialization. So 7229 // we need to insert '<>' after the name. 7230 SourceLocation InsertLoc; 7231 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7232 InsertLoc = D.getName().getSourceRange().getEnd(); 7233 InsertLoc = getLocForEndOfToken(InsertLoc); 7234 } 7235 7236 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7237 << Name << RemoveRange 7238 << FixItHint::CreateRemoval(RemoveRange) 7239 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7240 } 7241 } 7242 } 7243 else { 7244 // All template param lists were matched against the scope specifier: 7245 // this is NOT (an explicit specialization of) a template. 7246 if (TemplateParamLists.size() > 0) 7247 // For source fidelity, store all the template param lists. 7248 NewFD->setTemplateParameterListsInfo(Context, 7249 TemplateParamLists.size(), 7250 TemplateParamLists.data()); 7251 } 7252 7253 if (Invalid) { 7254 NewFD->setInvalidDecl(); 7255 if (FunctionTemplate) 7256 FunctionTemplate->setInvalidDecl(); 7257 } 7258 7259 // C++ [dcl.fct.spec]p5: 7260 // The virtual specifier shall only be used in declarations of 7261 // nonstatic class member functions that appear within a 7262 // member-specification of a class declaration; see 10.3. 7263 // 7264 if (isVirtual && !NewFD->isInvalidDecl()) { 7265 if (!isVirtualOkay) { 7266 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7267 diag::err_virtual_non_function); 7268 } else if (!CurContext->isRecord()) { 7269 // 'virtual' was specified outside of the class. 7270 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7271 diag::err_virtual_out_of_class) 7272 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7273 } else if (NewFD->getDescribedFunctionTemplate()) { 7274 // C++ [temp.mem]p3: 7275 // A member function template shall not be virtual. 7276 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7277 diag::err_virtual_member_function_template) 7278 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7279 } else { 7280 // Okay: Add virtual to the method. 7281 NewFD->setVirtualAsWritten(true); 7282 } 7283 7284 if (getLangOpts().CPlusPlus14 && 7285 NewFD->getReturnType()->isUndeducedType()) 7286 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7287 } 7288 7289 if (getLangOpts().CPlusPlus14 && 7290 (NewFD->isDependentContext() || 7291 (isFriend && CurContext->isDependentContext())) && 7292 NewFD->getReturnType()->isUndeducedType()) { 7293 // If the function template is referenced directly (for instance, as a 7294 // member of the current instantiation), pretend it has a dependent type. 7295 // This is not really justified by the standard, but is the only sane 7296 // thing to do. 7297 // FIXME: For a friend function, we have not marked the function as being 7298 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7299 const FunctionProtoType *FPT = 7300 NewFD->getType()->castAs<FunctionProtoType>(); 7301 QualType Result = 7302 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7303 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7304 FPT->getExtProtoInfo())); 7305 } 7306 7307 // C++ [dcl.fct.spec]p3: 7308 // The inline specifier shall not appear on a block scope function 7309 // declaration. 7310 if (isInline && !NewFD->isInvalidDecl()) { 7311 if (CurContext->isFunctionOrMethod()) { 7312 // 'inline' is not allowed on block scope function declaration. 7313 Diag(D.getDeclSpec().getInlineSpecLoc(), 7314 diag::err_inline_declaration_block_scope) << Name 7315 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7316 } 7317 } 7318 7319 // C++ [dcl.fct.spec]p6: 7320 // The explicit specifier shall be used only in the declaration of a 7321 // constructor or conversion function within its class definition; 7322 // see 12.3.1 and 12.3.2. 7323 if (isExplicit && !NewFD->isInvalidDecl()) { 7324 if (!CurContext->isRecord()) { 7325 // 'explicit' was specified outside of the class. 7326 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7327 diag::err_explicit_out_of_class) 7328 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7329 } else if (!isa<CXXConstructorDecl>(NewFD) && 7330 !isa<CXXConversionDecl>(NewFD)) { 7331 // 'explicit' was specified on a function that wasn't a constructor 7332 // or conversion function. 7333 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7334 diag::err_explicit_non_ctor_or_conv_function) 7335 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7336 } 7337 } 7338 7339 if (isConstexpr) { 7340 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7341 // are implicitly inline. 7342 NewFD->setImplicitlyInline(); 7343 7344 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7345 // be either constructors or to return a literal type. Therefore, 7346 // destructors cannot be declared constexpr. 7347 if (isa<CXXDestructorDecl>(NewFD)) 7348 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7349 } 7350 7351 // If __module_private__ was specified, mark the function accordingly. 7352 if (D.getDeclSpec().isModulePrivateSpecified()) { 7353 if (isFunctionTemplateSpecialization) { 7354 SourceLocation ModulePrivateLoc 7355 = D.getDeclSpec().getModulePrivateSpecLoc(); 7356 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7357 << 0 7358 << FixItHint::CreateRemoval(ModulePrivateLoc); 7359 } else { 7360 NewFD->setModulePrivate(); 7361 if (FunctionTemplate) 7362 FunctionTemplate->setModulePrivate(); 7363 } 7364 } 7365 7366 if (isFriend) { 7367 if (FunctionTemplate) { 7368 FunctionTemplate->setObjectOfFriendDecl(); 7369 FunctionTemplate->setAccess(AS_public); 7370 } 7371 NewFD->setObjectOfFriendDecl(); 7372 NewFD->setAccess(AS_public); 7373 } 7374 7375 // If a function is defined as defaulted or deleted, mark it as such now. 7376 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7377 // definition kind to FDK_Definition. 7378 switch (D.getFunctionDefinitionKind()) { 7379 case FDK_Declaration: 7380 case FDK_Definition: 7381 break; 7382 7383 case FDK_Defaulted: 7384 NewFD->setDefaulted(); 7385 break; 7386 7387 case FDK_Deleted: 7388 NewFD->setDeletedAsWritten(); 7389 break; 7390 } 7391 7392 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7393 D.isFunctionDefinition()) { 7394 // C++ [class.mfct]p2: 7395 // A member function may be defined (8.4) in its class definition, in 7396 // which case it is an inline member function (7.1.2) 7397 NewFD->setImplicitlyInline(); 7398 } 7399 7400 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7401 !CurContext->isRecord()) { 7402 // C++ [class.static]p1: 7403 // A data or function member of a class may be declared static 7404 // in a class definition, in which case it is a static member of 7405 // the class. 7406 7407 // Complain about the 'static' specifier if it's on an out-of-line 7408 // member function definition. 7409 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7410 diag::err_static_out_of_line) 7411 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7412 } 7413 7414 // C++11 [except.spec]p15: 7415 // A deallocation function with no exception-specification is treated 7416 // as if it were specified with noexcept(true). 7417 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7418 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7419 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7420 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7421 NewFD->setType(Context.getFunctionType( 7422 FPT->getReturnType(), FPT->getParamTypes(), 7423 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7424 } 7425 7426 // Filter out previous declarations that don't match the scope. 7427 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7428 D.getCXXScopeSpec().isNotEmpty() || 7429 isExplicitSpecialization || 7430 isFunctionTemplateSpecialization); 7431 7432 // Handle GNU asm-label extension (encoded as an attribute). 7433 if (Expr *E = (Expr*) D.getAsmLabel()) { 7434 // The parser guarantees this is a string. 7435 StringLiteral *SE = cast<StringLiteral>(E); 7436 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7437 SE->getString(), 0)); 7438 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7439 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7440 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7441 if (I != ExtnameUndeclaredIdentifiers.end()) { 7442 NewFD->addAttr(I->second); 7443 ExtnameUndeclaredIdentifiers.erase(I); 7444 } 7445 } 7446 7447 // Copy the parameter declarations from the declarator D to the function 7448 // declaration NewFD, if they are available. First scavenge them into Params. 7449 SmallVector<ParmVarDecl*, 16> Params; 7450 if (D.isFunctionDeclarator()) { 7451 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7452 7453 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7454 // function that takes no arguments, not a function that takes a 7455 // single void argument. 7456 // We let through "const void" here because Sema::GetTypeForDeclarator 7457 // already checks for that case. 7458 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7459 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7460 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7461 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7462 Param->setDeclContext(NewFD); 7463 Params.push_back(Param); 7464 7465 if (Param->isInvalidDecl()) 7466 NewFD->setInvalidDecl(); 7467 } 7468 } 7469 7470 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7471 // When we're declaring a function with a typedef, typeof, etc as in the 7472 // following example, we'll need to synthesize (unnamed) 7473 // parameters for use in the declaration. 7474 // 7475 // @code 7476 // typedef void fn(int); 7477 // fn f; 7478 // @endcode 7479 7480 // Synthesize a parameter for each argument type. 7481 for (const auto &AI : FT->param_types()) { 7482 ParmVarDecl *Param = 7483 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7484 Param->setScopeInfo(0, Params.size()); 7485 Params.push_back(Param); 7486 } 7487 } else { 7488 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7489 "Should not need args for typedef of non-prototype fn"); 7490 } 7491 7492 // Finally, we know we have the right number of parameters, install them. 7493 NewFD->setParams(Params); 7494 7495 // Find all anonymous symbols defined during the declaration of this function 7496 // and add to NewFD. This lets us track decls such 'enum Y' in: 7497 // 7498 // void f(enum Y {AA} x) {} 7499 // 7500 // which would otherwise incorrectly end up in the translation unit scope. 7501 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7502 DeclsInPrototypeScope.clear(); 7503 7504 if (D.getDeclSpec().isNoreturnSpecified()) 7505 NewFD->addAttr( 7506 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7507 Context, 0)); 7508 7509 // Functions returning a variably modified type violate C99 6.7.5.2p2 7510 // because all functions have linkage. 7511 if (!NewFD->isInvalidDecl() && 7512 NewFD->getReturnType()->isVariablyModifiedType()) { 7513 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7514 NewFD->setInvalidDecl(); 7515 } 7516 7517 // Apply an implicit SectionAttr if #pragma code_seg is active. 7518 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 7519 !NewFD->hasAttr<SectionAttr>()) { 7520 NewFD->addAttr( 7521 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7522 CodeSegStack.CurrentValue->getString(), 7523 CodeSegStack.CurrentPragmaLocation)); 7524 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7525 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 7526 ASTContext::PSF_Read, 7527 NewFD)) 7528 NewFD->dropAttr<SectionAttr>(); 7529 } 7530 7531 // Handle attributes. 7532 ProcessDeclAttributes(S, NewFD, D); 7533 7534 if (getLangOpts().OpenCL) { 7535 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7536 // type declaration will generate a compilation error. 7537 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 7538 if (AddressSpace == LangAS::opencl_local || 7539 AddressSpace == LangAS::opencl_global || 7540 AddressSpace == LangAS::opencl_constant) { 7541 Diag(NewFD->getLocation(), 7542 diag::err_opencl_return_value_with_address_space); 7543 NewFD->setInvalidDecl(); 7544 } 7545 } 7546 7547 if (!getLangOpts().CPlusPlus) { 7548 // Perform semantic checking on the function declaration. 7549 bool isExplicitSpecialization=false; 7550 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7551 CheckMain(NewFD, D.getDeclSpec()); 7552 7553 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7554 CheckMSVCRTEntryPoint(NewFD); 7555 7556 if (!NewFD->isInvalidDecl()) 7557 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7558 isExplicitSpecialization)); 7559 else if (!Previous.empty()) 7560 // Recover gracefully from an invalid redeclaration. 7561 D.setRedeclaration(true); 7562 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7563 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7564 "previous declaration set still overloaded"); 7565 7566 // Diagnose no-prototype function declarations with calling conventions that 7567 // don't support variadic calls. Only do this in C and do it after merging 7568 // possibly prototyped redeclarations. 7569 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 7570 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 7571 CallingConv CC = FT->getExtInfo().getCC(); 7572 if (!supportsVariadicCall(CC)) { 7573 // Windows system headers sometimes accidentally use stdcall without 7574 // (void) parameters, so we relax this to a warning. 7575 int DiagID = 7576 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 7577 Diag(NewFD->getLocation(), DiagID) 7578 << FunctionType::getNameForCallConv(CC); 7579 } 7580 } 7581 } else { 7582 // C++11 [replacement.functions]p3: 7583 // The program's definitions shall not be specified as inline. 7584 // 7585 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7586 // 7587 // Suppress the diagnostic if the function is __attribute__((used)), since 7588 // that forces an external definition to be emitted. 7589 if (D.getDeclSpec().isInlineSpecified() && 7590 NewFD->isReplaceableGlobalAllocationFunction() && 7591 !NewFD->hasAttr<UsedAttr>()) 7592 Diag(D.getDeclSpec().getInlineSpecLoc(), 7593 diag::ext_operator_new_delete_declared_inline) 7594 << NewFD->getDeclName(); 7595 7596 // If the declarator is a template-id, translate the parser's template 7597 // argument list into our AST format. 7598 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7599 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7600 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7601 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7602 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7603 TemplateId->NumArgs); 7604 translateTemplateArguments(TemplateArgsPtr, 7605 TemplateArgs); 7606 7607 HasExplicitTemplateArgs = true; 7608 7609 if (NewFD->isInvalidDecl()) { 7610 HasExplicitTemplateArgs = false; 7611 } else if (FunctionTemplate) { 7612 // Function template with explicit template arguments. 7613 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7614 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7615 7616 HasExplicitTemplateArgs = false; 7617 } else { 7618 assert((isFunctionTemplateSpecialization || 7619 D.getDeclSpec().isFriendSpecified()) && 7620 "should have a 'template<>' for this decl"); 7621 // "friend void foo<>(int);" is an implicit specialization decl. 7622 isFunctionTemplateSpecialization = true; 7623 } 7624 } else if (isFriend && isFunctionTemplateSpecialization) { 7625 // This combination is only possible in a recovery case; the user 7626 // wrote something like: 7627 // template <> friend void foo(int); 7628 // which we're recovering from as if the user had written: 7629 // friend void foo<>(int); 7630 // Go ahead and fake up a template id. 7631 HasExplicitTemplateArgs = true; 7632 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7633 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7634 } 7635 7636 // If it's a friend (and only if it's a friend), it's possible 7637 // that either the specialized function type or the specialized 7638 // template is dependent, and therefore matching will fail. In 7639 // this case, don't check the specialization yet. 7640 bool InstantiationDependent = false; 7641 if (isFunctionTemplateSpecialization && isFriend && 7642 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7643 TemplateSpecializationType::anyDependentTemplateArguments( 7644 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7645 InstantiationDependent))) { 7646 assert(HasExplicitTemplateArgs && 7647 "friend function specialization without template args"); 7648 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7649 Previous)) 7650 NewFD->setInvalidDecl(); 7651 } else if (isFunctionTemplateSpecialization) { 7652 if (CurContext->isDependentContext() && CurContext->isRecord() 7653 && !isFriend) { 7654 isDependentClassScopeExplicitSpecialization = true; 7655 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7656 diag::ext_function_specialization_in_class : 7657 diag::err_function_specialization_in_class) 7658 << NewFD->getDeclName(); 7659 } else if (CheckFunctionTemplateSpecialization(NewFD, 7660 (HasExplicitTemplateArgs ? &TemplateArgs 7661 : nullptr), 7662 Previous)) 7663 NewFD->setInvalidDecl(); 7664 7665 // C++ [dcl.stc]p1: 7666 // A storage-class-specifier shall not be specified in an explicit 7667 // specialization (14.7.3) 7668 FunctionTemplateSpecializationInfo *Info = 7669 NewFD->getTemplateSpecializationInfo(); 7670 if (Info && SC != SC_None) { 7671 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7672 Diag(NewFD->getLocation(), 7673 diag::err_explicit_specialization_inconsistent_storage_class) 7674 << SC 7675 << FixItHint::CreateRemoval( 7676 D.getDeclSpec().getStorageClassSpecLoc()); 7677 7678 else 7679 Diag(NewFD->getLocation(), 7680 diag::ext_explicit_specialization_storage_class) 7681 << FixItHint::CreateRemoval( 7682 D.getDeclSpec().getStorageClassSpecLoc()); 7683 } 7684 7685 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7686 if (CheckMemberSpecialization(NewFD, Previous)) 7687 NewFD->setInvalidDecl(); 7688 } 7689 7690 // Perform semantic checking on the function declaration. 7691 if (!isDependentClassScopeExplicitSpecialization) { 7692 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7693 CheckMain(NewFD, D.getDeclSpec()); 7694 7695 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7696 CheckMSVCRTEntryPoint(NewFD); 7697 7698 if (!NewFD->isInvalidDecl()) 7699 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7700 isExplicitSpecialization)); 7701 else if (!Previous.empty()) 7702 // Recover gracefully from an invalid redeclaration. 7703 D.setRedeclaration(true); 7704 } 7705 7706 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7707 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7708 "previous declaration set still overloaded"); 7709 7710 NamedDecl *PrincipalDecl = (FunctionTemplate 7711 ? cast<NamedDecl>(FunctionTemplate) 7712 : NewFD); 7713 7714 if (isFriend && D.isRedeclaration()) { 7715 AccessSpecifier Access = AS_public; 7716 if (!NewFD->isInvalidDecl()) 7717 Access = NewFD->getPreviousDecl()->getAccess(); 7718 7719 NewFD->setAccess(Access); 7720 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7721 } 7722 7723 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7724 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7725 PrincipalDecl->setNonMemberOperator(); 7726 7727 // If we have a function template, check the template parameter 7728 // list. This will check and merge default template arguments. 7729 if (FunctionTemplate) { 7730 FunctionTemplateDecl *PrevTemplate = 7731 FunctionTemplate->getPreviousDecl(); 7732 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7733 PrevTemplate ? PrevTemplate->getTemplateParameters() 7734 : nullptr, 7735 D.getDeclSpec().isFriendSpecified() 7736 ? (D.isFunctionDefinition() 7737 ? TPC_FriendFunctionTemplateDefinition 7738 : TPC_FriendFunctionTemplate) 7739 : (D.getCXXScopeSpec().isSet() && 7740 DC && DC->isRecord() && 7741 DC->isDependentContext()) 7742 ? TPC_ClassTemplateMember 7743 : TPC_FunctionTemplate); 7744 } 7745 7746 if (NewFD->isInvalidDecl()) { 7747 // Ignore all the rest of this. 7748 } else if (!D.isRedeclaration()) { 7749 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7750 AddToScope }; 7751 // Fake up an access specifier if it's supposed to be a class member. 7752 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7753 NewFD->setAccess(AS_public); 7754 7755 // Qualified decls generally require a previous declaration. 7756 if (D.getCXXScopeSpec().isSet()) { 7757 // ...with the major exception of templated-scope or 7758 // dependent-scope friend declarations. 7759 7760 // TODO: we currently also suppress this check in dependent 7761 // contexts because (1) the parameter depth will be off when 7762 // matching friend templates and (2) we might actually be 7763 // selecting a friend based on a dependent factor. But there 7764 // are situations where these conditions don't apply and we 7765 // can actually do this check immediately. 7766 if (isFriend && 7767 (TemplateParamLists.size() || 7768 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7769 CurContext->isDependentContext())) { 7770 // ignore these 7771 } else { 7772 // The user tried to provide an out-of-line definition for a 7773 // function that is a member of a class or namespace, but there 7774 // was no such member function declared (C++ [class.mfct]p2, 7775 // C++ [namespace.memdef]p2). For example: 7776 // 7777 // class X { 7778 // void f() const; 7779 // }; 7780 // 7781 // void X::f() { } // ill-formed 7782 // 7783 // Complain about this problem, and attempt to suggest close 7784 // matches (e.g., those that differ only in cv-qualifiers and 7785 // whether the parameter types are references). 7786 7787 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7788 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7789 AddToScope = ExtraArgs.AddToScope; 7790 return Result; 7791 } 7792 } 7793 7794 // Unqualified local friend declarations are required to resolve 7795 // to something. 7796 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7797 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7798 *this, Previous, NewFD, ExtraArgs, true, S)) { 7799 AddToScope = ExtraArgs.AddToScope; 7800 return Result; 7801 } 7802 } 7803 7804 } else if (!D.isFunctionDefinition() && 7805 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7806 !isFriend && !isFunctionTemplateSpecialization && 7807 !isExplicitSpecialization) { 7808 // An out-of-line member function declaration must also be a 7809 // definition (C++ [class.mfct]p2). 7810 // Note that this is not the case for explicit specializations of 7811 // function templates or member functions of class templates, per 7812 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7813 // extension for compatibility with old SWIG code which likes to 7814 // generate them. 7815 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7816 << D.getCXXScopeSpec().getRange(); 7817 } 7818 } 7819 7820 ProcessPragmaWeak(S, NewFD); 7821 checkAttributesAfterMerging(*this, *NewFD); 7822 7823 AddKnownFunctionAttributes(NewFD); 7824 7825 if (NewFD->hasAttr<OverloadableAttr>() && 7826 !NewFD->getType()->getAs<FunctionProtoType>()) { 7827 Diag(NewFD->getLocation(), 7828 diag::err_attribute_overloadable_no_prototype) 7829 << NewFD; 7830 7831 // Turn this into a variadic function with no parameters. 7832 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7833 FunctionProtoType::ExtProtoInfo EPI( 7834 Context.getDefaultCallingConvention(true, false)); 7835 EPI.Variadic = true; 7836 EPI.ExtInfo = FT->getExtInfo(); 7837 7838 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7839 NewFD->setType(R); 7840 } 7841 7842 // If there's a #pragma GCC visibility in scope, and this isn't a class 7843 // member, set the visibility of this function. 7844 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7845 AddPushedVisibilityAttribute(NewFD); 7846 7847 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7848 // marking the function. 7849 AddCFAuditedAttribute(NewFD); 7850 7851 // If this is a function definition, check if we have to apply optnone due to 7852 // a pragma. 7853 if(D.isFunctionDefinition()) 7854 AddRangeBasedOptnone(NewFD); 7855 7856 // If this is the first declaration of an extern C variable, update 7857 // the map of such variables. 7858 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7859 isIncompleteDeclExternC(*this, NewFD)) 7860 RegisterLocallyScopedExternCDecl(NewFD, S); 7861 7862 // Set this FunctionDecl's range up to the right paren. 7863 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7864 7865 if (D.isRedeclaration() && !Previous.empty()) { 7866 checkDLLAttributeRedeclaration( 7867 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7868 isExplicitSpecialization || isFunctionTemplateSpecialization); 7869 } 7870 7871 if (getLangOpts().CPlusPlus) { 7872 if (FunctionTemplate) { 7873 if (NewFD->isInvalidDecl()) 7874 FunctionTemplate->setInvalidDecl(); 7875 return FunctionTemplate; 7876 } 7877 } 7878 7879 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7880 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7881 if ((getLangOpts().OpenCLVersion >= 120) 7882 && (SC == SC_Static)) { 7883 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7884 D.setInvalidType(); 7885 } 7886 7887 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7888 if (!NewFD->getReturnType()->isVoidType()) { 7889 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 7890 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 7891 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 7892 : FixItHint()); 7893 D.setInvalidType(); 7894 } 7895 7896 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7897 for (auto Param : NewFD->params()) 7898 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7899 } 7900 7901 MarkUnusedFileScopedDecl(NewFD); 7902 7903 if (getLangOpts().CUDA) 7904 if (IdentifierInfo *II = NewFD->getIdentifier()) 7905 if (!NewFD->isInvalidDecl() && 7906 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7907 if (II->isStr("cudaConfigureCall")) { 7908 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7909 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7910 7911 Context.setcudaConfigureCallDecl(NewFD); 7912 } 7913 } 7914 7915 // Here we have an function template explicit specialization at class scope. 7916 // The actually specialization will be postponed to template instatiation 7917 // time via the ClassScopeFunctionSpecializationDecl node. 7918 if (isDependentClassScopeExplicitSpecialization) { 7919 ClassScopeFunctionSpecializationDecl *NewSpec = 7920 ClassScopeFunctionSpecializationDecl::Create( 7921 Context, CurContext, SourceLocation(), 7922 cast<CXXMethodDecl>(NewFD), 7923 HasExplicitTemplateArgs, TemplateArgs); 7924 CurContext->addDecl(NewSpec); 7925 AddToScope = false; 7926 } 7927 7928 return NewFD; 7929 } 7930 7931 /// \brief Perform semantic checking of a new function declaration. 7932 /// 7933 /// Performs semantic analysis of the new function declaration 7934 /// NewFD. This routine performs all semantic checking that does not 7935 /// require the actual declarator involved in the declaration, and is 7936 /// used both for the declaration of functions as they are parsed 7937 /// (called via ActOnDeclarator) and for the declaration of functions 7938 /// that have been instantiated via C++ template instantiation (called 7939 /// via InstantiateDecl). 7940 /// 7941 /// \param IsExplicitSpecialization whether this new function declaration is 7942 /// an explicit specialization of the previous declaration. 7943 /// 7944 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7945 /// 7946 /// \returns true if the function declaration is a redeclaration. 7947 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7948 LookupResult &Previous, 7949 bool IsExplicitSpecialization) { 7950 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7951 "Variably modified return types are not handled here"); 7952 7953 // Determine whether the type of this function should be merged with 7954 // a previous visible declaration. This never happens for functions in C++, 7955 // and always happens in C if the previous declaration was visible. 7956 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7957 !Previous.isShadowed(); 7958 7959 // Filter out any non-conflicting previous declarations. 7960 filterNonConflictingPreviousDecls(*this, NewFD, Previous); 7961 7962 bool Redeclaration = false; 7963 NamedDecl *OldDecl = nullptr; 7964 7965 // Merge or overload the declaration with an existing declaration of 7966 // the same name, if appropriate. 7967 if (!Previous.empty()) { 7968 // Determine whether NewFD is an overload of PrevDecl or 7969 // a declaration that requires merging. If it's an overload, 7970 // there's no more work to do here; we'll just add the new 7971 // function to the scope. 7972 if (!AllowOverloadingOfFunction(Previous, Context)) { 7973 NamedDecl *Candidate = Previous.getFoundDecl(); 7974 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7975 Redeclaration = true; 7976 OldDecl = Candidate; 7977 } 7978 } else { 7979 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7980 /*NewIsUsingDecl*/ false)) { 7981 case Ovl_Match: 7982 Redeclaration = true; 7983 break; 7984 7985 case Ovl_NonFunction: 7986 Redeclaration = true; 7987 break; 7988 7989 case Ovl_Overload: 7990 Redeclaration = false; 7991 break; 7992 } 7993 7994 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7995 // If a function name is overloadable in C, then every function 7996 // with that name must be marked "overloadable". 7997 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7998 << Redeclaration << NewFD; 7999 NamedDecl *OverloadedDecl = nullptr; 8000 if (Redeclaration) 8001 OverloadedDecl = OldDecl; 8002 else if (!Previous.empty()) 8003 OverloadedDecl = Previous.getRepresentativeDecl(); 8004 if (OverloadedDecl) 8005 Diag(OverloadedDecl->getLocation(), 8006 diag::note_attribute_overloadable_prev_overload); 8007 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8008 } 8009 } 8010 } 8011 8012 // Check for a previous extern "C" declaration with this name. 8013 if (!Redeclaration && 8014 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8015 filterNonConflictingPreviousDecls(*this, NewFD, Previous); 8016 if (!Previous.empty()) { 8017 // This is an extern "C" declaration with the same name as a previous 8018 // declaration, and thus redeclares that entity... 8019 Redeclaration = true; 8020 OldDecl = Previous.getFoundDecl(); 8021 MergeTypeWithPrevious = false; 8022 8023 // ... except in the presence of __attribute__((overloadable)). 8024 if (OldDecl->hasAttr<OverloadableAttr>()) { 8025 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8026 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8027 << Redeclaration << NewFD; 8028 Diag(Previous.getFoundDecl()->getLocation(), 8029 diag::note_attribute_overloadable_prev_overload); 8030 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8031 } 8032 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8033 Redeclaration = false; 8034 OldDecl = nullptr; 8035 } 8036 } 8037 } 8038 } 8039 8040 // C++11 [dcl.constexpr]p8: 8041 // A constexpr specifier for a non-static member function that is not 8042 // a constructor declares that member function to be const. 8043 // 8044 // This needs to be delayed until we know whether this is an out-of-line 8045 // definition of a static member function. 8046 // 8047 // This rule is not present in C++1y, so we produce a backwards 8048 // compatibility warning whenever it happens in C++11. 8049 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8050 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8051 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8052 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8053 CXXMethodDecl *OldMD = nullptr; 8054 if (OldDecl) 8055 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8056 if (!OldMD || !OldMD->isStatic()) { 8057 const FunctionProtoType *FPT = 8058 MD->getType()->castAs<FunctionProtoType>(); 8059 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8060 EPI.TypeQuals |= Qualifiers::Const; 8061 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8062 FPT->getParamTypes(), EPI)); 8063 8064 // Warn that we did this, if we're not performing template instantiation. 8065 // In that case, we'll have warned already when the template was defined. 8066 if (ActiveTemplateInstantiations.empty()) { 8067 SourceLocation AddConstLoc; 8068 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8069 .IgnoreParens().getAs<FunctionTypeLoc>()) 8070 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8071 8072 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8073 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8074 } 8075 } 8076 } 8077 8078 if (Redeclaration) { 8079 // NewFD and OldDecl represent declarations that need to be 8080 // merged. 8081 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8082 NewFD->setInvalidDecl(); 8083 return Redeclaration; 8084 } 8085 8086 Previous.clear(); 8087 Previous.addDecl(OldDecl); 8088 8089 if (FunctionTemplateDecl *OldTemplateDecl 8090 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8091 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8092 FunctionTemplateDecl *NewTemplateDecl 8093 = NewFD->getDescribedFunctionTemplate(); 8094 assert(NewTemplateDecl && "Template/non-template mismatch"); 8095 if (CXXMethodDecl *Method 8096 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8097 Method->setAccess(OldTemplateDecl->getAccess()); 8098 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8099 } 8100 8101 // If this is an explicit specialization of a member that is a function 8102 // template, mark it as a member specialization. 8103 if (IsExplicitSpecialization && 8104 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8105 NewTemplateDecl->setMemberSpecialization(); 8106 assert(OldTemplateDecl->isMemberSpecialization()); 8107 } 8108 8109 } else { 8110 // This needs to happen first so that 'inline' propagates. 8111 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8112 8113 if (isa<CXXMethodDecl>(NewFD)) 8114 NewFD->setAccess(OldDecl->getAccess()); 8115 } 8116 } 8117 8118 // Semantic checking for this function declaration (in isolation). 8119 8120 if (getLangOpts().CPlusPlus) { 8121 // C++-specific checks. 8122 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8123 CheckConstructor(Constructor); 8124 } else if (CXXDestructorDecl *Destructor = 8125 dyn_cast<CXXDestructorDecl>(NewFD)) { 8126 CXXRecordDecl *Record = Destructor->getParent(); 8127 QualType ClassType = Context.getTypeDeclType(Record); 8128 8129 // FIXME: Shouldn't we be able to perform this check even when the class 8130 // type is dependent? Both gcc and edg can handle that. 8131 if (!ClassType->isDependentType()) { 8132 DeclarationName Name 8133 = Context.DeclarationNames.getCXXDestructorName( 8134 Context.getCanonicalType(ClassType)); 8135 if (NewFD->getDeclName() != Name) { 8136 Diag(NewFD->getLocation(), diag::err_destructor_name); 8137 NewFD->setInvalidDecl(); 8138 return Redeclaration; 8139 } 8140 } 8141 } else if (CXXConversionDecl *Conversion 8142 = dyn_cast<CXXConversionDecl>(NewFD)) { 8143 ActOnConversionDeclarator(Conversion); 8144 } 8145 8146 // Find any virtual functions that this function overrides. 8147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8148 if (!Method->isFunctionTemplateSpecialization() && 8149 !Method->getDescribedFunctionTemplate() && 8150 Method->isCanonicalDecl()) { 8151 if (AddOverriddenMethods(Method->getParent(), Method)) { 8152 // If the function was marked as "static", we have a problem. 8153 if (NewFD->getStorageClass() == SC_Static) { 8154 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8155 } 8156 } 8157 } 8158 8159 if (Method->isStatic()) 8160 checkThisInStaticMemberFunctionType(Method); 8161 } 8162 8163 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8164 if (NewFD->isOverloadedOperator() && 8165 CheckOverloadedOperatorDeclaration(NewFD)) { 8166 NewFD->setInvalidDecl(); 8167 return Redeclaration; 8168 } 8169 8170 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8171 if (NewFD->getLiteralIdentifier() && 8172 CheckLiteralOperatorDeclaration(NewFD)) { 8173 NewFD->setInvalidDecl(); 8174 return Redeclaration; 8175 } 8176 8177 // In C++, check default arguments now that we have merged decls. Unless 8178 // the lexical context is the class, because in this case this is done 8179 // during delayed parsing anyway. 8180 if (!CurContext->isRecord()) 8181 CheckCXXDefaultArguments(NewFD); 8182 8183 // If this function declares a builtin function, check the type of this 8184 // declaration against the expected type for the builtin. 8185 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8186 ASTContext::GetBuiltinTypeError Error; 8187 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8188 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8189 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8190 // The type of this function differs from the type of the builtin, 8191 // so forget about the builtin entirely. 8192 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 8193 } 8194 } 8195 8196 // If this function is declared as being extern "C", then check to see if 8197 // the function returns a UDT (class, struct, or union type) that is not C 8198 // compatible, and if it does, warn the user. 8199 // But, issue any diagnostic on the first declaration only. 8200 if (Previous.empty() && NewFD->isExternC()) { 8201 QualType R = NewFD->getReturnType(); 8202 if (R->isIncompleteType() && !R->isVoidType()) 8203 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8204 << NewFD << R; 8205 else if (!R.isPODType(Context) && !R->isVoidType() && 8206 !R->isObjCObjectPointerType()) 8207 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8208 } 8209 } 8210 return Redeclaration; 8211 } 8212 8213 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8214 // C++11 [basic.start.main]p3: 8215 // A program that [...] declares main to be inline, static or 8216 // constexpr is ill-formed. 8217 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8218 // appear in a declaration of main. 8219 // static main is not an error under C99, but we should warn about it. 8220 // We accept _Noreturn main as an extension. 8221 if (FD->getStorageClass() == SC_Static) 8222 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8223 ? diag::err_static_main : diag::warn_static_main) 8224 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8225 if (FD->isInlineSpecified()) 8226 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8227 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8228 if (DS.isNoreturnSpecified()) { 8229 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8230 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8231 Diag(NoreturnLoc, diag::ext_noreturn_main); 8232 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8233 << FixItHint::CreateRemoval(NoreturnRange); 8234 } 8235 if (FD->isConstexpr()) { 8236 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8237 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8238 FD->setConstexpr(false); 8239 } 8240 8241 if (getLangOpts().OpenCL) { 8242 Diag(FD->getLocation(), diag::err_opencl_no_main) 8243 << FD->hasAttr<OpenCLKernelAttr>(); 8244 FD->setInvalidDecl(); 8245 return; 8246 } 8247 8248 QualType T = FD->getType(); 8249 assert(T->isFunctionType() && "function decl is not of function type"); 8250 const FunctionType* FT = T->castAs<FunctionType>(); 8251 8252 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8253 // In C with GNU extensions we allow main() to have non-integer return 8254 // type, but we should warn about the extension, and we disable the 8255 // implicit-return-zero rule. 8256 8257 // GCC in C mode accepts qualified 'int'. 8258 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8259 FD->setHasImplicitReturnZero(true); 8260 else { 8261 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8262 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8263 if (RTRange.isValid()) 8264 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8265 << FixItHint::CreateReplacement(RTRange, "int"); 8266 } 8267 } else { 8268 // In C and C++, main magically returns 0 if you fall off the end; 8269 // set the flag which tells us that. 8270 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8271 8272 // All the standards say that main() should return 'int'. 8273 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8274 FD->setHasImplicitReturnZero(true); 8275 else { 8276 // Otherwise, this is just a flat-out error. 8277 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8278 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8279 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8280 : FixItHint()); 8281 FD->setInvalidDecl(true); 8282 } 8283 } 8284 8285 // Treat protoless main() as nullary. 8286 if (isa<FunctionNoProtoType>(FT)) return; 8287 8288 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8289 unsigned nparams = FTP->getNumParams(); 8290 assert(FD->getNumParams() == nparams); 8291 8292 bool HasExtraParameters = (nparams > 3); 8293 8294 if (FTP->isVariadic()) { 8295 Diag(FD->getLocation(), diag::ext_variadic_main); 8296 // FIXME: if we had information about the location of the ellipsis, we 8297 // could add a FixIt hint to remove it as a parameter. 8298 } 8299 8300 // Darwin passes an undocumented fourth argument of type char**. If 8301 // other platforms start sprouting these, the logic below will start 8302 // getting shifty. 8303 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8304 HasExtraParameters = false; 8305 8306 if (HasExtraParameters) { 8307 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8308 FD->setInvalidDecl(true); 8309 nparams = 3; 8310 } 8311 8312 // FIXME: a lot of the following diagnostics would be improved 8313 // if we had some location information about types. 8314 8315 QualType CharPP = 8316 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8317 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8318 8319 for (unsigned i = 0; i < nparams; ++i) { 8320 QualType AT = FTP->getParamType(i); 8321 8322 bool mismatch = true; 8323 8324 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8325 mismatch = false; 8326 else if (Expected[i] == CharPP) { 8327 // As an extension, the following forms are okay: 8328 // char const ** 8329 // char const * const * 8330 // char * const * 8331 8332 QualifierCollector qs; 8333 const PointerType* PT; 8334 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8335 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8336 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8337 Context.CharTy)) { 8338 qs.removeConst(); 8339 mismatch = !qs.empty(); 8340 } 8341 } 8342 8343 if (mismatch) { 8344 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8345 // TODO: suggest replacing given type with expected type 8346 FD->setInvalidDecl(true); 8347 } 8348 } 8349 8350 if (nparams == 1 && !FD->isInvalidDecl()) { 8351 Diag(FD->getLocation(), diag::warn_main_one_arg); 8352 } 8353 8354 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8355 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8356 FD->setInvalidDecl(); 8357 } 8358 } 8359 8360 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8361 QualType T = FD->getType(); 8362 assert(T->isFunctionType() && "function decl is not of function type"); 8363 const FunctionType *FT = T->castAs<FunctionType>(); 8364 8365 // Set an implicit return of 'zero' if the function can return some integral, 8366 // enumeration, pointer or nullptr type. 8367 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8368 FT->getReturnType()->isAnyPointerType() || 8369 FT->getReturnType()->isNullPtrType()) 8370 // DllMain is exempt because a return value of zero means it failed. 8371 if (FD->getName() != "DllMain") 8372 FD->setHasImplicitReturnZero(true); 8373 8374 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8375 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8376 FD->setInvalidDecl(); 8377 } 8378 } 8379 8380 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8381 // FIXME: Need strict checking. In C89, we need to check for 8382 // any assignment, increment, decrement, function-calls, or 8383 // commas outside of a sizeof. In C99, it's the same list, 8384 // except that the aforementioned are allowed in unevaluated 8385 // expressions. Everything else falls under the 8386 // "may accept other forms of constant expressions" exception. 8387 // (We never end up here for C++, so the constant expression 8388 // rules there don't matter.) 8389 const Expr *Culprit; 8390 if (Init->isConstantInitializer(Context, false, &Culprit)) 8391 return false; 8392 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8393 << Culprit->getSourceRange(); 8394 return true; 8395 } 8396 8397 namespace { 8398 // Visits an initialization expression to see if OrigDecl is evaluated in 8399 // its own initialization and throws a warning if it does. 8400 class SelfReferenceChecker 8401 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8402 Sema &S; 8403 Decl *OrigDecl; 8404 bool isRecordType; 8405 bool isPODType; 8406 bool isReferenceType; 8407 8408 bool isInitList; 8409 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8410 public: 8411 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8412 8413 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8414 S(S), OrigDecl(OrigDecl) { 8415 isPODType = false; 8416 isRecordType = false; 8417 isReferenceType = false; 8418 isInitList = false; 8419 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8420 isPODType = VD->getType().isPODType(S.Context); 8421 isRecordType = VD->getType()->isRecordType(); 8422 isReferenceType = VD->getType()->isReferenceType(); 8423 } 8424 } 8425 8426 // For most expressions, just call the visitor. For initializer lists, 8427 // track the index of the field being initialized since fields are 8428 // initialized in order allowing use of previously initialized fields. 8429 void CheckExpr(Expr *E) { 8430 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8431 if (!InitList) { 8432 Visit(E); 8433 return; 8434 } 8435 8436 // Track and increment the index here. 8437 isInitList = true; 8438 InitFieldIndex.push_back(0); 8439 for (auto Child : InitList->children()) { 8440 CheckExpr(cast<Expr>(Child)); 8441 ++InitFieldIndex.back(); 8442 } 8443 InitFieldIndex.pop_back(); 8444 } 8445 8446 // Returns true if MemberExpr is checked and no futher checking is needed. 8447 // Returns false if additional checking is required. 8448 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8449 llvm::SmallVector<FieldDecl*, 4> Fields; 8450 Expr *Base = E; 8451 bool ReferenceField = false; 8452 8453 // Get the field memebers used. 8454 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8455 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8456 if (!FD) 8457 return false; 8458 Fields.push_back(FD); 8459 if (FD->getType()->isReferenceType()) 8460 ReferenceField = true; 8461 Base = ME->getBase()->IgnoreParenImpCasts(); 8462 } 8463 8464 // Keep checking only if the base Decl is the same. 8465 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8466 if (!DRE || DRE->getDecl() != OrigDecl) 8467 return false; 8468 8469 // A reference field can be bound to an unininitialized field. 8470 if (CheckReference && !ReferenceField) 8471 return true; 8472 8473 // Convert FieldDecls to their index number. 8474 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8475 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) { 8476 UsedFieldIndex.push_back((*I)->getFieldIndex()); 8477 } 8478 8479 // See if a warning is needed by checking the first difference in index 8480 // numbers. If field being used has index less than the field being 8481 // initialized, then the use is safe. 8482 for (auto UsedIter = UsedFieldIndex.begin(), 8483 UsedEnd = UsedFieldIndex.end(), 8484 OrigIter = InitFieldIndex.begin(), 8485 OrigEnd = InitFieldIndex.end(); 8486 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8487 if (*UsedIter < *OrigIter) 8488 return true; 8489 if (*UsedIter > *OrigIter) 8490 break; 8491 } 8492 8493 // TODO: Add a different warning which will print the field names. 8494 HandleDeclRefExpr(DRE); 8495 return true; 8496 } 8497 8498 // For most expressions, the cast is directly above the DeclRefExpr. 8499 // For conditional operators, the cast can be outside the conditional 8500 // operator if both expressions are DeclRefExpr's. 8501 void HandleValue(Expr *E) { 8502 E = E->IgnoreParens(); 8503 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8504 HandleDeclRefExpr(DRE); 8505 return; 8506 } 8507 8508 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8509 Visit(CO->getCond()); 8510 HandleValue(CO->getTrueExpr()); 8511 HandleValue(CO->getFalseExpr()); 8512 return; 8513 } 8514 8515 if (BinaryConditionalOperator *BCO = 8516 dyn_cast<BinaryConditionalOperator>(E)) { 8517 Visit(BCO->getCond()); 8518 HandleValue(BCO->getFalseExpr()); 8519 return; 8520 } 8521 8522 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8523 HandleValue(OVE->getSourceExpr()); 8524 return; 8525 } 8526 8527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8528 if (BO->getOpcode() == BO_Comma) { 8529 Visit(BO->getLHS()); 8530 HandleValue(BO->getRHS()); 8531 return; 8532 } 8533 } 8534 8535 if (isa<MemberExpr>(E)) { 8536 if (isInitList) { 8537 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8538 false /*CheckReference*/)) 8539 return; 8540 } 8541 8542 Expr *Base = E->IgnoreParenImpCasts(); 8543 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8544 // Check for static member variables and don't warn on them. 8545 if (!isa<FieldDecl>(ME->getMemberDecl())) 8546 return; 8547 Base = ME->getBase()->IgnoreParenImpCasts(); 8548 } 8549 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8550 HandleDeclRefExpr(DRE); 8551 return; 8552 } 8553 8554 Visit(E); 8555 } 8556 8557 // Reference types not handled in HandleValue are handled here since all 8558 // uses of references are bad, not just r-value uses. 8559 void VisitDeclRefExpr(DeclRefExpr *E) { 8560 if (isReferenceType) 8561 HandleDeclRefExpr(E); 8562 } 8563 8564 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8565 if (E->getCastKind() == CK_LValueToRValue) { 8566 HandleValue(E->getSubExpr()); 8567 return; 8568 } 8569 8570 Inherited::VisitImplicitCastExpr(E); 8571 } 8572 8573 void VisitMemberExpr(MemberExpr *E) { 8574 if (isInitList) { 8575 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 8576 return; 8577 } 8578 8579 // Don't warn on arrays since they can be treated as pointers. 8580 if (E->getType()->canDecayToPointerType()) return; 8581 8582 // Warn when a non-static method call is followed by non-static member 8583 // field accesses, which is followed by a DeclRefExpr. 8584 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8585 bool Warn = (MD && !MD->isStatic()); 8586 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8587 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8588 if (!isa<FieldDecl>(ME->getMemberDecl())) 8589 Warn = false; 8590 Base = ME->getBase()->IgnoreParenImpCasts(); 8591 } 8592 8593 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8594 if (Warn) 8595 HandleDeclRefExpr(DRE); 8596 return; 8597 } 8598 8599 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8600 // Visit that expression. 8601 Visit(Base); 8602 } 8603 8604 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8605 Expr *Callee = E->getCallee(); 8606 8607 if (isa<UnresolvedLookupExpr>(Callee)) 8608 return Inherited::VisitCXXOperatorCallExpr(E); 8609 8610 Visit(Callee); 8611 for (auto Arg: E->arguments()) 8612 HandleValue(Arg->IgnoreParenImpCasts()); 8613 } 8614 8615 void VisitUnaryOperator(UnaryOperator *E) { 8616 // For POD record types, addresses of its own members are well-defined. 8617 if (E->getOpcode() == UO_AddrOf && isRecordType && 8618 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8619 if (!isPODType) 8620 HandleValue(E->getSubExpr()); 8621 return; 8622 } 8623 8624 if (E->isIncrementDecrementOp()) { 8625 HandleValue(E->getSubExpr()); 8626 return; 8627 } 8628 8629 Inherited::VisitUnaryOperator(E); 8630 } 8631 8632 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8633 8634 void VisitCXXConstructExpr(CXXConstructExpr *E) { 8635 if (E->getConstructor()->isCopyConstructor()) { 8636 Expr *ArgExpr = E->getArg(0); 8637 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 8638 if (ILE->getNumInits() == 1) 8639 ArgExpr = ILE->getInit(0); 8640 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8641 if (ICE->getCastKind() == CK_NoOp) 8642 ArgExpr = ICE->getSubExpr(); 8643 HandleValue(ArgExpr); 8644 return; 8645 } 8646 Inherited::VisitCXXConstructExpr(E); 8647 } 8648 8649 void VisitCallExpr(CallExpr *E) { 8650 // Treat std::move as a use. 8651 if (E->getNumArgs() == 1) { 8652 if (FunctionDecl *FD = E->getDirectCallee()) { 8653 if (FD->isInStdNamespace() && FD->getIdentifier() && 8654 FD->getIdentifier()->isStr("move")) { 8655 HandleValue(E->getArg(0)); 8656 return; 8657 } 8658 } 8659 } 8660 8661 Inherited::VisitCallExpr(E); 8662 } 8663 8664 void VisitBinaryOperator(BinaryOperator *E) { 8665 if (E->isCompoundAssignmentOp()) { 8666 HandleValue(E->getLHS()); 8667 Visit(E->getRHS()); 8668 return; 8669 } 8670 8671 Inherited::VisitBinaryOperator(E); 8672 } 8673 8674 // A custom visitor for BinaryConditionalOperator is needed because the 8675 // regular visitor would check the condition and true expression separately 8676 // but both point to the same place giving duplicate diagnostics. 8677 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 8678 Visit(E->getCond()); 8679 Visit(E->getFalseExpr()); 8680 } 8681 8682 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8683 Decl* ReferenceDecl = DRE->getDecl(); 8684 if (OrigDecl != ReferenceDecl) return; 8685 unsigned diag; 8686 if (isReferenceType) { 8687 diag = diag::warn_uninit_self_reference_in_reference_init; 8688 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8689 diag = diag::warn_static_self_reference_in_init; 8690 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 8691 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 8692 DRE->getDecl()->getType()->isRecordType()) { 8693 diag = diag::warn_uninit_self_reference_in_init; 8694 } else { 8695 // Local variables will be handled by the CFG analysis. 8696 return; 8697 } 8698 8699 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8700 S.PDiag(diag) 8701 << DRE->getNameInfo().getName() 8702 << OrigDecl->getLocation() 8703 << DRE->getSourceRange()); 8704 } 8705 }; 8706 8707 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8708 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8709 bool DirectInit) { 8710 // Parameters arguments are occassionially constructed with itself, 8711 // for instance, in recursive functions. Skip them. 8712 if (isa<ParmVarDecl>(OrigDecl)) 8713 return; 8714 8715 E = E->IgnoreParens(); 8716 8717 // Skip checking T a = a where T is not a record or reference type. 8718 // Doing so is a way to silence uninitialized warnings. 8719 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8720 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8721 if (ICE->getCastKind() == CK_LValueToRValue) 8722 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8723 if (DRE->getDecl() == OrigDecl) 8724 return; 8725 8726 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 8727 } 8728 } 8729 8730 /// AddInitializerToDecl - Adds the initializer Init to the 8731 /// declaration dcl. If DirectInit is true, this is C++ direct 8732 /// initialization rather than copy initialization. 8733 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8734 bool DirectInit, bool TypeMayContainAuto) { 8735 // If there is no declaration, there was an error parsing it. Just ignore 8736 // the initializer. 8737 if (!RealDecl || RealDecl->isInvalidDecl()) { 8738 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 8739 return; 8740 } 8741 8742 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8743 // With declarators parsed the way they are, the parser cannot 8744 // distinguish between a normal initializer and a pure-specifier. 8745 // Thus this grotesque test. 8746 IntegerLiteral *IL; 8747 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8748 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8749 CheckPureMethod(Method, Init->getSourceRange()); 8750 else { 8751 Diag(Method->getLocation(), diag::err_member_function_initialization) 8752 << Method->getDeclName() << Init->getSourceRange(); 8753 Method->setInvalidDecl(); 8754 } 8755 return; 8756 } 8757 8758 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8759 if (!VDecl) { 8760 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8761 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8762 RealDecl->setInvalidDecl(); 8763 return; 8764 } 8765 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8766 8767 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8768 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8769 // Attempt typo correction early so that the type of the init expression can 8770 // be deduced based on the chosen correction:if the original init contains a 8771 // TypoExpr. 8772 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 8773 if (!Res.isUsable()) { 8774 RealDecl->setInvalidDecl(); 8775 return; 8776 } 8777 8778 if (Res.get() != Init) { 8779 Init = Res.get(); 8780 if (CXXDirectInit) 8781 CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8782 } 8783 8784 Expr *DeduceInit = Init; 8785 // Initializer could be a C++ direct-initializer. Deduction only works if it 8786 // contains exactly one expression. 8787 if (CXXDirectInit) { 8788 if (CXXDirectInit->getNumExprs() == 0) { 8789 // It isn't possible to write this directly, but it is possible to 8790 // end up in this situation with "auto x(some_pack...);" 8791 Diag(CXXDirectInit->getLocStart(), 8792 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8793 : diag::err_auto_var_init_no_expression) 8794 << VDecl->getDeclName() << VDecl->getType() 8795 << VDecl->getSourceRange(); 8796 RealDecl->setInvalidDecl(); 8797 return; 8798 } else if (CXXDirectInit->getNumExprs() > 1) { 8799 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8800 VDecl->isInitCapture() 8801 ? diag::err_init_capture_multiple_expressions 8802 : diag::err_auto_var_init_multiple_expressions) 8803 << VDecl->getDeclName() << VDecl->getType() 8804 << VDecl->getSourceRange(); 8805 RealDecl->setInvalidDecl(); 8806 return; 8807 } else { 8808 DeduceInit = CXXDirectInit->getExpr(0); 8809 if (isa<InitListExpr>(DeduceInit)) 8810 Diag(CXXDirectInit->getLocStart(), 8811 diag::err_auto_var_init_paren_braces) 8812 << VDecl->getDeclName() << VDecl->getType() 8813 << VDecl->getSourceRange(); 8814 } 8815 } 8816 8817 // Expressions default to 'id' when we're in a debugger. 8818 bool DefaultedToAuto = false; 8819 if (getLangOpts().DebuggerCastResultToId && 8820 Init->getType() == Context.UnknownAnyTy) { 8821 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8822 if (Result.isInvalid()) { 8823 VDecl->setInvalidDecl(); 8824 return; 8825 } 8826 Init = Result.get(); 8827 DefaultedToAuto = true; 8828 } 8829 8830 QualType DeducedType; 8831 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8832 DAR_Failed) 8833 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8834 if (DeducedType.isNull()) { 8835 RealDecl->setInvalidDecl(); 8836 return; 8837 } 8838 VDecl->setType(DeducedType); 8839 assert(VDecl->isLinkageValid()); 8840 8841 // In ARC, infer lifetime. 8842 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8843 VDecl->setInvalidDecl(); 8844 8845 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8846 // 'id' instead of a specific object type prevents most of our usual checks. 8847 // We only want to warn outside of template instantiations, though: 8848 // inside a template, the 'id' could have come from a parameter. 8849 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8850 DeducedType->isObjCIdType()) { 8851 SourceLocation Loc = 8852 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8853 Diag(Loc, diag::warn_auto_var_is_id) 8854 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8855 } 8856 8857 // If this is a redeclaration, check that the type we just deduced matches 8858 // the previously declared type. 8859 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8860 // We never need to merge the type, because we cannot form an incomplete 8861 // array of auto, nor deduce such a type. 8862 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8863 } 8864 8865 // Check the deduced type is valid for a variable declaration. 8866 CheckVariableDeclarationType(VDecl); 8867 if (VDecl->isInvalidDecl()) 8868 return; 8869 8870 // If all looks well, warn if this is a case that will change meaning when 8871 // we implement N3922. 8872 if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) { 8873 Diag(Init->getLocStart(), 8874 diag::warn_auto_var_direct_list_init) 8875 << FixItHint::CreateInsertion(Init->getLocStart(), "="); 8876 } 8877 } 8878 8879 // dllimport cannot be used on variable definitions. 8880 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8881 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8882 VDecl->setInvalidDecl(); 8883 return; 8884 } 8885 8886 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8887 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8888 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8889 VDecl->setInvalidDecl(); 8890 return; 8891 } 8892 8893 if (!VDecl->getType()->isDependentType()) { 8894 // A definition must end up with a complete type, which means it must be 8895 // complete with the restriction that an array type might be completed by 8896 // the initializer; note that later code assumes this restriction. 8897 QualType BaseDeclType = VDecl->getType(); 8898 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8899 BaseDeclType = Array->getElementType(); 8900 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8901 diag::err_typecheck_decl_incomplete_type)) { 8902 RealDecl->setInvalidDecl(); 8903 return; 8904 } 8905 8906 // The variable can not have an abstract class type. 8907 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8908 diag::err_abstract_type_in_decl, 8909 AbstractVariableType)) 8910 VDecl->setInvalidDecl(); 8911 } 8912 8913 VarDecl *Def; 8914 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8915 NamedDecl *Hidden = nullptr; 8916 if (!hasVisibleDefinition(Def, &Hidden) && 8917 (VDecl->getDescribedVarTemplate() || 8918 VDecl->getNumTemplateParameterLists() || 8919 VDecl->getDeclContext()->isDependentContext())) { 8920 // The previous definition is hidden, and multiple definitions are 8921 // permitted (in separate TUs). Form another definition of it. 8922 } else { 8923 Diag(VDecl->getLocation(), diag::err_redefinition) 8924 << VDecl->getDeclName(); 8925 Diag(Def->getLocation(), diag::note_previous_definition); 8926 VDecl->setInvalidDecl(); 8927 return; 8928 } 8929 } 8930 8931 if (getLangOpts().CPlusPlus) { 8932 // C++ [class.static.data]p4 8933 // If a static data member is of const integral or const 8934 // enumeration type, its declaration in the class definition can 8935 // specify a constant-initializer which shall be an integral 8936 // constant expression (5.19). In that case, the member can appear 8937 // in integral constant expressions. The member shall still be 8938 // defined in a namespace scope if it is used in the program and the 8939 // namespace scope definition shall not contain an initializer. 8940 // 8941 // We already performed a redefinition check above, but for static 8942 // data members we also need to check whether there was an in-class 8943 // declaration with an initializer. 8944 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 8945 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8946 << VDecl->getDeclName(); 8947 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 8948 diag::note_previous_initializer) 8949 << 0; 8950 return; 8951 } 8952 8953 if (VDecl->hasLocalStorage()) 8954 getCurFunction()->setHasBranchProtectedScope(); 8955 8956 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8957 VDecl->setInvalidDecl(); 8958 return; 8959 } 8960 } 8961 8962 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8963 // a kernel function cannot be initialized." 8964 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8965 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8966 VDecl->setInvalidDecl(); 8967 return; 8968 } 8969 8970 // Get the decls type and save a reference for later, since 8971 // CheckInitializerTypes may change it. 8972 QualType DclT = VDecl->getType(), SavT = DclT; 8973 8974 // Expressions default to 'id' when we're in a debugger 8975 // and we are assigning it to a variable of Objective-C pointer type. 8976 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8977 Init->getType() == Context.UnknownAnyTy) { 8978 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8979 if (Result.isInvalid()) { 8980 VDecl->setInvalidDecl(); 8981 return; 8982 } 8983 Init = Result.get(); 8984 } 8985 8986 // Perform the initialization. 8987 if (!VDecl->isInvalidDecl()) { 8988 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8989 InitializationKind Kind 8990 = DirectInit ? 8991 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8992 Init->getLocStart(), 8993 Init->getLocEnd()) 8994 : InitializationKind::CreateDirectList( 8995 VDecl->getLocation()) 8996 : InitializationKind::CreateCopy(VDecl->getLocation(), 8997 Init->getLocStart()); 8998 8999 MultiExprArg Args = Init; 9000 if (CXXDirectInit) 9001 Args = MultiExprArg(CXXDirectInit->getExprs(), 9002 CXXDirectInit->getNumExprs()); 9003 9004 // Try to correct any TypoExprs in the initialization arguments. 9005 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9006 ExprResult Res = CorrectDelayedTyposInExpr( 9007 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9008 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9009 return Init.Failed() ? ExprError() : E; 9010 }); 9011 if (Res.isInvalid()) { 9012 VDecl->setInvalidDecl(); 9013 } else if (Res.get() != Args[Idx]) { 9014 Args[Idx] = Res.get(); 9015 } 9016 } 9017 if (VDecl->isInvalidDecl()) 9018 return; 9019 9020 InitializationSequence InitSeq(*this, Entity, Kind, Args); 9021 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9022 if (Result.isInvalid()) { 9023 VDecl->setInvalidDecl(); 9024 return; 9025 } 9026 9027 Init = Result.getAs<Expr>(); 9028 } 9029 9030 // Check for self-references within variable initializers. 9031 // Variables declared within a function/method body (except for references) 9032 // are handled by a dataflow analysis. 9033 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9034 VDecl->getType()->isReferenceType()) { 9035 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9036 } 9037 9038 // If the type changed, it means we had an incomplete type that was 9039 // completed by the initializer. For example: 9040 // int ary[] = { 1, 3, 5 }; 9041 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9042 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9043 VDecl->setType(DclT); 9044 9045 if (!VDecl->isInvalidDecl()) { 9046 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9047 9048 if (VDecl->hasAttr<BlocksAttr>()) 9049 checkRetainCycles(VDecl, Init); 9050 9051 // It is safe to assign a weak reference into a strong variable. 9052 // Although this code can still have problems: 9053 // id x = self.weakProp; 9054 // id y = self.weakProp; 9055 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9056 // paths through the function. This should be revisited if 9057 // -Wrepeated-use-of-weak is made flow-sensitive. 9058 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9059 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9060 Init->getLocStart())) 9061 getCurFunction()->markSafeWeakUse(Init); 9062 } 9063 9064 // The initialization is usually a full-expression. 9065 // 9066 // FIXME: If this is a braced initialization of an aggregate, it is not 9067 // an expression, and each individual field initializer is a separate 9068 // full-expression. For instance, in: 9069 // 9070 // struct Temp { ~Temp(); }; 9071 // struct S { S(Temp); }; 9072 // struct T { S a, b; } t = { Temp(), Temp() } 9073 // 9074 // we should destroy the first Temp before constructing the second. 9075 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9076 false, 9077 VDecl->isConstexpr()); 9078 if (Result.isInvalid()) { 9079 VDecl->setInvalidDecl(); 9080 return; 9081 } 9082 Init = Result.get(); 9083 9084 // Attach the initializer to the decl. 9085 VDecl->setInit(Init); 9086 9087 if (VDecl->isLocalVarDecl()) { 9088 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9089 // static storage duration shall be constant expressions or string literals. 9090 // C++ does not have this restriction. 9091 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9092 const Expr *Culprit; 9093 if (VDecl->getStorageClass() == SC_Static) 9094 CheckForConstantInitializer(Init, DclT); 9095 // C89 is stricter than C99 for non-static aggregate types. 9096 // C89 6.5.7p3: All the expressions [...] in an initializer list 9097 // for an object that has aggregate or union type shall be 9098 // constant expressions. 9099 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9100 isa<InitListExpr>(Init) && 9101 !Init->isConstantInitializer(Context, false, &Culprit)) 9102 Diag(Culprit->getExprLoc(), 9103 diag::ext_aggregate_init_not_constant) 9104 << Culprit->getSourceRange(); 9105 } 9106 } else if (VDecl->isStaticDataMember() && 9107 VDecl->getLexicalDeclContext()->isRecord()) { 9108 // This is an in-class initialization for a static data member, e.g., 9109 // 9110 // struct S { 9111 // static const int value = 17; 9112 // }; 9113 9114 // C++ [class.mem]p4: 9115 // A member-declarator can contain a constant-initializer only 9116 // if it declares a static member (9.4) of const integral or 9117 // const enumeration type, see 9.4.2. 9118 // 9119 // C++11 [class.static.data]p3: 9120 // If a non-volatile const static data member is of integral or 9121 // enumeration type, its declaration in the class definition can 9122 // specify a brace-or-equal-initializer in which every initalizer-clause 9123 // that is an assignment-expression is a constant expression. A static 9124 // data member of literal type can be declared in the class definition 9125 // with the constexpr specifier; if so, its declaration shall specify a 9126 // brace-or-equal-initializer in which every initializer-clause that is 9127 // an assignment-expression is a constant expression. 9128 9129 // Do nothing on dependent types. 9130 if (DclT->isDependentType()) { 9131 9132 // Allow any 'static constexpr' members, whether or not they are of literal 9133 // type. We separately check that every constexpr variable is of literal 9134 // type. 9135 } else if (VDecl->isConstexpr()) { 9136 9137 // Require constness. 9138 } else if (!DclT.isConstQualified()) { 9139 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9140 << Init->getSourceRange(); 9141 VDecl->setInvalidDecl(); 9142 9143 // We allow integer constant expressions in all cases. 9144 } else if (DclT->isIntegralOrEnumerationType()) { 9145 // Check whether the expression is a constant expression. 9146 SourceLocation Loc; 9147 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9148 // In C++11, a non-constexpr const static data member with an 9149 // in-class initializer cannot be volatile. 9150 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9151 else if (Init->isValueDependent()) 9152 ; // Nothing to check. 9153 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9154 ; // Ok, it's an ICE! 9155 else if (Init->isEvaluatable(Context)) { 9156 // If we can constant fold the initializer through heroics, accept it, 9157 // but report this as a use of an extension for -pedantic. 9158 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9159 << Init->getSourceRange(); 9160 } else { 9161 // Otherwise, this is some crazy unknown case. Report the issue at the 9162 // location provided by the isIntegerConstantExpr failed check. 9163 Diag(Loc, diag::err_in_class_initializer_non_constant) 9164 << Init->getSourceRange(); 9165 VDecl->setInvalidDecl(); 9166 } 9167 9168 // We allow foldable floating-point constants as an extension. 9169 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9170 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9171 // it anyway and provide a fixit to add the 'constexpr'. 9172 if (getLangOpts().CPlusPlus11) { 9173 Diag(VDecl->getLocation(), 9174 diag::ext_in_class_initializer_float_type_cxx11) 9175 << DclT << Init->getSourceRange(); 9176 Diag(VDecl->getLocStart(), 9177 diag::note_in_class_initializer_float_type_cxx11) 9178 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9179 } else { 9180 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9181 << DclT << Init->getSourceRange(); 9182 9183 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9184 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9185 << Init->getSourceRange(); 9186 VDecl->setInvalidDecl(); 9187 } 9188 } 9189 9190 // Suggest adding 'constexpr' in C++11 for literal types. 9191 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9192 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9193 << DclT << Init->getSourceRange() 9194 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9195 VDecl->setConstexpr(true); 9196 9197 } else { 9198 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9199 << DclT << Init->getSourceRange(); 9200 VDecl->setInvalidDecl(); 9201 } 9202 } else if (VDecl->isFileVarDecl()) { 9203 if (VDecl->getStorageClass() == SC_Extern && 9204 (!getLangOpts().CPlusPlus || 9205 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 9206 VDecl->isExternC())) && 9207 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9208 Diag(VDecl->getLocation(), diag::warn_extern_init); 9209 9210 // C99 6.7.8p4. All file scoped initializers need to be constant. 9211 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9212 CheckForConstantInitializer(Init, DclT); 9213 } 9214 9215 // We will represent direct-initialization similarly to copy-initialization: 9216 // int x(1); -as-> int x = 1; 9217 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9218 // 9219 // Clients that want to distinguish between the two forms, can check for 9220 // direct initializer using VarDecl::getInitStyle(). 9221 // A major benefit is that clients that don't particularly care about which 9222 // exactly form was it (like the CodeGen) can handle both cases without 9223 // special case code. 9224 9225 // C++ 8.5p11: 9226 // The form of initialization (using parentheses or '=') is generally 9227 // insignificant, but does matter when the entity being initialized has a 9228 // class type. 9229 if (CXXDirectInit) { 9230 assert(DirectInit && "Call-style initializer must be direct init."); 9231 VDecl->setInitStyle(VarDecl::CallInit); 9232 } else if (DirectInit) { 9233 // This must be list-initialization. No other way is direct-initialization. 9234 VDecl->setInitStyle(VarDecl::ListInit); 9235 } 9236 9237 CheckCompleteVariableDeclaration(VDecl); 9238 } 9239 9240 /// ActOnInitializerError - Given that there was an error parsing an 9241 /// initializer for the given declaration, try to return to some form 9242 /// of sanity. 9243 void Sema::ActOnInitializerError(Decl *D) { 9244 // Our main concern here is re-establishing invariants like "a 9245 // variable's type is either dependent or complete". 9246 if (!D || D->isInvalidDecl()) return; 9247 9248 VarDecl *VD = dyn_cast<VarDecl>(D); 9249 if (!VD) return; 9250 9251 // Auto types are meaningless if we can't make sense of the initializer. 9252 if (ParsingInitForAutoVars.count(D)) { 9253 D->setInvalidDecl(); 9254 return; 9255 } 9256 9257 QualType Ty = VD->getType(); 9258 if (Ty->isDependentType()) return; 9259 9260 // Require a complete type. 9261 if (RequireCompleteType(VD->getLocation(), 9262 Context.getBaseElementType(Ty), 9263 diag::err_typecheck_decl_incomplete_type)) { 9264 VD->setInvalidDecl(); 9265 return; 9266 } 9267 9268 // Require a non-abstract type. 9269 if (RequireNonAbstractType(VD->getLocation(), Ty, 9270 diag::err_abstract_type_in_decl, 9271 AbstractVariableType)) { 9272 VD->setInvalidDecl(); 9273 return; 9274 } 9275 9276 // Don't bother complaining about constructors or destructors, 9277 // though. 9278 } 9279 9280 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9281 bool TypeMayContainAuto) { 9282 // If there is no declaration, there was an error parsing it. Just ignore it. 9283 if (!RealDecl) 9284 return; 9285 9286 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9287 QualType Type = Var->getType(); 9288 9289 // C++11 [dcl.spec.auto]p3 9290 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9291 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9292 << Var->getDeclName() << Type; 9293 Var->setInvalidDecl(); 9294 return; 9295 } 9296 9297 // C++11 [class.static.data]p3: A static data member can be declared with 9298 // the constexpr specifier; if so, its declaration shall specify 9299 // a brace-or-equal-initializer. 9300 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9301 // the definition of a variable [...] or the declaration of a static data 9302 // member. 9303 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9304 if (Var->isStaticDataMember()) 9305 Diag(Var->getLocation(), 9306 diag::err_constexpr_static_mem_var_requires_init) 9307 << Var->getDeclName(); 9308 else 9309 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9310 Var->setInvalidDecl(); 9311 return; 9312 } 9313 9314 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9315 // be initialized. 9316 if (!Var->isInvalidDecl() && 9317 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9318 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9319 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9320 Var->setInvalidDecl(); 9321 return; 9322 } 9323 9324 switch (Var->isThisDeclarationADefinition()) { 9325 case VarDecl::Definition: 9326 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9327 break; 9328 9329 // We have an out-of-line definition of a static data member 9330 // that has an in-class initializer, so we type-check this like 9331 // a declaration. 9332 // 9333 // Fall through 9334 9335 case VarDecl::DeclarationOnly: 9336 // It's only a declaration. 9337 9338 // Block scope. C99 6.7p7: If an identifier for an object is 9339 // declared with no linkage (C99 6.2.2p6), the type for the 9340 // object shall be complete. 9341 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9342 !Var->hasLinkage() && !Var->isInvalidDecl() && 9343 RequireCompleteType(Var->getLocation(), Type, 9344 diag::err_typecheck_decl_incomplete_type)) 9345 Var->setInvalidDecl(); 9346 9347 // Make sure that the type is not abstract. 9348 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9349 RequireNonAbstractType(Var->getLocation(), Type, 9350 diag::err_abstract_type_in_decl, 9351 AbstractVariableType)) 9352 Var->setInvalidDecl(); 9353 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9354 Var->getStorageClass() == SC_PrivateExtern) { 9355 Diag(Var->getLocation(), diag::warn_private_extern); 9356 Diag(Var->getLocation(), diag::note_private_extern); 9357 } 9358 9359 return; 9360 9361 case VarDecl::TentativeDefinition: 9362 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9363 // object that has file scope without an initializer, and without a 9364 // storage-class specifier or with the storage-class specifier "static", 9365 // constitutes a tentative definition. Note: A tentative definition with 9366 // external linkage is valid (C99 6.2.2p5). 9367 if (!Var->isInvalidDecl()) { 9368 if (const IncompleteArrayType *ArrayT 9369 = Context.getAsIncompleteArrayType(Type)) { 9370 if (RequireCompleteType(Var->getLocation(), 9371 ArrayT->getElementType(), 9372 diag::err_illegal_decl_array_incomplete_type)) 9373 Var->setInvalidDecl(); 9374 } else if (Var->getStorageClass() == SC_Static) { 9375 // C99 6.9.2p3: If the declaration of an identifier for an object is 9376 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9377 // declared type shall not be an incomplete type. 9378 // NOTE: code such as the following 9379 // static struct s; 9380 // struct s { int a; }; 9381 // is accepted by gcc. Hence here we issue a warning instead of 9382 // an error and we do not invalidate the static declaration. 9383 // NOTE: to avoid multiple warnings, only check the first declaration. 9384 if (Var->isFirstDecl()) 9385 RequireCompleteType(Var->getLocation(), Type, 9386 diag::ext_typecheck_decl_incomplete_type); 9387 } 9388 } 9389 9390 // Record the tentative definition; we're done. 9391 if (!Var->isInvalidDecl()) 9392 TentativeDefinitions.push_back(Var); 9393 return; 9394 } 9395 9396 // Provide a specific diagnostic for uninitialized variable 9397 // definitions with incomplete array type. 9398 if (Type->isIncompleteArrayType()) { 9399 Diag(Var->getLocation(), 9400 diag::err_typecheck_incomplete_array_needs_initializer); 9401 Var->setInvalidDecl(); 9402 return; 9403 } 9404 9405 // Provide a specific diagnostic for uninitialized variable 9406 // definitions with reference type. 9407 if (Type->isReferenceType()) { 9408 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9409 << Var->getDeclName() 9410 << SourceRange(Var->getLocation(), Var->getLocation()); 9411 Var->setInvalidDecl(); 9412 return; 9413 } 9414 9415 // Do not attempt to type-check the default initializer for a 9416 // variable with dependent type. 9417 if (Type->isDependentType()) 9418 return; 9419 9420 if (Var->isInvalidDecl()) 9421 return; 9422 9423 if (!Var->hasAttr<AliasAttr>()) { 9424 if (RequireCompleteType(Var->getLocation(), 9425 Context.getBaseElementType(Type), 9426 diag::err_typecheck_decl_incomplete_type)) { 9427 Var->setInvalidDecl(); 9428 return; 9429 } 9430 } else { 9431 return; 9432 } 9433 9434 // The variable can not have an abstract class type. 9435 if (RequireNonAbstractType(Var->getLocation(), Type, 9436 diag::err_abstract_type_in_decl, 9437 AbstractVariableType)) { 9438 Var->setInvalidDecl(); 9439 return; 9440 } 9441 9442 // Check for jumps past the implicit initializer. C++0x 9443 // clarifies that this applies to a "variable with automatic 9444 // storage duration", not a "local variable". 9445 // C++11 [stmt.dcl]p3 9446 // A program that jumps from a point where a variable with automatic 9447 // storage duration is not in scope to a point where it is in scope is 9448 // ill-formed unless the variable has scalar type, class type with a 9449 // trivial default constructor and a trivial destructor, a cv-qualified 9450 // version of one of these types, or an array of one of the preceding 9451 // types and is declared without an initializer. 9452 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9453 if (const RecordType *Record 9454 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9455 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9456 // Mark the function for further checking even if the looser rules of 9457 // C++11 do not require such checks, so that we can diagnose 9458 // incompatibilities with C++98. 9459 if (!CXXRecord->isPOD()) 9460 getCurFunction()->setHasBranchProtectedScope(); 9461 } 9462 } 9463 9464 // C++03 [dcl.init]p9: 9465 // If no initializer is specified for an object, and the 9466 // object is of (possibly cv-qualified) non-POD class type (or 9467 // array thereof), the object shall be default-initialized; if 9468 // the object is of const-qualified type, the underlying class 9469 // type shall have a user-declared default 9470 // constructor. Otherwise, if no initializer is specified for 9471 // a non- static object, the object and its subobjects, if 9472 // any, have an indeterminate initial value); if the object 9473 // or any of its subobjects are of const-qualified type, the 9474 // program is ill-formed. 9475 // C++0x [dcl.init]p11: 9476 // If no initializer is specified for an object, the object is 9477 // default-initialized; [...]. 9478 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9479 InitializationKind Kind 9480 = InitializationKind::CreateDefault(Var->getLocation()); 9481 9482 InitializationSequence InitSeq(*this, Entity, Kind, None); 9483 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9484 if (Init.isInvalid()) 9485 Var->setInvalidDecl(); 9486 else if (Init.get()) { 9487 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9488 // This is important for template substitution. 9489 Var->setInitStyle(VarDecl::CallInit); 9490 } 9491 9492 CheckCompleteVariableDeclaration(Var); 9493 } 9494 } 9495 9496 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9497 VarDecl *VD = dyn_cast<VarDecl>(D); 9498 if (!VD) { 9499 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9500 D->setInvalidDecl(); 9501 return; 9502 } 9503 9504 VD->setCXXForRangeDecl(true); 9505 9506 // for-range-declaration cannot be given a storage class specifier. 9507 int Error = -1; 9508 switch (VD->getStorageClass()) { 9509 case SC_None: 9510 break; 9511 case SC_Extern: 9512 Error = 0; 9513 break; 9514 case SC_Static: 9515 Error = 1; 9516 break; 9517 case SC_PrivateExtern: 9518 Error = 2; 9519 break; 9520 case SC_Auto: 9521 Error = 3; 9522 break; 9523 case SC_Register: 9524 Error = 4; 9525 break; 9526 case SC_OpenCLWorkGroupLocal: 9527 llvm_unreachable("Unexpected storage class"); 9528 } 9529 if (Error != -1) { 9530 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9531 << VD->getDeclName() << Error; 9532 D->setInvalidDecl(); 9533 } 9534 } 9535 9536 StmtResult 9537 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9538 IdentifierInfo *Ident, 9539 ParsedAttributes &Attrs, 9540 SourceLocation AttrEnd) { 9541 // C++1y [stmt.iter]p1: 9542 // A range-based for statement of the form 9543 // for ( for-range-identifier : for-range-initializer ) statement 9544 // is equivalent to 9545 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9546 DeclSpec DS(Attrs.getPool().getFactory()); 9547 9548 const char *PrevSpec; 9549 unsigned DiagID; 9550 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 9551 getPrintingPolicy()); 9552 9553 Declarator D(DS, Declarator::ForContext); 9554 D.SetIdentifier(Ident, IdentLoc); 9555 D.takeAttributes(Attrs, AttrEnd); 9556 9557 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 9558 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 9559 EmptyAttrs, IdentLoc); 9560 Decl *Var = ActOnDeclarator(S, D); 9561 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 9562 FinalizeDeclaration(Var); 9563 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 9564 AttrEnd.isValid() ? AttrEnd : IdentLoc); 9565 } 9566 9567 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 9568 if (var->isInvalidDecl()) return; 9569 9570 // In ARC, don't allow jumps past the implicit initialization of a 9571 // local retaining variable. 9572 if (getLangOpts().ObjCAutoRefCount && 9573 var->hasLocalStorage()) { 9574 switch (var->getType().getObjCLifetime()) { 9575 case Qualifiers::OCL_None: 9576 case Qualifiers::OCL_ExplicitNone: 9577 case Qualifiers::OCL_Autoreleasing: 9578 break; 9579 9580 case Qualifiers::OCL_Weak: 9581 case Qualifiers::OCL_Strong: 9582 getCurFunction()->setHasBranchProtectedScope(); 9583 break; 9584 } 9585 } 9586 9587 // Warn about externally-visible variables being defined without a 9588 // prior declaration. We only want to do this for global 9589 // declarations, but we also specifically need to avoid doing it for 9590 // class members because the linkage of an anonymous class can 9591 // change if it's later given a typedef name. 9592 if (var->isThisDeclarationADefinition() && 9593 var->getDeclContext()->getRedeclContext()->isFileContext() && 9594 var->isExternallyVisible() && var->hasLinkage() && 9595 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9596 var->getLocation())) { 9597 // Find a previous declaration that's not a definition. 9598 VarDecl *prev = var->getPreviousDecl(); 9599 while (prev && prev->isThisDeclarationADefinition()) 9600 prev = prev->getPreviousDecl(); 9601 9602 if (!prev) 9603 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9604 } 9605 9606 if (var->getTLSKind() == VarDecl::TLS_Static) { 9607 const Expr *Culprit; 9608 if (var->getType().isDestructedType()) { 9609 // GNU C++98 edits for __thread, [basic.start.term]p3: 9610 // The type of an object with thread storage duration shall not 9611 // have a non-trivial destructor. 9612 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9613 if (getLangOpts().CPlusPlus11) 9614 Diag(var->getLocation(), diag::note_use_thread_local); 9615 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9616 !var->getInit()->isConstantInitializer( 9617 Context, var->getType()->isReferenceType(), &Culprit)) { 9618 // GNU C++98 edits for __thread, [basic.start.init]p4: 9619 // An object of thread storage duration shall not require dynamic 9620 // initialization. 9621 // FIXME: Need strict checking here. 9622 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9623 << Culprit->getSourceRange(); 9624 if (getLangOpts().CPlusPlus11) 9625 Diag(var->getLocation(), diag::note_use_thread_local); 9626 } 9627 9628 } 9629 9630 // Apply section attributes and pragmas to global variables. 9631 bool GlobalStorage = var->hasGlobalStorage(); 9632 if (GlobalStorage && var->isThisDeclarationADefinition() && 9633 ActiveTemplateInstantiations.empty()) { 9634 PragmaStack<StringLiteral *> *Stack = nullptr; 9635 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 9636 if (var->getType().isConstQualified()) 9637 Stack = &ConstSegStack; 9638 else if (!var->getInit()) { 9639 Stack = &BSSSegStack; 9640 SectionFlags |= ASTContext::PSF_Write; 9641 } else { 9642 Stack = &DataSegStack; 9643 SectionFlags |= ASTContext::PSF_Write; 9644 } 9645 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 9646 var->addAttr(SectionAttr::CreateImplicit( 9647 Context, SectionAttr::Declspec_allocate, 9648 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 9649 } 9650 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9651 if (UnifySection(SA->getName(), SectionFlags, var)) 9652 var->dropAttr<SectionAttr>(); 9653 9654 // Apply the init_seg attribute if this has an initializer. If the 9655 // initializer turns out to not be dynamic, we'll end up ignoring this 9656 // attribute. 9657 if (CurInitSeg && var->getInit()) 9658 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 9659 CurInitSegLoc)); 9660 } 9661 9662 // All the following checks are C++ only. 9663 if (!getLangOpts().CPlusPlus) return; 9664 9665 QualType type = var->getType(); 9666 if (type->isDependentType()) return; 9667 9668 // __block variables might require us to capture a copy-initializer. 9669 if (var->hasAttr<BlocksAttr>()) { 9670 // It's currently invalid to ever have a __block variable with an 9671 // array type; should we diagnose that here? 9672 9673 // Regardless, we don't want to ignore array nesting when 9674 // constructing this copy. 9675 if (type->isStructureOrClassType()) { 9676 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9677 SourceLocation poi = var->getLocation(); 9678 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9679 ExprResult result 9680 = PerformMoveOrCopyInitialization( 9681 InitializedEntity::InitializeBlock(poi, type, false), 9682 var, var->getType(), varRef, /*AllowNRVO=*/true); 9683 if (!result.isInvalid()) { 9684 result = MaybeCreateExprWithCleanups(result); 9685 Expr *init = result.getAs<Expr>(); 9686 Context.setBlockVarCopyInits(var, init); 9687 } 9688 } 9689 } 9690 9691 Expr *Init = var->getInit(); 9692 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 9693 QualType baseType = Context.getBaseElementType(type); 9694 9695 if (!var->getDeclContext()->isDependentContext() && 9696 Init && !Init->isValueDependent()) { 9697 if (IsGlobal && !var->isConstexpr() && 9698 !getDiagnostics().isIgnored(diag::warn_global_constructor, 9699 var->getLocation())) { 9700 // Warn about globals which don't have a constant initializer. Don't 9701 // warn about globals with a non-trivial destructor because we already 9702 // warned about them. 9703 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9704 if (!(RD && !RD->hasTrivialDestructor()) && 9705 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9706 Diag(var->getLocation(), diag::warn_global_constructor) 9707 << Init->getSourceRange(); 9708 } 9709 9710 if (var->isConstexpr()) { 9711 SmallVector<PartialDiagnosticAt, 8> Notes; 9712 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9713 SourceLocation DiagLoc = var->getLocation(); 9714 // If the note doesn't add any useful information other than a source 9715 // location, fold it into the primary diagnostic. 9716 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9717 diag::note_invalid_subexpr_in_const_expr) { 9718 DiagLoc = Notes[0].first; 9719 Notes.clear(); 9720 } 9721 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9722 << var << Init->getSourceRange(); 9723 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9724 Diag(Notes[I].first, Notes[I].second); 9725 } 9726 } else if (var->isUsableInConstantExpressions(Context)) { 9727 // Check whether the initializer of a const variable of integral or 9728 // enumeration type is an ICE now, since we can't tell whether it was 9729 // initialized by a constant expression if we check later. 9730 var->checkInitIsICE(); 9731 } 9732 } 9733 9734 // Require the destructor. 9735 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9736 FinalizeVarWithDestructor(var, recordType); 9737 } 9738 9739 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9740 /// any semantic actions necessary after any initializer has been attached. 9741 void 9742 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9743 // Note that we are no longer parsing the initializer for this declaration. 9744 ParsingInitForAutoVars.erase(ThisDecl); 9745 9746 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9747 if (!VD) 9748 return; 9749 9750 checkAttributesAfterMerging(*this, *VD); 9751 9752 // Static locals inherit dll attributes from their function. 9753 if (VD->isStaticLocal()) { 9754 if (FunctionDecl *FD = 9755 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 9756 if (Attr *A = getDLLAttr(FD)) { 9757 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 9758 NewAttr->setInherited(true); 9759 VD->addAttr(NewAttr); 9760 } 9761 } 9762 } 9763 9764 // Grab the dllimport or dllexport attribute off of the VarDecl. 9765 const InheritableAttr *DLLAttr = getDLLAttr(VD); 9766 9767 // Imported static data members cannot be defined out-of-line. 9768 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 9769 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9770 VD->isThisDeclarationADefinition()) { 9771 // We allow definitions of dllimport class template static data members 9772 // with a warning. 9773 CXXRecordDecl *Context = 9774 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9775 bool IsClassTemplateMember = 9776 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9777 Context->getDescribedClassTemplate(); 9778 9779 Diag(VD->getLocation(), 9780 IsClassTemplateMember 9781 ? diag::warn_attribute_dllimport_static_field_definition 9782 : diag::err_attribute_dllimport_static_field_definition); 9783 Diag(IA->getLocation(), diag::note_attribute); 9784 if (!IsClassTemplateMember) 9785 VD->setInvalidDecl(); 9786 } 9787 } 9788 9789 // dllimport/dllexport variables cannot be thread local, their TLS index 9790 // isn't exported with the variable. 9791 if (DLLAttr && VD->getTLSKind()) { 9792 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 9793 << DLLAttr; 9794 VD->setInvalidDecl(); 9795 } 9796 9797 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9798 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9799 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9800 VD->dropAttr<UsedAttr>(); 9801 } 9802 } 9803 9804 const DeclContext *DC = VD->getDeclContext(); 9805 // If there's a #pragma GCC visibility in scope, and this isn't a class 9806 // member, set the visibility of this variable. 9807 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9808 AddPushedVisibilityAttribute(VD); 9809 9810 // FIXME: Warn on unused templates. 9811 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9812 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9813 MarkUnusedFileScopedDecl(VD); 9814 9815 // Now we have parsed the initializer and can update the table of magic 9816 // tag values. 9817 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9818 !VD->getType()->isIntegralOrEnumerationType()) 9819 return; 9820 9821 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9822 const Expr *MagicValueExpr = VD->getInit(); 9823 if (!MagicValueExpr) { 9824 continue; 9825 } 9826 llvm::APSInt MagicValueInt; 9827 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9828 Diag(I->getRange().getBegin(), 9829 diag::err_type_tag_for_datatype_not_ice) 9830 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9831 continue; 9832 } 9833 if (MagicValueInt.getActiveBits() > 64) { 9834 Diag(I->getRange().getBegin(), 9835 diag::err_type_tag_for_datatype_too_large) 9836 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9837 continue; 9838 } 9839 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9840 RegisterTypeTagForDatatype(I->getArgumentKind(), 9841 MagicValue, 9842 I->getMatchingCType(), 9843 I->getLayoutCompatible(), 9844 I->getMustBeNull()); 9845 } 9846 } 9847 9848 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9849 ArrayRef<Decl *> Group) { 9850 SmallVector<Decl*, 8> Decls; 9851 9852 if (DS.isTypeSpecOwned()) 9853 Decls.push_back(DS.getRepAsDecl()); 9854 9855 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9856 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9857 if (Decl *D = Group[i]) { 9858 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9859 if (!FirstDeclaratorInGroup) 9860 FirstDeclaratorInGroup = DD; 9861 Decls.push_back(D); 9862 } 9863 9864 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9865 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9866 handleTagNumbering(Tag, S); 9867 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9868 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9869 } 9870 } 9871 9872 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9873 } 9874 9875 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9876 /// group, performing any necessary semantic checking. 9877 Sema::DeclGroupPtrTy 9878 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 9879 bool TypeMayContainAuto) { 9880 // C++0x [dcl.spec.auto]p7: 9881 // If the type deduced for the template parameter U is not the same in each 9882 // deduction, the program is ill-formed. 9883 // FIXME: When initializer-list support is added, a distinction is needed 9884 // between the deduced type U and the deduced type which 'auto' stands for. 9885 // auto a = 0, b = { 1, 2, 3 }; 9886 // is legal because the deduced type U is 'int' in both cases. 9887 if (TypeMayContainAuto && Group.size() > 1) { 9888 QualType Deduced; 9889 CanQualType DeducedCanon; 9890 VarDecl *DeducedDecl = nullptr; 9891 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9892 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9893 AutoType *AT = D->getType()->getContainedAutoType(); 9894 // Don't reissue diagnostics when instantiating a template. 9895 if (AT && D->isInvalidDecl()) 9896 break; 9897 QualType U = AT ? AT->getDeducedType() : QualType(); 9898 if (!U.isNull()) { 9899 CanQualType UCanon = Context.getCanonicalType(U); 9900 if (Deduced.isNull()) { 9901 Deduced = U; 9902 DeducedCanon = UCanon; 9903 DeducedDecl = D; 9904 } else if (DeducedCanon != UCanon) { 9905 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9906 diag::err_auto_different_deductions) 9907 << (AT->isDecltypeAuto() ? 1 : 0) 9908 << Deduced << DeducedDecl->getDeclName() 9909 << U << D->getDeclName() 9910 << DeducedDecl->getInit()->getSourceRange() 9911 << D->getInit()->getSourceRange(); 9912 D->setInvalidDecl(); 9913 break; 9914 } 9915 } 9916 } 9917 } 9918 } 9919 9920 ActOnDocumentableDecls(Group); 9921 9922 return DeclGroupPtrTy::make( 9923 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9924 } 9925 9926 void Sema::ActOnDocumentableDecl(Decl *D) { 9927 ActOnDocumentableDecls(D); 9928 } 9929 9930 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9931 // Don't parse the comment if Doxygen diagnostics are ignored. 9932 if (Group.empty() || !Group[0]) 9933 return; 9934 9935 if (Diags.isIgnored(diag::warn_doc_param_not_found, 9936 Group[0]->getLocation()) && 9937 Diags.isIgnored(diag::warn_unknown_comment_command_name, 9938 Group[0]->getLocation())) 9939 return; 9940 9941 if (Group.size() >= 2) { 9942 // This is a decl group. Normally it will contain only declarations 9943 // produced from declarator list. But in case we have any definitions or 9944 // additional declaration references: 9945 // 'typedef struct S {} S;' 9946 // 'typedef struct S *S;' 9947 // 'struct S *pS;' 9948 // FinalizeDeclaratorGroup adds these as separate declarations. 9949 Decl *MaybeTagDecl = Group[0]; 9950 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9951 Group = Group.slice(1); 9952 } 9953 } 9954 9955 // See if there are any new comments that are not attached to a decl. 9956 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9957 if (!Comments.empty() && 9958 !Comments.back()->isAttached()) { 9959 // There is at least one comment that not attached to a decl. 9960 // Maybe it should be attached to one of these decls? 9961 // 9962 // Note that this way we pick up not only comments that precede the 9963 // declaration, but also comments that *follow* the declaration -- thanks to 9964 // the lookahead in the lexer: we've consumed the semicolon and looked 9965 // ahead through comments. 9966 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9967 Context.getCommentForDecl(Group[i], &PP); 9968 } 9969 } 9970 9971 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9972 /// to introduce parameters into function prototype scope. 9973 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9974 const DeclSpec &DS = D.getDeclSpec(); 9975 9976 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9977 9978 // C++03 [dcl.stc]p2 also permits 'auto'. 9979 StorageClass SC = SC_None; 9980 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9981 SC = SC_Register; 9982 } else if (getLangOpts().CPlusPlus && 9983 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9984 SC = SC_Auto; 9985 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9986 Diag(DS.getStorageClassSpecLoc(), 9987 diag::err_invalid_storage_class_in_func_decl); 9988 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9989 } 9990 9991 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9992 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9993 << DeclSpec::getSpecifierName(TSCS); 9994 if (DS.isConstexprSpecified()) 9995 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9996 << 0; 9997 9998 DiagnoseFunctionSpecifiers(DS); 9999 10000 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10001 QualType parmDeclType = TInfo->getType(); 10002 10003 if (getLangOpts().CPlusPlus) { 10004 // Check that there are no default arguments inside the type of this 10005 // parameter. 10006 CheckExtraCXXDefaultArguments(D); 10007 10008 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 10009 if (D.getCXXScopeSpec().isSet()) { 10010 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 10011 << D.getCXXScopeSpec().getRange(); 10012 D.getCXXScopeSpec().clear(); 10013 } 10014 } 10015 10016 // Ensure we have a valid name 10017 IdentifierInfo *II = nullptr; 10018 if (D.hasName()) { 10019 II = D.getIdentifier(); 10020 if (!II) { 10021 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 10022 << GetNameForDeclarator(D).getName(); 10023 D.setInvalidType(true); 10024 } 10025 } 10026 10027 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 10028 if (II) { 10029 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 10030 ForRedeclaration); 10031 LookupName(R, S); 10032 if (R.isSingleResult()) { 10033 NamedDecl *PrevDecl = R.getFoundDecl(); 10034 if (PrevDecl->isTemplateParameter()) { 10035 // Maybe we will complain about the shadowed template parameter. 10036 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10037 // Just pretend that we didn't see the previous declaration. 10038 PrevDecl = nullptr; 10039 } else if (S->isDeclScope(PrevDecl)) { 10040 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 10041 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10042 10043 // Recover by removing the name 10044 II = nullptr; 10045 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 10046 D.setInvalidType(true); 10047 } 10048 } 10049 } 10050 10051 // Temporarily put parameter variables in the translation unit, not 10052 // the enclosing context. This prevents them from accidentally 10053 // looking like class members in C++. 10054 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 10055 D.getLocStart(), 10056 D.getIdentifierLoc(), II, 10057 parmDeclType, TInfo, 10058 SC); 10059 10060 if (D.isInvalidType()) 10061 New->setInvalidDecl(); 10062 10063 assert(S->isFunctionPrototypeScope()); 10064 assert(S->getFunctionPrototypeDepth() >= 1); 10065 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 10066 S->getNextFunctionPrototypeIndex()); 10067 10068 // Add the parameter declaration into this scope. 10069 S->AddDecl(New); 10070 if (II) 10071 IdResolver.AddDecl(New); 10072 10073 ProcessDeclAttributes(S, New, D); 10074 10075 if (D.getDeclSpec().isModulePrivateSpecified()) 10076 Diag(New->getLocation(), diag::err_module_private_local) 10077 << 1 << New->getDeclName() 10078 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10079 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10080 10081 if (New->hasAttr<BlocksAttr>()) { 10082 Diag(New->getLocation(), diag::err_block_on_nonlocal); 10083 } 10084 return New; 10085 } 10086 10087 /// \brief Synthesizes a variable for a parameter arising from a 10088 /// typedef. 10089 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 10090 SourceLocation Loc, 10091 QualType T) { 10092 /* FIXME: setting StartLoc == Loc. 10093 Would it be worth to modify callers so as to provide proper source 10094 location for the unnamed parameters, embedding the parameter's type? */ 10095 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 10096 T, Context.getTrivialTypeSourceInfo(T, Loc), 10097 SC_None, nullptr); 10098 Param->setImplicit(); 10099 return Param; 10100 } 10101 10102 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 10103 ParmVarDecl * const *ParamEnd) { 10104 // Don't diagnose unused-parameter errors in template instantiations; we 10105 // will already have done so in the template itself. 10106 if (!ActiveTemplateInstantiations.empty()) 10107 return; 10108 10109 for (; Param != ParamEnd; ++Param) { 10110 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 10111 !(*Param)->hasAttr<UnusedAttr>()) { 10112 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 10113 << (*Param)->getDeclName(); 10114 } 10115 } 10116 } 10117 10118 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 10119 ParmVarDecl * const *ParamEnd, 10120 QualType ReturnTy, 10121 NamedDecl *D) { 10122 if (LangOpts.NumLargeByValueCopy == 0) // No check. 10123 return; 10124 10125 // Warn if the return value is pass-by-value and larger than the specified 10126 // threshold. 10127 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 10128 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 10129 if (Size > LangOpts.NumLargeByValueCopy) 10130 Diag(D->getLocation(), diag::warn_return_value_size) 10131 << D->getDeclName() << Size; 10132 } 10133 10134 // Warn if any parameter is pass-by-value and larger than the specified 10135 // threshold. 10136 for (; Param != ParamEnd; ++Param) { 10137 QualType T = (*Param)->getType(); 10138 if (T->isDependentType() || !T.isPODType(Context)) 10139 continue; 10140 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 10141 if (Size > LangOpts.NumLargeByValueCopy) 10142 Diag((*Param)->getLocation(), diag::warn_parameter_size) 10143 << (*Param)->getDeclName() << Size; 10144 } 10145 } 10146 10147 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 10148 SourceLocation NameLoc, IdentifierInfo *Name, 10149 QualType T, TypeSourceInfo *TSInfo, 10150 StorageClass SC) { 10151 // In ARC, infer a lifetime qualifier for appropriate parameter types. 10152 if (getLangOpts().ObjCAutoRefCount && 10153 T.getObjCLifetime() == Qualifiers::OCL_None && 10154 T->isObjCLifetimeType()) { 10155 10156 Qualifiers::ObjCLifetime lifetime; 10157 10158 // Special cases for arrays: 10159 // - if it's const, use __unsafe_unretained 10160 // - otherwise, it's an error 10161 if (T->isArrayType()) { 10162 if (!T.isConstQualified()) { 10163 DelayedDiagnostics.add( 10164 sema::DelayedDiagnostic::makeForbiddenType( 10165 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 10166 } 10167 lifetime = Qualifiers::OCL_ExplicitNone; 10168 } else { 10169 lifetime = T->getObjCARCImplicitLifetime(); 10170 } 10171 T = Context.getLifetimeQualifiedType(T, lifetime); 10172 } 10173 10174 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 10175 Context.getAdjustedParameterType(T), 10176 TSInfo, SC, nullptr); 10177 10178 // Parameters can not be abstract class types. 10179 // For record types, this is done by the AbstractClassUsageDiagnoser once 10180 // the class has been completely parsed. 10181 if (!CurContext->isRecord() && 10182 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 10183 AbstractParamType)) 10184 New->setInvalidDecl(); 10185 10186 // Parameter declarators cannot be interface types. All ObjC objects are 10187 // passed by reference. 10188 if (T->isObjCObjectType()) { 10189 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 10190 Diag(NameLoc, 10191 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 10192 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 10193 T = Context.getObjCObjectPointerType(T); 10194 New->setType(T); 10195 } 10196 10197 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 10198 // duration shall not be qualified by an address-space qualifier." 10199 // Since all parameters have automatic store duration, they can not have 10200 // an address space. 10201 if (T.getAddressSpace() != 0) { 10202 // OpenCL allows function arguments declared to be an array of a type 10203 // to be qualified with an address space. 10204 if (!(getLangOpts().OpenCL && T->isArrayType())) { 10205 Diag(NameLoc, diag::err_arg_with_address_space); 10206 New->setInvalidDecl(); 10207 } 10208 } 10209 10210 return New; 10211 } 10212 10213 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 10214 SourceLocation LocAfterDecls) { 10215 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10216 10217 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 10218 // for a K&R function. 10219 if (!FTI.hasPrototype) { 10220 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10221 --i; 10222 if (FTI.Params[i].Param == nullptr) { 10223 SmallString<256> Code; 10224 llvm::raw_svector_ostream(Code) 10225 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10226 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10227 << FTI.Params[i].Ident 10228 << FixItHint::CreateInsertion(LocAfterDecls, Code); 10229 10230 // Implicitly declare the argument as type 'int' for lack of a better 10231 // type. 10232 AttributeFactory attrs; 10233 DeclSpec DS(attrs); 10234 const char* PrevSpec; // unused 10235 unsigned DiagID; // unused 10236 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10237 DiagID, Context.getPrintingPolicy()); 10238 // Use the identifier location for the type source range. 10239 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10240 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10241 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10242 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10243 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10244 } 10245 } 10246 } 10247 } 10248 10249 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 10250 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10251 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10252 Scope *ParentScope = FnBodyScope->getParent(); 10253 10254 D.setFunctionDefinitionKind(FDK_Definition); 10255 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 10256 return ActOnStartOfFunctionDef(FnBodyScope, DP); 10257 } 10258 10259 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10260 Consumer.HandleInlineMethodDefinition(D); 10261 } 10262 10263 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10264 const FunctionDecl*& PossibleZeroParamPrototype) { 10265 // Don't warn about invalid declarations. 10266 if (FD->isInvalidDecl()) 10267 return false; 10268 10269 // Or declarations that aren't global. 10270 if (!FD->isGlobal()) 10271 return false; 10272 10273 // Don't warn about C++ member functions. 10274 if (isa<CXXMethodDecl>(FD)) 10275 return false; 10276 10277 // Don't warn about 'main'. 10278 if (FD->isMain()) 10279 return false; 10280 10281 // Don't warn about inline functions. 10282 if (FD->isInlined()) 10283 return false; 10284 10285 // Don't warn about function templates. 10286 if (FD->getDescribedFunctionTemplate()) 10287 return false; 10288 10289 // Don't warn about function template specializations. 10290 if (FD->isFunctionTemplateSpecialization()) 10291 return false; 10292 10293 // Don't warn for OpenCL kernels. 10294 if (FD->hasAttr<OpenCLKernelAttr>()) 10295 return false; 10296 10297 // Don't warn on explicitly deleted functions. 10298 if (FD->isDeleted()) 10299 return false; 10300 10301 bool MissingPrototype = true; 10302 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10303 Prev; Prev = Prev->getPreviousDecl()) { 10304 // Ignore any declarations that occur in function or method 10305 // scope, because they aren't visible from the header. 10306 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10307 continue; 10308 10309 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10310 if (FD->getNumParams() == 0) 10311 PossibleZeroParamPrototype = Prev; 10312 break; 10313 } 10314 10315 return MissingPrototype; 10316 } 10317 10318 void 10319 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10320 const FunctionDecl *EffectiveDefinition) { 10321 // Don't complain if we're in GNU89 mode and the previous definition 10322 // was an extern inline function. 10323 const FunctionDecl *Definition = EffectiveDefinition; 10324 if (!Definition) 10325 if (!FD->isDefined(Definition)) 10326 return; 10327 10328 if (canRedefineFunction(Definition, getLangOpts())) 10329 return; 10330 10331 // If we don't have a visible definition of the function, and it's inline or 10332 // a template, it's OK to form another definition of it. 10333 // 10334 // FIXME: Should we skip the body of the function and use the old definition 10335 // in this case? That may be necessary for functions that return local types 10336 // through a deduced return type, or instantiate templates with local types. 10337 if (!hasVisibleDefinition(Definition) && 10338 (Definition->isInlineSpecified() || 10339 Definition->getDescribedFunctionTemplate() || 10340 Definition->getNumTemplateParameterLists())) 10341 return; 10342 10343 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10344 Definition->getStorageClass() == SC_Extern) 10345 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10346 << FD->getDeclName() << getLangOpts().CPlusPlus; 10347 else 10348 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10349 10350 Diag(Definition->getLocation(), diag::note_previous_definition); 10351 FD->setInvalidDecl(); 10352 } 10353 10354 10355 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10356 Sema &S) { 10357 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10358 10359 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10360 LSI->CallOperator = CallOperator; 10361 LSI->Lambda = LambdaClass; 10362 LSI->ReturnType = CallOperator->getReturnType(); 10363 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10364 10365 if (LCD == LCD_None) 10366 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10367 else if (LCD == LCD_ByCopy) 10368 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10369 else if (LCD == LCD_ByRef) 10370 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10371 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10372 10373 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10374 LSI->Mutable = !CallOperator->isConst(); 10375 10376 // Add the captures to the LSI so they can be noted as already 10377 // captured within tryCaptureVar. 10378 auto I = LambdaClass->field_begin(); 10379 for (const auto &C : LambdaClass->captures()) { 10380 if (C.capturesVariable()) { 10381 VarDecl *VD = C.getCapturedVar(); 10382 if (VD->isInitCapture()) 10383 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10384 QualType CaptureType = VD->getType(); 10385 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10386 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10387 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 10388 /*EllipsisLoc*/C.isPackExpansion() 10389 ? C.getEllipsisLoc() : SourceLocation(), 10390 CaptureType, /*Expr*/ nullptr); 10391 10392 } else if (C.capturesThis()) { 10393 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10394 S.getCurrentThisType(), /*Expr*/ nullptr); 10395 } else { 10396 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10397 } 10398 ++I; 10399 } 10400 } 10401 10402 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 10403 // Clear the last template instantiation error context. 10404 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10405 10406 if (!D) 10407 return D; 10408 FunctionDecl *FD = nullptr; 10409 10410 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10411 FD = FunTmpl->getTemplatedDecl(); 10412 else 10413 FD = cast<FunctionDecl>(D); 10414 // If we are instantiating a generic lambda call operator, push 10415 // a LambdaScopeInfo onto the function stack. But use the information 10416 // that's already been calculated (ActOnLambdaExpr) to prime the current 10417 // LambdaScopeInfo. 10418 // When the template operator is being specialized, the LambdaScopeInfo, 10419 // has to be properly restored so that tryCaptureVariable doesn't try 10420 // and capture any new variables. In addition when calculating potential 10421 // captures during transformation of nested lambdas, it is necessary to 10422 // have the LSI properly restored. 10423 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10424 assert(ActiveTemplateInstantiations.size() && 10425 "There should be an active template instantiation on the stack " 10426 "when instantiating a generic lambda!"); 10427 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10428 } 10429 else 10430 // Enter a new function scope 10431 PushFunctionScope(); 10432 10433 // See if this is a redefinition. 10434 if (!FD->isLateTemplateParsed()) 10435 CheckForFunctionRedefinition(FD); 10436 10437 // Builtin functions cannot be defined. 10438 if (unsigned BuiltinID = FD->getBuiltinID()) { 10439 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10440 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10441 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10442 FD->setInvalidDecl(); 10443 } 10444 } 10445 10446 // The return type of a function definition must be complete 10447 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10448 QualType ResultType = FD->getReturnType(); 10449 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10450 !FD->isInvalidDecl() && 10451 RequireCompleteType(FD->getLocation(), ResultType, 10452 diag::err_func_def_incomplete_result)) 10453 FD->setInvalidDecl(); 10454 10455 if (FnBodyScope) 10456 PushDeclContext(FnBodyScope, FD); 10457 10458 // Check the validity of our function parameters 10459 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10460 /*CheckParameterNames=*/true); 10461 10462 // Introduce our parameters into the function scope 10463 for (auto Param : FD->params()) { 10464 Param->setOwningFunction(FD); 10465 10466 // If this has an identifier, add it to the scope stack. 10467 if (Param->getIdentifier() && FnBodyScope) { 10468 CheckShadow(FnBodyScope, Param); 10469 10470 PushOnScopeChains(Param, FnBodyScope); 10471 } 10472 } 10473 10474 // If we had any tags defined in the function prototype, 10475 // introduce them into the function scope. 10476 if (FnBodyScope) { 10477 for (ArrayRef<NamedDecl *>::iterator 10478 I = FD->getDeclsInPrototypeScope().begin(), 10479 E = FD->getDeclsInPrototypeScope().end(); 10480 I != E; ++I) { 10481 NamedDecl *D = *I; 10482 10483 // Some of these decls (like enums) may have been pinned to the 10484 // translation unit for lack of a real context earlier. If so, remove 10485 // from the translation unit and reattach to the current context. 10486 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 10487 // Is the decl actually in the context? 10488 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 10489 if (DI == D) { 10490 Context.getTranslationUnitDecl()->removeDecl(D); 10491 break; 10492 } 10493 } 10494 // Either way, reassign the lexical decl context to our FunctionDecl. 10495 D->setLexicalDeclContext(CurContext); 10496 } 10497 10498 // If the decl has a non-null name, make accessible in the current scope. 10499 if (!D->getName().empty()) 10500 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 10501 10502 // Similarly, dive into enums and fish their constants out, making them 10503 // accessible in this scope. 10504 if (auto *ED = dyn_cast<EnumDecl>(D)) { 10505 for (auto *EI : ED->enumerators()) 10506 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 10507 } 10508 } 10509 } 10510 10511 // Ensure that the function's exception specification is instantiated. 10512 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 10513 ResolveExceptionSpec(D->getLocation(), FPT); 10514 10515 // dllimport cannot be applied to non-inline function definitions. 10516 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 10517 !FD->isTemplateInstantiation()) { 10518 assert(!FD->hasAttr<DLLExportAttr>()); 10519 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 10520 FD->setInvalidDecl(); 10521 return D; 10522 } 10523 // We want to attach documentation to original Decl (which might be 10524 // a function template). 10525 ActOnDocumentableDecl(D); 10526 if (getCurLexicalContext()->isObjCContainer() && 10527 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 10528 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 10529 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 10530 10531 return D; 10532 } 10533 10534 /// \brief Given the set of return statements within a function body, 10535 /// compute the variables that are subject to the named return value 10536 /// optimization. 10537 /// 10538 /// Each of the variables that is subject to the named return value 10539 /// optimization will be marked as NRVO variables in the AST, and any 10540 /// return statement that has a marked NRVO variable as its NRVO candidate can 10541 /// use the named return value optimization. 10542 /// 10543 /// This function applies a very simplistic algorithm for NRVO: if every return 10544 /// statement in the scope of a variable has the same NRVO candidate, that 10545 /// candidate is an NRVO variable. 10546 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 10547 ReturnStmt **Returns = Scope->Returns.data(); 10548 10549 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 10550 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 10551 if (!NRVOCandidate->isNRVOVariable()) 10552 Returns[I]->setNRVOCandidate(nullptr); 10553 } 10554 } 10555 } 10556 10557 bool Sema::canDelayFunctionBody(const Declarator &D) { 10558 // We can't delay parsing the body of a constexpr function template (yet). 10559 if (D.getDeclSpec().isConstexprSpecified()) 10560 return false; 10561 10562 // We can't delay parsing the body of a function template with a deduced 10563 // return type (yet). 10564 if (D.getDeclSpec().containsPlaceholderType()) { 10565 // If the placeholder introduces a non-deduced trailing return type, 10566 // we can still delay parsing it. 10567 if (D.getNumTypeObjects()) { 10568 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 10569 if (Outer.Kind == DeclaratorChunk::Function && 10570 Outer.Fun.hasTrailingReturnType()) { 10571 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 10572 return Ty.isNull() || !Ty->isUndeducedType(); 10573 } 10574 } 10575 return false; 10576 } 10577 10578 return true; 10579 } 10580 10581 bool Sema::canSkipFunctionBody(Decl *D) { 10582 // We cannot skip the body of a function (or function template) which is 10583 // constexpr, since we may need to evaluate its body in order to parse the 10584 // rest of the file. 10585 // We cannot skip the body of a function with an undeduced return type, 10586 // because any callers of that function need to know the type. 10587 if (const FunctionDecl *FD = D->getAsFunction()) 10588 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 10589 return false; 10590 return Consumer.shouldSkipFunctionBody(D); 10591 } 10592 10593 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 10594 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 10595 FD->setHasSkippedBody(); 10596 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10597 MD->setHasSkippedBody(); 10598 return ActOnFinishFunctionBody(Decl, nullptr); 10599 } 10600 10601 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10602 return ActOnFinishFunctionBody(D, BodyArg, false); 10603 } 10604 10605 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10606 bool IsInstantiation) { 10607 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10608 10609 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10610 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10611 10612 if (FD) { 10613 FD->setBody(Body); 10614 10615 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body && 10616 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10617 // If the function has a deduced result type but contains no 'return' 10618 // statements, the result type as written must be exactly 'auto', and 10619 // the deduced result type is 'void'. 10620 if (!FD->getReturnType()->getAs<AutoType>()) { 10621 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10622 << FD->getReturnType(); 10623 FD->setInvalidDecl(); 10624 } else { 10625 // Substitute 'void' for the 'auto' in the type. 10626 TypeLoc ResultType = getReturnTypeLoc(FD); 10627 Context.adjustDeducedFunctionResultType( 10628 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10629 } 10630 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 10631 auto *LSI = getCurLambda(); 10632 if (LSI->HasImplicitReturnType) { 10633 deduceClosureReturnType(*LSI); 10634 10635 // C++11 [expr.prim.lambda]p4: 10636 // [...] if there are no return statements in the compound-statement 10637 // [the deduced type is] the type void 10638 QualType RetType = 10639 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 10640 10641 // Update the return type to the deduced type. 10642 const FunctionProtoType *Proto = 10643 FD->getType()->getAs<FunctionProtoType>(); 10644 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 10645 Proto->getExtProtoInfo())); 10646 } 10647 } 10648 10649 // The only way to be included in UndefinedButUsed is if there is an 10650 // ODR use before the definition. Avoid the expensive map lookup if this 10651 // is the first declaration. 10652 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 10653 if (!FD->isExternallyVisible()) 10654 UndefinedButUsed.erase(FD); 10655 else if (FD->isInlined() && 10656 !LangOpts.GNUInline && 10657 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 10658 UndefinedButUsed.erase(FD); 10659 } 10660 10661 // If the function implicitly returns zero (like 'main') or is naked, 10662 // don't complain about missing return statements. 10663 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 10664 WP.disableCheckFallThrough(); 10665 10666 // MSVC permits the use of pure specifier (=0) on function definition, 10667 // defined at class scope, warn about this non-standard construct. 10668 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10669 Diag(FD->getLocation(), diag::ext_pure_function_definition); 10670 10671 if (!FD->isInvalidDecl()) { 10672 // Don't diagnose unused parameters of defaulted or deleted functions. 10673 if (!FD->isDeleted() && !FD->isDefaulted()) 10674 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10675 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10676 FD->getReturnType(), FD); 10677 10678 // If this is a structor, we need a vtable. 10679 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10680 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10681 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 10682 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 10683 10684 // Try to apply the named return value optimization. We have to check 10685 // if we can do this here because lambdas keep return statements around 10686 // to deduce an implicit return type. 10687 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10688 !FD->isDependentContext()) 10689 computeNRVO(Body, getCurFunction()); 10690 } 10691 10692 // GNU warning -Wmissing-prototypes: 10693 // Warn if a global function is defined without a previous 10694 // prototype declaration. This warning is issued even if the 10695 // definition itself provides a prototype. The aim is to detect 10696 // global functions that fail to be declared in header files. 10697 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 10698 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 10699 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 10700 10701 if (PossibleZeroParamPrototype) { 10702 // We found a declaration that is not a prototype, 10703 // but that could be a zero-parameter prototype 10704 if (TypeSourceInfo *TI = 10705 PossibleZeroParamPrototype->getTypeSourceInfo()) { 10706 TypeLoc TL = TI->getTypeLoc(); 10707 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 10708 Diag(PossibleZeroParamPrototype->getLocation(), 10709 diag::note_declaration_not_a_prototype) 10710 << PossibleZeroParamPrototype 10711 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 10712 } 10713 } 10714 } 10715 10716 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 10717 const CXXMethodDecl *KeyFunction; 10718 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 10719 MD->isVirtual() && 10720 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 10721 MD == KeyFunction->getCanonicalDecl()) { 10722 // Update the key-function state if necessary for this ABI. 10723 if (FD->isInlined() && 10724 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 10725 Context.setNonKeyFunction(MD); 10726 10727 // If the newly-chosen key function is already defined, then we 10728 // need to mark the vtable as used retroactively. 10729 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 10730 const FunctionDecl *Definition; 10731 if (KeyFunction && KeyFunction->isDefined(Definition)) 10732 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 10733 } else { 10734 // We just defined they key function; mark the vtable as used. 10735 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 10736 } 10737 } 10738 } 10739 10740 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10741 "Function parsing confused"); 10742 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10743 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10744 MD->setBody(Body); 10745 if (!MD->isInvalidDecl()) { 10746 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10747 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10748 MD->getReturnType(), MD); 10749 10750 if (Body) 10751 computeNRVO(Body, getCurFunction()); 10752 } 10753 if (getCurFunction()->ObjCShouldCallSuper) { 10754 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10755 << MD->getSelector().getAsString(); 10756 getCurFunction()->ObjCShouldCallSuper = false; 10757 } 10758 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10759 const ObjCMethodDecl *InitMethod = nullptr; 10760 bool isDesignated = 10761 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10762 assert(isDesignated && InitMethod); 10763 (void)isDesignated; 10764 10765 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10766 auto IFace = MD->getClassInterface(); 10767 if (!IFace) 10768 return false; 10769 auto SuperD = IFace->getSuperClass(); 10770 if (!SuperD) 10771 return false; 10772 return SuperD->getIdentifier() == 10773 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10774 }; 10775 // Don't issue this warning for unavailable inits or direct subclasses 10776 // of NSObject. 10777 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10778 Diag(MD->getLocation(), 10779 diag::warn_objc_designated_init_missing_super_call); 10780 Diag(InitMethod->getLocation(), 10781 diag::note_objc_designated_init_marked_here); 10782 } 10783 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10784 } 10785 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10786 // Don't issue this warning for unavaialable inits. 10787 if (!MD->isUnavailable()) 10788 Diag(MD->getLocation(), 10789 diag::warn_objc_secondary_init_missing_init_call); 10790 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10791 } 10792 } else { 10793 return nullptr; 10794 } 10795 10796 assert(!getCurFunction()->ObjCShouldCallSuper && 10797 "This should only be set for ObjC methods, which should have been " 10798 "handled in the block above."); 10799 10800 // Verify and clean out per-function state. 10801 if (Body && (!FD || !FD->isDefaulted())) { 10802 // C++ constructors that have function-try-blocks can't have return 10803 // statements in the handlers of that block. (C++ [except.handle]p14) 10804 // Verify this. 10805 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10806 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10807 10808 // Verify that gotos and switch cases don't jump into scopes illegally. 10809 if (getCurFunction()->NeedsScopeChecking() && 10810 !PP.isCodeCompletionEnabled()) 10811 DiagnoseInvalidJumps(Body); 10812 10813 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10814 if (!Destructor->getParent()->isDependentType()) 10815 CheckDestructor(Destructor); 10816 10817 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10818 Destructor->getParent()); 10819 } 10820 10821 // If any errors have occurred, clear out any temporaries that may have 10822 // been leftover. This ensures that these temporaries won't be picked up for 10823 // deletion in some later function. 10824 if (getDiagnostics().hasErrorOccurred() || 10825 getDiagnostics().getSuppressAllDiagnostics()) { 10826 DiscardCleanupsInEvaluationContext(); 10827 } 10828 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10829 !isa<FunctionTemplateDecl>(dcl)) { 10830 // Since the body is valid, issue any analysis-based warnings that are 10831 // enabled. 10832 ActivePolicy = &WP; 10833 } 10834 10835 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10836 (!CheckConstexprFunctionDecl(FD) || 10837 !CheckConstexprFunctionBody(FD, Body))) 10838 FD->setInvalidDecl(); 10839 10840 if (FD && FD->hasAttr<NakedAttr>()) { 10841 for (const Stmt *S : Body->children()) { 10842 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 10843 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 10844 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 10845 FD->setInvalidDecl(); 10846 break; 10847 } 10848 } 10849 } 10850 10851 assert(ExprCleanupObjects.size() == 10852 ExprEvalContexts.back().NumCleanupObjects && 10853 "Leftover temporaries in function"); 10854 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10855 assert(MaybeODRUseExprs.empty() && 10856 "Leftover expressions for odr-use checking"); 10857 } 10858 10859 if (!IsInstantiation) 10860 PopDeclContext(); 10861 10862 PopFunctionScopeInfo(ActivePolicy, dcl); 10863 // If any errors have occurred, clear out any temporaries that may have 10864 // been leftover. This ensures that these temporaries won't be picked up for 10865 // deletion in some later function. 10866 if (getDiagnostics().hasErrorOccurred()) { 10867 DiscardCleanupsInEvaluationContext(); 10868 } 10869 10870 return dcl; 10871 } 10872 10873 10874 /// When we finish delayed parsing of an attribute, we must attach it to the 10875 /// relevant Decl. 10876 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10877 ParsedAttributes &Attrs) { 10878 // Always attach attributes to the underlying decl. 10879 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10880 D = TD->getTemplatedDecl(); 10881 ProcessDeclAttributeList(S, D, Attrs.getList()); 10882 10883 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10884 if (Method->isStatic()) 10885 checkThisInStaticMemberFunctionAttributes(Method); 10886 } 10887 10888 10889 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10890 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10891 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10892 IdentifierInfo &II, Scope *S) { 10893 // Before we produce a declaration for an implicitly defined 10894 // function, see whether there was a locally-scoped declaration of 10895 // this name as a function or variable. If so, use that 10896 // (non-visible) declaration, and complain about it. 10897 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10898 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10899 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10900 return ExternCPrev; 10901 } 10902 10903 // Extension in C99. Legal in C90, but warn about it. 10904 unsigned diag_id; 10905 if (II.getName().startswith("__builtin_")) 10906 diag_id = diag::warn_builtin_unknown; 10907 else if (getLangOpts().C99) 10908 diag_id = diag::ext_implicit_function_decl; 10909 else 10910 diag_id = diag::warn_implicit_function_decl; 10911 Diag(Loc, diag_id) << &II; 10912 10913 // Because typo correction is expensive, only do it if the implicit 10914 // function declaration is going to be treated as an error. 10915 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10916 TypoCorrection Corrected; 10917 if (S && 10918 (Corrected = CorrectTypo( 10919 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 10920 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 10921 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10922 /*ErrorRecovery*/false); 10923 } 10924 10925 // Set a Declarator for the implicit definition: int foo(); 10926 const char *Dummy; 10927 AttributeFactory attrFactory; 10928 DeclSpec DS(attrFactory); 10929 unsigned DiagID; 10930 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10931 Context.getPrintingPolicy()); 10932 (void)Error; // Silence warning. 10933 assert(!Error && "Error setting up implicit decl!"); 10934 SourceLocation NoLoc; 10935 Declarator D(DS, Declarator::BlockContext); 10936 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10937 /*IsAmbiguous=*/false, 10938 /*LParenLoc=*/NoLoc, 10939 /*Params=*/nullptr, 10940 /*NumParams=*/0, 10941 /*EllipsisLoc=*/NoLoc, 10942 /*RParenLoc=*/NoLoc, 10943 /*TypeQuals=*/0, 10944 /*RefQualifierIsLvalueRef=*/true, 10945 /*RefQualifierLoc=*/NoLoc, 10946 /*ConstQualifierLoc=*/NoLoc, 10947 /*VolatileQualifierLoc=*/NoLoc, 10948 /*RestrictQualifierLoc=*/NoLoc, 10949 /*MutableLoc=*/NoLoc, 10950 EST_None, 10951 /*ESpecLoc=*/NoLoc, 10952 /*Exceptions=*/nullptr, 10953 /*ExceptionRanges=*/nullptr, 10954 /*NumExceptions=*/0, 10955 /*NoexceptExpr=*/nullptr, 10956 /*ExceptionSpecTokens=*/nullptr, 10957 Loc, Loc, D), 10958 DS.getAttributes(), 10959 SourceLocation()); 10960 D.SetIdentifier(&II, Loc); 10961 10962 // Insert this function into translation-unit scope. 10963 10964 DeclContext *PrevDC = CurContext; 10965 CurContext = Context.getTranslationUnitDecl(); 10966 10967 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10968 FD->setImplicit(); 10969 10970 CurContext = PrevDC; 10971 10972 AddKnownFunctionAttributes(FD); 10973 10974 return FD; 10975 } 10976 10977 /// \brief Adds any function attributes that we know a priori based on 10978 /// the declaration of this function. 10979 /// 10980 /// These attributes can apply both to implicitly-declared builtins 10981 /// (like __builtin___printf_chk) or to library-declared functions 10982 /// like NSLog or printf. 10983 /// 10984 /// We need to check for duplicate attributes both here and where user-written 10985 /// attributes are applied to declarations. 10986 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10987 if (FD->isInvalidDecl()) 10988 return; 10989 10990 // If this is a built-in function, map its builtin attributes to 10991 // actual attributes. 10992 if (unsigned BuiltinID = FD->getBuiltinID()) { 10993 // Handle printf-formatting attributes. 10994 unsigned FormatIdx; 10995 bool HasVAListArg; 10996 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10997 if (!FD->hasAttr<FormatAttr>()) { 10998 const char *fmt = "printf"; 10999 unsigned int NumParams = FD->getNumParams(); 11000 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 11001 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 11002 fmt = "NSString"; 11003 FD->addAttr(FormatAttr::CreateImplicit(Context, 11004 &Context.Idents.get(fmt), 11005 FormatIdx+1, 11006 HasVAListArg ? 0 : FormatIdx+2, 11007 FD->getLocation())); 11008 } 11009 } 11010 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 11011 HasVAListArg)) { 11012 if (!FD->hasAttr<FormatAttr>()) 11013 FD->addAttr(FormatAttr::CreateImplicit(Context, 11014 &Context.Idents.get("scanf"), 11015 FormatIdx+1, 11016 HasVAListArg ? 0 : FormatIdx+2, 11017 FD->getLocation())); 11018 } 11019 11020 // Mark const if we don't care about errno and that is the only 11021 // thing preventing the function from being const. This allows 11022 // IRgen to use LLVM intrinsics for such functions. 11023 if (!getLangOpts().MathErrno && 11024 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 11025 if (!FD->hasAttr<ConstAttr>()) 11026 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11027 } 11028 11029 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 11030 !FD->hasAttr<ReturnsTwiceAttr>()) 11031 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 11032 FD->getLocation())); 11033 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 11034 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 11035 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 11036 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11037 } 11038 11039 IdentifierInfo *Name = FD->getIdentifier(); 11040 if (!Name) 11041 return; 11042 if ((!getLangOpts().CPlusPlus && 11043 FD->getDeclContext()->isTranslationUnit()) || 11044 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 11045 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 11046 LinkageSpecDecl::lang_c)) { 11047 // Okay: this could be a libc/libm/Objective-C function we know 11048 // about. 11049 } else 11050 return; 11051 11052 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 11053 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 11054 // target-specific builtins, perhaps? 11055 if (!FD->hasAttr<FormatAttr>()) 11056 FD->addAttr(FormatAttr::CreateImplicit(Context, 11057 &Context.Idents.get("printf"), 2, 11058 Name->isStr("vasprintf") ? 0 : 3, 11059 FD->getLocation())); 11060 } 11061 11062 if (Name->isStr("__CFStringMakeConstantString")) { 11063 // We already have a __builtin___CFStringMakeConstantString, 11064 // but builds that use -fno-constant-cfstrings don't go through that. 11065 if (!FD->hasAttr<FormatArgAttr>()) 11066 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 11067 FD->getLocation())); 11068 } 11069 } 11070 11071 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 11072 TypeSourceInfo *TInfo) { 11073 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 11074 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 11075 11076 if (!TInfo) { 11077 assert(D.isInvalidType() && "no declarator info for valid type"); 11078 TInfo = Context.getTrivialTypeSourceInfo(T); 11079 } 11080 11081 // Scope manipulation handled by caller. 11082 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 11083 D.getLocStart(), 11084 D.getIdentifierLoc(), 11085 D.getIdentifier(), 11086 TInfo); 11087 11088 // Bail out immediately if we have an invalid declaration. 11089 if (D.isInvalidType()) { 11090 NewTD->setInvalidDecl(); 11091 return NewTD; 11092 } 11093 11094 if (D.getDeclSpec().isModulePrivateSpecified()) { 11095 if (CurContext->isFunctionOrMethod()) 11096 Diag(NewTD->getLocation(), diag::err_module_private_local) 11097 << 2 << NewTD->getDeclName() 11098 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11099 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11100 else 11101 NewTD->setModulePrivate(); 11102 } 11103 11104 // C++ [dcl.typedef]p8: 11105 // If the typedef declaration defines an unnamed class (or 11106 // enum), the first typedef-name declared by the declaration 11107 // to be that class type (or enum type) is used to denote the 11108 // class type (or enum type) for linkage purposes only. 11109 // We need to check whether the type was declared in the declaration. 11110 switch (D.getDeclSpec().getTypeSpecType()) { 11111 case TST_enum: 11112 case TST_struct: 11113 case TST_interface: 11114 case TST_union: 11115 case TST_class: { 11116 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 11117 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 11118 break; 11119 } 11120 11121 default: 11122 break; 11123 } 11124 11125 return NewTD; 11126 } 11127 11128 11129 /// \brief Check that this is a valid underlying type for an enum declaration. 11130 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 11131 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 11132 QualType T = TI->getType(); 11133 11134 if (T->isDependentType()) 11135 return false; 11136 11137 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 11138 if (BT->isInteger()) 11139 return false; 11140 11141 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 11142 return true; 11143 } 11144 11145 /// Check whether this is a valid redeclaration of a previous enumeration. 11146 /// \return true if the redeclaration was invalid. 11147 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 11148 QualType EnumUnderlyingTy, 11149 const EnumDecl *Prev) { 11150 bool IsFixed = !EnumUnderlyingTy.isNull(); 11151 11152 if (IsScoped != Prev->isScoped()) { 11153 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 11154 << Prev->isScoped(); 11155 Diag(Prev->getLocation(), diag::note_previous_declaration); 11156 return true; 11157 } 11158 11159 if (IsFixed && Prev->isFixed()) { 11160 if (!EnumUnderlyingTy->isDependentType() && 11161 !Prev->getIntegerType()->isDependentType() && 11162 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 11163 Prev->getIntegerType())) { 11164 // TODO: Highlight the underlying type of the redeclaration. 11165 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 11166 << EnumUnderlyingTy << Prev->getIntegerType(); 11167 Diag(Prev->getLocation(), diag::note_previous_declaration) 11168 << Prev->getIntegerTypeRange(); 11169 return true; 11170 } 11171 } else if (IsFixed != Prev->isFixed()) { 11172 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 11173 << Prev->isFixed(); 11174 Diag(Prev->getLocation(), diag::note_previous_declaration); 11175 return true; 11176 } 11177 11178 return false; 11179 } 11180 11181 /// \brief Get diagnostic %select index for tag kind for 11182 /// redeclaration diagnostic message. 11183 /// WARNING: Indexes apply to particular diagnostics only! 11184 /// 11185 /// \returns diagnostic %select index. 11186 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 11187 switch (Tag) { 11188 case TTK_Struct: return 0; 11189 case TTK_Interface: return 1; 11190 case TTK_Class: return 2; 11191 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 11192 } 11193 } 11194 11195 /// \brief Determine if tag kind is a class-key compatible with 11196 /// class for redeclaration (class, struct, or __interface). 11197 /// 11198 /// \returns true iff the tag kind is compatible. 11199 static bool isClassCompatTagKind(TagTypeKind Tag) 11200 { 11201 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 11202 } 11203 11204 /// \brief Determine whether a tag with a given kind is acceptable 11205 /// as a redeclaration of the given tag declaration. 11206 /// 11207 /// \returns true if the new tag kind is acceptable, false otherwise. 11208 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 11209 TagTypeKind NewTag, bool isDefinition, 11210 SourceLocation NewTagLoc, 11211 const IdentifierInfo &Name) { 11212 // C++ [dcl.type.elab]p3: 11213 // The class-key or enum keyword present in the 11214 // elaborated-type-specifier shall agree in kind with the 11215 // declaration to which the name in the elaborated-type-specifier 11216 // refers. This rule also applies to the form of 11217 // elaborated-type-specifier that declares a class-name or 11218 // friend class since it can be construed as referring to the 11219 // definition of the class. Thus, in any 11220 // elaborated-type-specifier, the enum keyword shall be used to 11221 // refer to an enumeration (7.2), the union class-key shall be 11222 // used to refer to a union (clause 9), and either the class or 11223 // struct class-key shall be used to refer to a class (clause 9) 11224 // declared using the class or struct class-key. 11225 TagTypeKind OldTag = Previous->getTagKind(); 11226 if (!isDefinition || !isClassCompatTagKind(NewTag)) 11227 if (OldTag == NewTag) 11228 return true; 11229 11230 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 11231 // Warn about the struct/class tag mismatch. 11232 bool isTemplate = false; 11233 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 11234 isTemplate = Record->getDescribedClassTemplate(); 11235 11236 if (!ActiveTemplateInstantiations.empty()) { 11237 // In a template instantiation, do not offer fix-its for tag mismatches 11238 // since they usually mess up the template instead of fixing the problem. 11239 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11240 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11241 << getRedeclDiagFromTagKind(OldTag); 11242 return true; 11243 } 11244 11245 if (isDefinition) { 11246 // On definitions, check previous tags and issue a fix-it for each 11247 // one that doesn't match the current tag. 11248 if (Previous->getDefinition()) { 11249 // Don't suggest fix-its for redefinitions. 11250 return true; 11251 } 11252 11253 bool previousMismatch = false; 11254 for (auto I : Previous->redecls()) { 11255 if (I->getTagKind() != NewTag) { 11256 if (!previousMismatch) { 11257 previousMismatch = true; 11258 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11259 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11260 << getRedeclDiagFromTagKind(I->getTagKind()); 11261 } 11262 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11263 << getRedeclDiagFromTagKind(NewTag) 11264 << FixItHint::CreateReplacement(I->getInnerLocStart(), 11265 TypeWithKeyword::getTagTypeKindName(NewTag)); 11266 } 11267 } 11268 return true; 11269 } 11270 11271 // Check for a previous definition. If current tag and definition 11272 // are same type, do nothing. If no definition, but disagree with 11273 // with previous tag type, give a warning, but no fix-it. 11274 const TagDecl *Redecl = Previous->getDefinition() ? 11275 Previous->getDefinition() : Previous; 11276 if (Redecl->getTagKind() == NewTag) { 11277 return true; 11278 } 11279 11280 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11281 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11282 << getRedeclDiagFromTagKind(OldTag); 11283 Diag(Redecl->getLocation(), diag::note_previous_use); 11284 11285 // If there is a previous definition, suggest a fix-it. 11286 if (Previous->getDefinition()) { 11287 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11288 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11289 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11290 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11291 } 11292 11293 return true; 11294 } 11295 return false; 11296 } 11297 11298 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11299 /// from an outer enclosing namespace or file scope inside a friend declaration. 11300 /// This should provide the commented out code in the following snippet: 11301 /// namespace N { 11302 /// struct X; 11303 /// namespace M { 11304 /// struct Y { friend struct /*N::*/ X; }; 11305 /// } 11306 /// } 11307 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11308 SourceLocation NameLoc) { 11309 // While the decl is in a namespace, do repeated lookup of that name and see 11310 // if we get the same namespace back. If we do not, continue until 11311 // translation unit scope, at which point we have a fully qualified NNS. 11312 SmallVector<IdentifierInfo *, 4> Namespaces; 11313 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11314 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11315 // This tag should be declared in a namespace, which can only be enclosed by 11316 // other namespaces. Bail if there's an anonymous namespace in the chain. 11317 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11318 if (!Namespace || Namespace->isAnonymousNamespace()) 11319 return FixItHint(); 11320 IdentifierInfo *II = Namespace->getIdentifier(); 11321 Namespaces.push_back(II); 11322 NamedDecl *Lookup = SemaRef.LookupSingleName( 11323 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11324 if (Lookup == Namespace) 11325 break; 11326 } 11327 11328 // Once we have all the namespaces, reverse them to go outermost first, and 11329 // build an NNS. 11330 SmallString<64> Insertion; 11331 llvm::raw_svector_ostream OS(Insertion); 11332 if (DC->isTranslationUnit()) 11333 OS << "::"; 11334 std::reverse(Namespaces.begin(), Namespaces.end()); 11335 for (auto *II : Namespaces) 11336 OS << II->getName() << "::"; 11337 OS.flush(); 11338 return FixItHint::CreateInsertion(NameLoc, Insertion); 11339 } 11340 11341 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 11342 /// former case, Name will be non-null. In the later case, Name will be null. 11343 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11344 /// reference/declaration/definition of a tag. 11345 /// 11346 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 11347 /// trailing-type-specifier) other than one in an alias-declaration. 11348 /// 11349 /// \param SkipBody If non-null, will be set to indicate if the caller should 11350 /// skip the definition of this tag and treat it as if it were a declaration. 11351 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11352 SourceLocation KWLoc, CXXScopeSpec &SS, 11353 IdentifierInfo *Name, SourceLocation NameLoc, 11354 AttributeList *Attr, AccessSpecifier AS, 11355 SourceLocation ModulePrivateLoc, 11356 MultiTemplateParamsArg TemplateParameterLists, 11357 bool &OwnedDecl, bool &IsDependent, 11358 SourceLocation ScopedEnumKWLoc, 11359 bool ScopedEnumUsesClassTag, 11360 TypeResult UnderlyingType, 11361 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 11362 // If this is not a definition, it must have a name. 11363 IdentifierInfo *OrigName = Name; 11364 assert((Name != nullptr || TUK == TUK_Definition) && 11365 "Nameless record must be a definition!"); 11366 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11367 11368 OwnedDecl = false; 11369 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11370 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11371 11372 // FIXME: Check explicit specializations more carefully. 11373 bool isExplicitSpecialization = false; 11374 bool Invalid = false; 11375 11376 // We only need to do this matching if we have template parameters 11377 // or a scope specifier, which also conveniently avoids this work 11378 // for non-C++ cases. 11379 if (TemplateParameterLists.size() > 0 || 11380 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11381 if (TemplateParameterList *TemplateParams = 11382 MatchTemplateParametersToScopeSpecifier( 11383 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11384 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11385 if (Kind == TTK_Enum) { 11386 Diag(KWLoc, diag::err_enum_template); 11387 return nullptr; 11388 } 11389 11390 if (TemplateParams->size() > 0) { 11391 // This is a declaration or definition of a class template (which may 11392 // be a member of another template). 11393 11394 if (Invalid) 11395 return nullptr; 11396 11397 OwnedDecl = false; 11398 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11399 SS, Name, NameLoc, Attr, 11400 TemplateParams, AS, 11401 ModulePrivateLoc, 11402 /*FriendLoc*/SourceLocation(), 11403 TemplateParameterLists.size()-1, 11404 TemplateParameterLists.data(), 11405 SkipBody); 11406 return Result.get(); 11407 } else { 11408 // The "template<>" header is extraneous. 11409 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11410 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11411 isExplicitSpecialization = true; 11412 } 11413 } 11414 } 11415 11416 // Figure out the underlying type if this a enum declaration. We need to do 11417 // this early, because it's needed to detect if this is an incompatible 11418 // redeclaration. 11419 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 11420 11421 if (Kind == TTK_Enum) { 11422 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 11423 // No underlying type explicitly specified, or we failed to parse the 11424 // type, default to int. 11425 EnumUnderlying = Context.IntTy.getTypePtr(); 11426 else if (UnderlyingType.get()) { 11427 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 11428 // integral type; any cv-qualification is ignored. 11429 TypeSourceInfo *TI = nullptr; 11430 GetTypeFromParser(UnderlyingType.get(), &TI); 11431 EnumUnderlying = TI; 11432 11433 if (CheckEnumUnderlyingType(TI)) 11434 // Recover by falling back to int. 11435 EnumUnderlying = Context.IntTy.getTypePtr(); 11436 11437 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 11438 UPPC_FixedUnderlyingType)) 11439 EnumUnderlying = Context.IntTy.getTypePtr(); 11440 11441 } else if (getLangOpts().MSVCCompat) 11442 // Microsoft enums are always of int type. 11443 EnumUnderlying = Context.IntTy.getTypePtr(); 11444 } 11445 11446 DeclContext *SearchDC = CurContext; 11447 DeclContext *DC = CurContext; 11448 bool isStdBadAlloc = false; 11449 11450 RedeclarationKind Redecl = ForRedeclaration; 11451 if (TUK == TUK_Friend || TUK == TUK_Reference) 11452 Redecl = NotForRedeclaration; 11453 11454 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 11455 if (Name && SS.isNotEmpty()) { 11456 // We have a nested-name tag ('struct foo::bar'). 11457 11458 // Check for invalid 'foo::'. 11459 if (SS.isInvalid()) { 11460 Name = nullptr; 11461 goto CreateNewDecl; 11462 } 11463 11464 // If this is a friend or a reference to a class in a dependent 11465 // context, don't try to make a decl for it. 11466 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11467 DC = computeDeclContext(SS, false); 11468 if (!DC) { 11469 IsDependent = true; 11470 return nullptr; 11471 } 11472 } else { 11473 DC = computeDeclContext(SS, true); 11474 if (!DC) { 11475 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 11476 << SS.getRange(); 11477 return nullptr; 11478 } 11479 } 11480 11481 if (RequireCompleteDeclContext(SS, DC)) 11482 return nullptr; 11483 11484 SearchDC = DC; 11485 // Look-up name inside 'foo::'. 11486 LookupQualifiedName(Previous, DC); 11487 11488 if (Previous.isAmbiguous()) 11489 return nullptr; 11490 11491 if (Previous.empty()) { 11492 // Name lookup did not find anything. However, if the 11493 // nested-name-specifier refers to the current instantiation, 11494 // and that current instantiation has any dependent base 11495 // classes, we might find something at instantiation time: treat 11496 // this as a dependent elaborated-type-specifier. 11497 // But this only makes any sense for reference-like lookups. 11498 if (Previous.wasNotFoundInCurrentInstantiation() && 11499 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11500 IsDependent = true; 11501 return nullptr; 11502 } 11503 11504 // A tag 'foo::bar' must already exist. 11505 Diag(NameLoc, diag::err_not_tag_in_scope) 11506 << Kind << Name << DC << SS.getRange(); 11507 Name = nullptr; 11508 Invalid = true; 11509 goto CreateNewDecl; 11510 } 11511 } else if (Name) { 11512 // If this is a named struct, check to see if there was a previous forward 11513 // declaration or definition. 11514 // FIXME: We're looking into outer scopes here, even when we 11515 // shouldn't be. Doing so can result in ambiguities that we 11516 // shouldn't be diagnosing. 11517 LookupName(Previous, S); 11518 11519 // When declaring or defining a tag, ignore ambiguities introduced 11520 // by types using'ed into this scope. 11521 if (Previous.isAmbiguous() && 11522 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 11523 LookupResult::Filter F = Previous.makeFilter(); 11524 while (F.hasNext()) { 11525 NamedDecl *ND = F.next(); 11526 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 11527 F.erase(); 11528 } 11529 F.done(); 11530 } 11531 11532 // C++11 [namespace.memdef]p3: 11533 // If the name in a friend declaration is neither qualified nor 11534 // a template-id and the declaration is a function or an 11535 // elaborated-type-specifier, the lookup to determine whether 11536 // the entity has been previously declared shall not consider 11537 // any scopes outside the innermost enclosing namespace. 11538 // 11539 // MSVC doesn't implement the above rule for types, so a friend tag 11540 // declaration may be a redeclaration of a type declared in an enclosing 11541 // scope. They do implement this rule for friend functions. 11542 // 11543 // Does it matter that this should be by scope instead of by 11544 // semantic context? 11545 if (!Previous.empty() && TUK == TUK_Friend) { 11546 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 11547 LookupResult::Filter F = Previous.makeFilter(); 11548 bool FriendSawTagOutsideEnclosingNamespace = false; 11549 while (F.hasNext()) { 11550 NamedDecl *ND = F.next(); 11551 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11552 if (DC->isFileContext() && 11553 !EnclosingNS->Encloses(ND->getDeclContext())) { 11554 if (getLangOpts().MSVCCompat) 11555 FriendSawTagOutsideEnclosingNamespace = true; 11556 else 11557 F.erase(); 11558 } 11559 } 11560 F.done(); 11561 11562 // Diagnose this MSVC extension in the easy case where lookup would have 11563 // unambiguously found something outside the enclosing namespace. 11564 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 11565 NamedDecl *ND = Previous.getFoundDecl(); 11566 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 11567 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 11568 } 11569 } 11570 11571 // Note: there used to be some attempt at recovery here. 11572 if (Previous.isAmbiguous()) 11573 return nullptr; 11574 11575 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 11576 // FIXME: This makes sure that we ignore the contexts associated 11577 // with C structs, unions, and enums when looking for a matching 11578 // tag declaration or definition. See the similar lookup tweak 11579 // in Sema::LookupName; is there a better way to deal with this? 11580 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 11581 SearchDC = SearchDC->getParent(); 11582 } 11583 } 11584 11585 if (Previous.isSingleResult() && 11586 Previous.getFoundDecl()->isTemplateParameter()) { 11587 // Maybe we will complain about the shadowed template parameter. 11588 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 11589 // Just pretend that we didn't see the previous declaration. 11590 Previous.clear(); 11591 } 11592 11593 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 11594 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 11595 // This is a declaration of or a reference to "std::bad_alloc". 11596 isStdBadAlloc = true; 11597 11598 if (Previous.empty() && StdBadAlloc) { 11599 // std::bad_alloc has been implicitly declared (but made invisible to 11600 // name lookup). Fill in this implicit declaration as the previous 11601 // declaration, so that the declarations get chained appropriately. 11602 Previous.addDecl(getStdBadAlloc()); 11603 } 11604 } 11605 11606 // If we didn't find a previous declaration, and this is a reference 11607 // (or friend reference), move to the correct scope. In C++, we 11608 // also need to do a redeclaration lookup there, just in case 11609 // there's a shadow friend decl. 11610 if (Name && Previous.empty() && 11611 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11612 if (Invalid) goto CreateNewDecl; 11613 assert(SS.isEmpty()); 11614 11615 if (TUK == TUK_Reference) { 11616 // C++ [basic.scope.pdecl]p5: 11617 // -- for an elaborated-type-specifier of the form 11618 // 11619 // class-key identifier 11620 // 11621 // if the elaborated-type-specifier is used in the 11622 // decl-specifier-seq or parameter-declaration-clause of a 11623 // function defined in namespace scope, the identifier is 11624 // declared as a class-name in the namespace that contains 11625 // the declaration; otherwise, except as a friend 11626 // declaration, the identifier is declared in the smallest 11627 // non-class, non-function-prototype scope that contains the 11628 // declaration. 11629 // 11630 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 11631 // C structs and unions. 11632 // 11633 // It is an error in C++ to declare (rather than define) an enum 11634 // type, including via an elaborated type specifier. We'll 11635 // diagnose that later; for now, declare the enum in the same 11636 // scope as we would have picked for any other tag type. 11637 // 11638 // GNU C also supports this behavior as part of its incomplete 11639 // enum types extension, while GNU C++ does not. 11640 // 11641 // Find the context where we'll be declaring the tag. 11642 // FIXME: We would like to maintain the current DeclContext as the 11643 // lexical context, 11644 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 11645 SearchDC = SearchDC->getParent(); 11646 11647 // Find the scope where we'll be declaring the tag. 11648 while (S->isClassScope() || 11649 (getLangOpts().CPlusPlus && 11650 S->isFunctionPrototypeScope()) || 11651 ((S->getFlags() & Scope::DeclScope) == 0) || 11652 (S->getEntity() && S->getEntity()->isTransparentContext())) 11653 S = S->getParent(); 11654 } else { 11655 assert(TUK == TUK_Friend); 11656 // C++ [namespace.memdef]p3: 11657 // If a friend declaration in a non-local class first declares a 11658 // class or function, the friend class or function is a member of 11659 // the innermost enclosing namespace. 11660 SearchDC = SearchDC->getEnclosingNamespaceContext(); 11661 } 11662 11663 // In C++, we need to do a redeclaration lookup to properly 11664 // diagnose some problems. 11665 if (getLangOpts().CPlusPlus) { 11666 Previous.setRedeclarationKind(ForRedeclaration); 11667 LookupQualifiedName(Previous, SearchDC); 11668 } 11669 } 11670 11671 // If we have a known previous declaration to use, then use it. 11672 if (Previous.empty() && SkipBody && SkipBody->Previous) 11673 Previous.addDecl(SkipBody->Previous); 11674 11675 if (!Previous.empty()) { 11676 NamedDecl *PrevDecl = Previous.getFoundDecl(); 11677 NamedDecl *DirectPrevDecl = 11678 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 11679 11680 // It's okay to have a tag decl in the same scope as a typedef 11681 // which hides a tag decl in the same scope. Finding this 11682 // insanity with a redeclaration lookup can only actually happen 11683 // in C++. 11684 // 11685 // This is also okay for elaborated-type-specifiers, which is 11686 // technically forbidden by the current standard but which is 11687 // okay according to the likely resolution of an open issue; 11688 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 11689 if (getLangOpts().CPlusPlus) { 11690 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11691 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 11692 TagDecl *Tag = TT->getDecl(); 11693 if (Tag->getDeclName() == Name && 11694 Tag->getDeclContext()->getRedeclContext() 11695 ->Equals(TD->getDeclContext()->getRedeclContext())) { 11696 PrevDecl = Tag; 11697 Previous.clear(); 11698 Previous.addDecl(Tag); 11699 Previous.resolveKind(); 11700 } 11701 } 11702 } 11703 } 11704 11705 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 11706 // If this is a use of a previous tag, or if the tag is already declared 11707 // in the same scope (so that the definition/declaration completes or 11708 // rementions the tag), reuse the decl. 11709 if (TUK == TUK_Reference || TUK == TUK_Friend || 11710 isDeclInScope(DirectPrevDecl, SearchDC, S, 11711 SS.isNotEmpty() || isExplicitSpecialization)) { 11712 // Make sure that this wasn't declared as an enum and now used as a 11713 // struct or something similar. 11714 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 11715 TUK == TUK_Definition, KWLoc, 11716 *Name)) { 11717 bool SafeToContinue 11718 = (PrevTagDecl->getTagKind() != TTK_Enum && 11719 Kind != TTK_Enum); 11720 if (SafeToContinue) 11721 Diag(KWLoc, diag::err_use_with_wrong_tag) 11722 << Name 11723 << FixItHint::CreateReplacement(SourceRange(KWLoc), 11724 PrevTagDecl->getKindName()); 11725 else 11726 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 11727 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 11728 11729 if (SafeToContinue) 11730 Kind = PrevTagDecl->getTagKind(); 11731 else { 11732 // Recover by making this an anonymous redefinition. 11733 Name = nullptr; 11734 Previous.clear(); 11735 Invalid = true; 11736 } 11737 } 11738 11739 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 11740 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 11741 11742 // If this is an elaborated-type-specifier for a scoped enumeration, 11743 // the 'class' keyword is not necessary and not permitted. 11744 if (TUK == TUK_Reference || TUK == TUK_Friend) { 11745 if (ScopedEnum) 11746 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 11747 << PrevEnum->isScoped() 11748 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 11749 return PrevTagDecl; 11750 } 11751 11752 QualType EnumUnderlyingTy; 11753 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11754 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 11755 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 11756 EnumUnderlyingTy = QualType(T, 0); 11757 11758 // All conflicts with previous declarations are recovered by 11759 // returning the previous declaration, unless this is a definition, 11760 // in which case we want the caller to bail out. 11761 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11762 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11763 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11764 } 11765 11766 // C++11 [class.mem]p1: 11767 // A member shall not be declared twice in the member-specification, 11768 // except that a nested class or member class template can be declared 11769 // and then later defined. 11770 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11771 S->isDeclScope(PrevDecl)) { 11772 Diag(NameLoc, diag::ext_member_redeclared); 11773 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11774 } 11775 11776 if (!Invalid) { 11777 // If this is a use, just return the declaration we found, unless 11778 // we have attributes. 11779 11780 // FIXME: In the future, return a variant or some other clue 11781 // for the consumer of this Decl to know it doesn't own it. 11782 // For our current ASTs this shouldn't be a problem, but will 11783 // need to be changed with DeclGroups. 11784 if (!Attr && 11785 ((TUK == TUK_Reference && 11786 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11787 || TUK == TUK_Friend)) 11788 return PrevTagDecl; 11789 11790 // Diagnose attempts to redefine a tag. 11791 if (TUK == TUK_Definition) { 11792 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 11793 // If we're defining a specialization and the previous definition 11794 // is from an implicit instantiation, don't emit an error 11795 // here; we'll catch this in the general case below. 11796 bool IsExplicitSpecializationAfterInstantiation = false; 11797 if (isExplicitSpecialization) { 11798 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11799 IsExplicitSpecializationAfterInstantiation = 11800 RD->getTemplateSpecializationKind() != 11801 TSK_ExplicitSpecialization; 11802 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11803 IsExplicitSpecializationAfterInstantiation = 11804 ED->getTemplateSpecializationKind() != 11805 TSK_ExplicitSpecialization; 11806 } 11807 11808 NamedDecl *Hidden = nullptr; 11809 if (SkipBody && getLangOpts().CPlusPlus && 11810 !hasVisibleDefinition(Def, &Hidden)) { 11811 // There is a definition of this tag, but it is not visible. We 11812 // explicitly make use of C++'s one definition rule here, and 11813 // assume that this definition is identical to the hidden one 11814 // we already have. Make the existing definition visible and 11815 // use it in place of this one. 11816 SkipBody->ShouldSkip = true; 11817 makeMergedDefinitionVisible(Hidden, KWLoc); 11818 return Def; 11819 } else if (!IsExplicitSpecializationAfterInstantiation) { 11820 // A redeclaration in function prototype scope in C isn't 11821 // visible elsewhere, so merely issue a warning. 11822 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11823 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11824 else 11825 Diag(NameLoc, diag::err_redefinition) << Name; 11826 Diag(Def->getLocation(), diag::note_previous_definition); 11827 // If this is a redefinition, recover by making this 11828 // struct be anonymous, which will make any later 11829 // references get the previous definition. 11830 Name = nullptr; 11831 Previous.clear(); 11832 Invalid = true; 11833 } 11834 } else { 11835 // If the type is currently being defined, complain 11836 // about a nested redefinition. 11837 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 11838 if (TD->isBeingDefined()) { 11839 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11840 Diag(PrevTagDecl->getLocation(), 11841 diag::note_previous_definition); 11842 Name = nullptr; 11843 Previous.clear(); 11844 Invalid = true; 11845 } 11846 } 11847 11848 // Okay, this is definition of a previously declared or referenced 11849 // tag. We're going to create a new Decl for it. 11850 } 11851 11852 // Okay, we're going to make a redeclaration. If this is some kind 11853 // of reference, make sure we build the redeclaration in the same DC 11854 // as the original, and ignore the current access specifier. 11855 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11856 SearchDC = PrevTagDecl->getDeclContext(); 11857 AS = AS_none; 11858 } 11859 } 11860 // If we get here we have (another) forward declaration or we 11861 // have a definition. Just create a new decl. 11862 11863 } else { 11864 // If we get here, this is a definition of a new tag type in a nested 11865 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11866 // new decl/type. We set PrevDecl to NULL so that the entities 11867 // have distinct types. 11868 Previous.clear(); 11869 } 11870 // If we get here, we're going to create a new Decl. If PrevDecl 11871 // is non-NULL, it's a definition of the tag declared by 11872 // PrevDecl. If it's NULL, we have a new definition. 11873 11874 11875 // Otherwise, PrevDecl is not a tag, but was found with tag 11876 // lookup. This is only actually possible in C++, where a few 11877 // things like templates still live in the tag namespace. 11878 } else { 11879 // Use a better diagnostic if an elaborated-type-specifier 11880 // found the wrong kind of type on the first 11881 // (non-redeclaration) lookup. 11882 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11883 !Previous.isForRedeclaration()) { 11884 unsigned Kind = 0; 11885 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11886 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11887 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11888 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11889 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11890 Invalid = true; 11891 11892 // Otherwise, only diagnose if the declaration is in scope. 11893 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11894 SS.isNotEmpty() || isExplicitSpecialization)) { 11895 // do nothing 11896 11897 // Diagnose implicit declarations introduced by elaborated types. 11898 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11899 unsigned Kind = 0; 11900 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11901 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11902 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11903 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11904 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11905 Invalid = true; 11906 11907 // Otherwise it's a declaration. Call out a particularly common 11908 // case here. 11909 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11910 unsigned Kind = 0; 11911 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11912 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11913 << Name << Kind << TND->getUnderlyingType(); 11914 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11915 Invalid = true; 11916 11917 // Otherwise, diagnose. 11918 } else { 11919 // The tag name clashes with something else in the target scope, 11920 // issue an error and recover by making this tag be anonymous. 11921 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11922 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11923 Name = nullptr; 11924 Invalid = true; 11925 } 11926 11927 // The existing declaration isn't relevant to us; we're in a 11928 // new scope, so clear out the previous declaration. 11929 Previous.clear(); 11930 } 11931 } 11932 11933 CreateNewDecl: 11934 11935 TagDecl *PrevDecl = nullptr; 11936 if (Previous.isSingleResult()) 11937 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11938 11939 // If there is an identifier, use the location of the identifier as the 11940 // location of the decl, otherwise use the location of the struct/union 11941 // keyword. 11942 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11943 11944 // Otherwise, create a new declaration. If there is a previous 11945 // declaration of the same entity, the two will be linked via 11946 // PrevDecl. 11947 TagDecl *New; 11948 11949 bool IsForwardReference = false; 11950 if (Kind == TTK_Enum) { 11951 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11952 // enum X { A, B, C } D; D should chain to X. 11953 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11954 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11955 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11956 // If this is an undefined enum, warn. 11957 if (TUK != TUK_Definition && !Invalid) { 11958 TagDecl *Def; 11959 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11960 cast<EnumDecl>(New)->isFixed()) { 11961 // C++0x: 7.2p2: opaque-enum-declaration. 11962 // Conflicts are diagnosed above. Do nothing. 11963 } 11964 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11965 Diag(Loc, diag::ext_forward_ref_enum_def) 11966 << New; 11967 Diag(Def->getLocation(), diag::note_previous_definition); 11968 } else { 11969 unsigned DiagID = diag::ext_forward_ref_enum; 11970 if (getLangOpts().MSVCCompat) 11971 DiagID = diag::ext_ms_forward_ref_enum; 11972 else if (getLangOpts().CPlusPlus) 11973 DiagID = diag::err_forward_ref_enum; 11974 Diag(Loc, DiagID); 11975 11976 // If this is a forward-declared reference to an enumeration, make a 11977 // note of it; we won't actually be introducing the declaration into 11978 // the declaration context. 11979 if (TUK == TUK_Reference) 11980 IsForwardReference = true; 11981 } 11982 } 11983 11984 if (EnumUnderlying) { 11985 EnumDecl *ED = cast<EnumDecl>(New); 11986 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11987 ED->setIntegerTypeSourceInfo(TI); 11988 else 11989 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11990 ED->setPromotionType(ED->getIntegerType()); 11991 } 11992 11993 } else { 11994 // struct/union/class 11995 11996 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11997 // struct X { int A; } D; D should chain to X. 11998 if (getLangOpts().CPlusPlus) { 11999 // FIXME: Look for a way to use RecordDecl for simple structs. 12000 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12001 cast_or_null<CXXRecordDecl>(PrevDecl)); 12002 12003 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 12004 StdBadAlloc = cast<CXXRecordDecl>(New); 12005 } else 12006 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12007 cast_or_null<RecordDecl>(PrevDecl)); 12008 } 12009 12010 // C++11 [dcl.type]p3: 12011 // A type-specifier-seq shall not define a class or enumeration [...]. 12012 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 12013 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 12014 << Context.getTagDeclType(New); 12015 Invalid = true; 12016 } 12017 12018 // Maybe add qualifier info. 12019 if (SS.isNotEmpty()) { 12020 if (SS.isSet()) { 12021 // If this is either a declaration or a definition, check the 12022 // nested-name-specifier against the current context. We don't do this 12023 // for explicit specializations, because they have similar checking 12024 // (with more specific diagnostics) in the call to 12025 // CheckMemberSpecialization, below. 12026 if (!isExplicitSpecialization && 12027 (TUK == TUK_Definition || TUK == TUK_Declaration) && 12028 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 12029 Invalid = true; 12030 12031 New->setQualifierInfo(SS.getWithLocInContext(Context)); 12032 if (TemplateParameterLists.size() > 0) { 12033 New->setTemplateParameterListsInfo(Context, 12034 TemplateParameterLists.size(), 12035 TemplateParameterLists.data()); 12036 } 12037 } 12038 else 12039 Invalid = true; 12040 } 12041 12042 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 12043 // Add alignment attributes if necessary; these attributes are checked when 12044 // the ASTContext lays out the structure. 12045 // 12046 // It is important for implementing the correct semantics that this 12047 // happen here (in act on tag decl). The #pragma pack stack is 12048 // maintained as a result of parser callbacks which can occur at 12049 // many points during the parsing of a struct declaration (because 12050 // the #pragma tokens are effectively skipped over during the 12051 // parsing of the struct). 12052 if (TUK == TUK_Definition) { 12053 AddAlignmentAttributesForRecord(RD); 12054 AddMsStructLayoutForRecord(RD); 12055 } 12056 } 12057 12058 if (ModulePrivateLoc.isValid()) { 12059 if (isExplicitSpecialization) 12060 Diag(New->getLocation(), diag::err_module_private_specialization) 12061 << 2 12062 << FixItHint::CreateRemoval(ModulePrivateLoc); 12063 // __module_private__ does not apply to local classes. However, we only 12064 // diagnose this as an error when the declaration specifiers are 12065 // freestanding. Here, we just ignore the __module_private__. 12066 else if (!SearchDC->isFunctionOrMethod()) 12067 New->setModulePrivate(); 12068 } 12069 12070 // If this is a specialization of a member class (of a class template), 12071 // check the specialization. 12072 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 12073 Invalid = true; 12074 12075 // If we're declaring or defining a tag in function prototype scope in C, 12076 // note that this type can only be used within the function and add it to 12077 // the list of decls to inject into the function definition scope. 12078 if ((Name || Kind == TTK_Enum) && 12079 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 12080 if (getLangOpts().CPlusPlus) { 12081 // C++ [dcl.fct]p6: 12082 // Types shall not be defined in return or parameter types. 12083 if (TUK == TUK_Definition && !IsTypeSpecifier) { 12084 Diag(Loc, diag::err_type_defined_in_param_type) 12085 << Name; 12086 Invalid = true; 12087 } 12088 } else { 12089 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 12090 } 12091 DeclsInPrototypeScope.push_back(New); 12092 } 12093 12094 if (Invalid) 12095 New->setInvalidDecl(); 12096 12097 if (Attr) 12098 ProcessDeclAttributeList(S, New, Attr); 12099 12100 // Set the lexical context. If the tag has a C++ scope specifier, the 12101 // lexical context will be different from the semantic context. 12102 New->setLexicalDeclContext(CurContext); 12103 12104 // Mark this as a friend decl if applicable. 12105 // In Microsoft mode, a friend declaration also acts as a forward 12106 // declaration so we always pass true to setObjectOfFriendDecl to make 12107 // the tag name visible. 12108 if (TUK == TUK_Friend) 12109 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 12110 12111 // Set the access specifier. 12112 if (!Invalid && SearchDC->isRecord()) 12113 SetMemberAccessSpecifier(New, PrevDecl, AS); 12114 12115 if (TUK == TUK_Definition) 12116 New->startDefinition(); 12117 12118 // If this has an identifier, add it to the scope stack. 12119 if (TUK == TUK_Friend) { 12120 // We might be replacing an existing declaration in the lookup tables; 12121 // if so, borrow its access specifier. 12122 if (PrevDecl) 12123 New->setAccess(PrevDecl->getAccess()); 12124 12125 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 12126 DC->makeDeclVisibleInContext(New); 12127 if (Name) // can be null along some error paths 12128 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12129 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 12130 } else if (Name) { 12131 S = getNonFieldDeclScope(S); 12132 PushOnScopeChains(New, S, !IsForwardReference); 12133 if (IsForwardReference) 12134 SearchDC->makeDeclVisibleInContext(New); 12135 12136 } else { 12137 CurContext->addDecl(New); 12138 } 12139 12140 // If this is the C FILE type, notify the AST context. 12141 if (IdentifierInfo *II = New->getIdentifier()) 12142 if (!New->isInvalidDecl() && 12143 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 12144 II->isStr("FILE")) 12145 Context.setFILEDecl(New); 12146 12147 if (PrevDecl) 12148 mergeDeclAttributes(New, PrevDecl); 12149 12150 // If there's a #pragma GCC visibility in scope, set the visibility of this 12151 // record. 12152 AddPushedVisibilityAttribute(New); 12153 12154 OwnedDecl = true; 12155 // In C++, don't return an invalid declaration. We can't recover well from 12156 // the cases where we make the type anonymous. 12157 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 12158 } 12159 12160 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 12161 AdjustDeclIfTemplate(TagD); 12162 TagDecl *Tag = cast<TagDecl>(TagD); 12163 12164 // Enter the tag context. 12165 PushDeclContext(S, Tag); 12166 12167 ActOnDocumentableDecl(TagD); 12168 12169 // If there's a #pragma GCC visibility in scope, set the visibility of this 12170 // record. 12171 AddPushedVisibilityAttribute(Tag); 12172 } 12173 12174 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 12175 assert(isa<ObjCContainerDecl>(IDecl) && 12176 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 12177 DeclContext *OCD = cast<DeclContext>(IDecl); 12178 assert(getContainingDC(OCD) == CurContext && 12179 "The next DeclContext should be lexically contained in the current one."); 12180 CurContext = OCD; 12181 return IDecl; 12182 } 12183 12184 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 12185 SourceLocation FinalLoc, 12186 bool IsFinalSpelledSealed, 12187 SourceLocation LBraceLoc) { 12188 AdjustDeclIfTemplate(TagD); 12189 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 12190 12191 FieldCollector->StartClass(); 12192 12193 if (!Record->getIdentifier()) 12194 return; 12195 12196 if (FinalLoc.isValid()) 12197 Record->addAttr(new (Context) 12198 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 12199 12200 // C++ [class]p2: 12201 // [...] The class-name is also inserted into the scope of the 12202 // class itself; this is known as the injected-class-name. For 12203 // purposes of access checking, the injected-class-name is treated 12204 // as if it were a public member name. 12205 CXXRecordDecl *InjectedClassName 12206 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 12207 Record->getLocStart(), Record->getLocation(), 12208 Record->getIdentifier(), 12209 /*PrevDecl=*/nullptr, 12210 /*DelayTypeCreation=*/true); 12211 Context.getTypeDeclType(InjectedClassName, Record); 12212 InjectedClassName->setImplicit(); 12213 InjectedClassName->setAccess(AS_public); 12214 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 12215 InjectedClassName->setDescribedClassTemplate(Template); 12216 PushOnScopeChains(InjectedClassName, S); 12217 assert(InjectedClassName->isInjectedClassName() && 12218 "Broken injected-class-name"); 12219 } 12220 12221 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 12222 SourceLocation RBraceLoc) { 12223 AdjustDeclIfTemplate(TagD); 12224 TagDecl *Tag = cast<TagDecl>(TagD); 12225 Tag->setRBraceLoc(RBraceLoc); 12226 12227 // Make sure we "complete" the definition even it is invalid. 12228 if (Tag->isBeingDefined()) { 12229 assert(Tag->isInvalidDecl() && "We should already have completed it"); 12230 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12231 RD->completeDefinition(); 12232 } 12233 12234 if (isa<CXXRecordDecl>(Tag)) 12235 FieldCollector->FinishClass(); 12236 12237 // Exit this scope of this tag's definition. 12238 PopDeclContext(); 12239 12240 if (getCurLexicalContext()->isObjCContainer() && 12241 Tag->getDeclContext()->isFileContext()) 12242 Tag->setTopLevelDeclInObjCContainer(); 12243 12244 // Notify the consumer that we've defined a tag. 12245 if (!Tag->isInvalidDecl()) 12246 Consumer.HandleTagDeclDefinition(Tag); 12247 } 12248 12249 void Sema::ActOnObjCContainerFinishDefinition() { 12250 // Exit this scope of this interface definition. 12251 PopDeclContext(); 12252 } 12253 12254 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 12255 assert(DC == CurContext && "Mismatch of container contexts"); 12256 OriginalLexicalContext = DC; 12257 ActOnObjCContainerFinishDefinition(); 12258 } 12259 12260 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 12261 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 12262 OriginalLexicalContext = nullptr; 12263 } 12264 12265 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 12266 AdjustDeclIfTemplate(TagD); 12267 TagDecl *Tag = cast<TagDecl>(TagD); 12268 Tag->setInvalidDecl(); 12269 12270 // Make sure we "complete" the definition even it is invalid. 12271 if (Tag->isBeingDefined()) { 12272 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12273 RD->completeDefinition(); 12274 } 12275 12276 // We're undoing ActOnTagStartDefinition here, not 12277 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 12278 // the FieldCollector. 12279 12280 PopDeclContext(); 12281 } 12282 12283 // Note that FieldName may be null for anonymous bitfields. 12284 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 12285 IdentifierInfo *FieldName, 12286 QualType FieldTy, bool IsMsStruct, 12287 Expr *BitWidth, bool *ZeroWidth) { 12288 // Default to true; that shouldn't confuse checks for emptiness 12289 if (ZeroWidth) 12290 *ZeroWidth = true; 12291 12292 // C99 6.7.2.1p4 - verify the field type. 12293 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 12294 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 12295 // Handle incomplete types with specific error. 12296 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12297 return ExprError(); 12298 if (FieldName) 12299 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12300 << FieldName << FieldTy << BitWidth->getSourceRange(); 12301 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12302 << FieldTy << BitWidth->getSourceRange(); 12303 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12304 UPPC_BitFieldWidth)) 12305 return ExprError(); 12306 12307 // If the bit-width is type- or value-dependent, don't try to check 12308 // it now. 12309 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12310 return BitWidth; 12311 12312 llvm::APSInt Value; 12313 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12314 if (ICE.isInvalid()) 12315 return ICE; 12316 BitWidth = ICE.get(); 12317 12318 if (Value != 0 && ZeroWidth) 12319 *ZeroWidth = false; 12320 12321 // Zero-width bitfield is ok for anonymous field. 12322 if (Value == 0 && FieldName) 12323 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12324 12325 if (Value.isSigned() && Value.isNegative()) { 12326 if (FieldName) 12327 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12328 << FieldName << Value.toString(10); 12329 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12330 << Value.toString(10); 12331 } 12332 12333 if (!FieldTy->isDependentType()) { 12334 uint64_t TypeSize = Context.getTypeSize(FieldTy); 12335 if (Value.getZExtValue() > TypeSize) { 12336 if (!getLangOpts().CPlusPlus || IsMsStruct || 12337 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12338 if (FieldName) 12339 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 12340 << FieldName << (unsigned)Value.getZExtValue() 12341 << (unsigned)TypeSize; 12342 12343 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 12344 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12345 } 12346 12347 if (FieldName) 12348 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 12349 << FieldName << (unsigned)Value.getZExtValue() 12350 << (unsigned)TypeSize; 12351 else 12352 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 12353 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12354 } 12355 } 12356 12357 return BitWidth; 12358 } 12359 12360 /// ActOnField - Each field of a C struct/union is passed into this in order 12361 /// to create a FieldDecl object for it. 12362 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 12363 Declarator &D, Expr *BitfieldWidth) { 12364 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 12365 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 12366 /*InitStyle=*/ICIS_NoInit, AS_public); 12367 return Res; 12368 } 12369 12370 /// HandleField - Analyze a field of a C struct or a C++ data member. 12371 /// 12372 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 12373 SourceLocation DeclStart, 12374 Declarator &D, Expr *BitWidth, 12375 InClassInitStyle InitStyle, 12376 AccessSpecifier AS) { 12377 IdentifierInfo *II = D.getIdentifier(); 12378 SourceLocation Loc = DeclStart; 12379 if (II) Loc = D.getIdentifierLoc(); 12380 12381 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12382 QualType T = TInfo->getType(); 12383 if (getLangOpts().CPlusPlus) { 12384 CheckExtraCXXDefaultArguments(D); 12385 12386 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12387 UPPC_DataMemberType)) { 12388 D.setInvalidType(); 12389 T = Context.IntTy; 12390 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12391 } 12392 } 12393 12394 // TR 18037 does not allow fields to be declared with address spaces. 12395 if (T.getQualifiers().hasAddressSpace()) { 12396 Diag(Loc, diag::err_field_with_address_space); 12397 D.setInvalidType(); 12398 } 12399 12400 // OpenCL 1.2 spec, s6.9 r: 12401 // The event type cannot be used to declare a structure or union field. 12402 if (LangOpts.OpenCL && T->isEventT()) { 12403 Diag(Loc, diag::err_event_t_struct_field); 12404 D.setInvalidType(); 12405 } 12406 12407 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12408 12409 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12410 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12411 diag::err_invalid_thread) 12412 << DeclSpec::getSpecifierName(TSCS); 12413 12414 // Check to see if this name was declared as a member previously 12415 NamedDecl *PrevDecl = nullptr; 12416 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12417 LookupName(Previous, S); 12418 switch (Previous.getResultKind()) { 12419 case LookupResult::Found: 12420 case LookupResult::FoundUnresolvedValue: 12421 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12422 break; 12423 12424 case LookupResult::FoundOverloaded: 12425 PrevDecl = Previous.getRepresentativeDecl(); 12426 break; 12427 12428 case LookupResult::NotFound: 12429 case LookupResult::NotFoundInCurrentInstantiation: 12430 case LookupResult::Ambiguous: 12431 break; 12432 } 12433 Previous.suppressDiagnostics(); 12434 12435 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12436 // Maybe we will complain about the shadowed template parameter. 12437 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12438 // Just pretend that we didn't see the previous declaration. 12439 PrevDecl = nullptr; 12440 } 12441 12442 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12443 PrevDecl = nullptr; 12444 12445 bool Mutable 12446 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 12447 SourceLocation TSSL = D.getLocStart(); 12448 FieldDecl *NewFD 12449 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 12450 TSSL, AS, PrevDecl, &D); 12451 12452 if (NewFD->isInvalidDecl()) 12453 Record->setInvalidDecl(); 12454 12455 if (D.getDeclSpec().isModulePrivateSpecified()) 12456 NewFD->setModulePrivate(); 12457 12458 if (NewFD->isInvalidDecl() && PrevDecl) { 12459 // Don't introduce NewFD into scope; there's already something 12460 // with the same name in the same scope. 12461 } else if (II) { 12462 PushOnScopeChains(NewFD, S); 12463 } else 12464 Record->addDecl(NewFD); 12465 12466 return NewFD; 12467 } 12468 12469 /// \brief Build a new FieldDecl and check its well-formedness. 12470 /// 12471 /// This routine builds a new FieldDecl given the fields name, type, 12472 /// record, etc. \p PrevDecl should refer to any previous declaration 12473 /// with the same name and in the same scope as the field to be 12474 /// created. 12475 /// 12476 /// \returns a new FieldDecl. 12477 /// 12478 /// \todo The Declarator argument is a hack. It will be removed once 12479 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 12480 TypeSourceInfo *TInfo, 12481 RecordDecl *Record, SourceLocation Loc, 12482 bool Mutable, Expr *BitWidth, 12483 InClassInitStyle InitStyle, 12484 SourceLocation TSSL, 12485 AccessSpecifier AS, NamedDecl *PrevDecl, 12486 Declarator *D) { 12487 IdentifierInfo *II = Name.getAsIdentifierInfo(); 12488 bool InvalidDecl = false; 12489 if (D) InvalidDecl = D->isInvalidType(); 12490 12491 // If we receive a broken type, recover by assuming 'int' and 12492 // marking this declaration as invalid. 12493 if (T.isNull()) { 12494 InvalidDecl = true; 12495 T = Context.IntTy; 12496 } 12497 12498 QualType EltTy = Context.getBaseElementType(T); 12499 if (!EltTy->isDependentType()) { 12500 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 12501 // Fields of incomplete type force their record to be invalid. 12502 Record->setInvalidDecl(); 12503 InvalidDecl = true; 12504 } else { 12505 NamedDecl *Def; 12506 EltTy->isIncompleteType(&Def); 12507 if (Def && Def->isInvalidDecl()) { 12508 Record->setInvalidDecl(); 12509 InvalidDecl = true; 12510 } 12511 } 12512 } 12513 12514 // OpenCL v1.2 s6.9.c: bitfields are not supported. 12515 if (BitWidth && getLangOpts().OpenCL) { 12516 Diag(Loc, diag::err_opencl_bitfields); 12517 InvalidDecl = true; 12518 } 12519 12520 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12521 // than a variably modified type. 12522 if (!InvalidDecl && T->isVariablyModifiedType()) { 12523 bool SizeIsNegative; 12524 llvm::APSInt Oversized; 12525 12526 TypeSourceInfo *FixedTInfo = 12527 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 12528 SizeIsNegative, 12529 Oversized); 12530 if (FixedTInfo) { 12531 Diag(Loc, diag::warn_illegal_constant_array_size); 12532 TInfo = FixedTInfo; 12533 T = FixedTInfo->getType(); 12534 } else { 12535 if (SizeIsNegative) 12536 Diag(Loc, diag::err_typecheck_negative_array_size); 12537 else if (Oversized.getBoolValue()) 12538 Diag(Loc, diag::err_array_too_large) 12539 << Oversized.toString(10); 12540 else 12541 Diag(Loc, diag::err_typecheck_field_variable_size); 12542 InvalidDecl = true; 12543 } 12544 } 12545 12546 // Fields can not have abstract class types 12547 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 12548 diag::err_abstract_type_in_decl, 12549 AbstractFieldType)) 12550 InvalidDecl = true; 12551 12552 bool ZeroWidth = false; 12553 if (InvalidDecl) 12554 BitWidth = nullptr; 12555 // If this is declared as a bit-field, check the bit-field. 12556 if (BitWidth) { 12557 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 12558 &ZeroWidth).get(); 12559 if (!BitWidth) { 12560 InvalidDecl = true; 12561 BitWidth = nullptr; 12562 ZeroWidth = false; 12563 } 12564 } 12565 12566 // Check that 'mutable' is consistent with the type of the declaration. 12567 if (!InvalidDecl && Mutable) { 12568 unsigned DiagID = 0; 12569 if (T->isReferenceType()) 12570 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 12571 : diag::err_mutable_reference; 12572 else if (T.isConstQualified()) 12573 DiagID = diag::err_mutable_const; 12574 12575 if (DiagID) { 12576 SourceLocation ErrLoc = Loc; 12577 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 12578 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 12579 Diag(ErrLoc, DiagID); 12580 if (DiagID != diag::ext_mutable_reference) { 12581 Mutable = false; 12582 InvalidDecl = true; 12583 } 12584 } 12585 } 12586 12587 // C++11 [class.union]p8 (DR1460): 12588 // At most one variant member of a union may have a 12589 // brace-or-equal-initializer. 12590 if (InitStyle != ICIS_NoInit) 12591 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 12592 12593 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 12594 BitWidth, Mutable, InitStyle); 12595 if (InvalidDecl) 12596 NewFD->setInvalidDecl(); 12597 12598 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 12599 Diag(Loc, diag::err_duplicate_member) << II; 12600 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12601 NewFD->setInvalidDecl(); 12602 } 12603 12604 if (!InvalidDecl && getLangOpts().CPlusPlus) { 12605 if (Record->isUnion()) { 12606 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12607 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12608 if (RDecl->getDefinition()) { 12609 // C++ [class.union]p1: An object of a class with a non-trivial 12610 // constructor, a non-trivial copy constructor, a non-trivial 12611 // destructor, or a non-trivial copy assignment operator 12612 // cannot be a member of a union, nor can an array of such 12613 // objects. 12614 if (CheckNontrivialField(NewFD)) 12615 NewFD->setInvalidDecl(); 12616 } 12617 } 12618 12619 // C++ [class.union]p1: If a union contains a member of reference type, 12620 // the program is ill-formed, except when compiling with MSVC extensions 12621 // enabled. 12622 if (EltTy->isReferenceType()) { 12623 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 12624 diag::ext_union_member_of_reference_type : 12625 diag::err_union_member_of_reference_type) 12626 << NewFD->getDeclName() << EltTy; 12627 if (!getLangOpts().MicrosoftExt) 12628 NewFD->setInvalidDecl(); 12629 } 12630 } 12631 } 12632 12633 // FIXME: We need to pass in the attributes given an AST 12634 // representation, not a parser representation. 12635 if (D) { 12636 // FIXME: The current scope is almost... but not entirely... correct here. 12637 ProcessDeclAttributes(getCurScope(), NewFD, *D); 12638 12639 if (NewFD->hasAttrs()) 12640 CheckAlignasUnderalignment(NewFD); 12641 } 12642 12643 // In auto-retain/release, infer strong retension for fields of 12644 // retainable type. 12645 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 12646 NewFD->setInvalidDecl(); 12647 12648 if (T.isObjCGCWeak()) 12649 Diag(Loc, diag::warn_attribute_weak_on_field); 12650 12651 NewFD->setAccess(AS); 12652 return NewFD; 12653 } 12654 12655 bool Sema::CheckNontrivialField(FieldDecl *FD) { 12656 assert(FD); 12657 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 12658 12659 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 12660 return false; 12661 12662 QualType EltTy = Context.getBaseElementType(FD->getType()); 12663 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12664 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12665 if (RDecl->getDefinition()) { 12666 // We check for copy constructors before constructors 12667 // because otherwise we'll never get complaints about 12668 // copy constructors. 12669 12670 CXXSpecialMember member = CXXInvalid; 12671 // We're required to check for any non-trivial constructors. Since the 12672 // implicit default constructor is suppressed if there are any 12673 // user-declared constructors, we just need to check that there is a 12674 // trivial default constructor and a trivial copy constructor. (We don't 12675 // worry about move constructors here, since this is a C++98 check.) 12676 if (RDecl->hasNonTrivialCopyConstructor()) 12677 member = CXXCopyConstructor; 12678 else if (!RDecl->hasTrivialDefaultConstructor()) 12679 member = CXXDefaultConstructor; 12680 else if (RDecl->hasNonTrivialCopyAssignment()) 12681 member = CXXCopyAssignment; 12682 else if (RDecl->hasNonTrivialDestructor()) 12683 member = CXXDestructor; 12684 12685 if (member != CXXInvalid) { 12686 if (!getLangOpts().CPlusPlus11 && 12687 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 12688 // Objective-C++ ARC: it is an error to have a non-trivial field of 12689 // a union. However, system headers in Objective-C programs 12690 // occasionally have Objective-C lifetime objects within unions, 12691 // and rather than cause the program to fail, we make those 12692 // members unavailable. 12693 SourceLocation Loc = FD->getLocation(); 12694 if (getSourceManager().isInSystemHeader(Loc)) { 12695 if (!FD->hasAttr<UnavailableAttr>()) 12696 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12697 "this system field has retaining ownership", 12698 Loc)); 12699 return false; 12700 } 12701 } 12702 12703 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 12704 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 12705 diag::err_illegal_union_or_anon_struct_member) 12706 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 12707 DiagnoseNontrivial(RDecl, member); 12708 return !getLangOpts().CPlusPlus11; 12709 } 12710 } 12711 } 12712 12713 return false; 12714 } 12715 12716 /// TranslateIvarVisibility - Translate visibility from a token ID to an 12717 /// AST enum value. 12718 static ObjCIvarDecl::AccessControl 12719 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 12720 switch (ivarVisibility) { 12721 default: llvm_unreachable("Unknown visitibility kind"); 12722 case tok::objc_private: return ObjCIvarDecl::Private; 12723 case tok::objc_public: return ObjCIvarDecl::Public; 12724 case tok::objc_protected: return ObjCIvarDecl::Protected; 12725 case tok::objc_package: return ObjCIvarDecl::Package; 12726 } 12727 } 12728 12729 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 12730 /// in order to create an IvarDecl object for it. 12731 Decl *Sema::ActOnIvar(Scope *S, 12732 SourceLocation DeclStart, 12733 Declarator &D, Expr *BitfieldWidth, 12734 tok::ObjCKeywordKind Visibility) { 12735 12736 IdentifierInfo *II = D.getIdentifier(); 12737 Expr *BitWidth = (Expr*)BitfieldWidth; 12738 SourceLocation Loc = DeclStart; 12739 if (II) Loc = D.getIdentifierLoc(); 12740 12741 // FIXME: Unnamed fields can be handled in various different ways, for 12742 // example, unnamed unions inject all members into the struct namespace! 12743 12744 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12745 QualType T = TInfo->getType(); 12746 12747 if (BitWidth) { 12748 // 6.7.2.1p3, 6.7.2.1p4 12749 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 12750 if (!BitWidth) 12751 D.setInvalidType(); 12752 } else { 12753 // Not a bitfield. 12754 12755 // validate II. 12756 12757 } 12758 if (T->isReferenceType()) { 12759 Diag(Loc, diag::err_ivar_reference_type); 12760 D.setInvalidType(); 12761 } 12762 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12763 // than a variably modified type. 12764 else if (T->isVariablyModifiedType()) { 12765 Diag(Loc, diag::err_typecheck_ivar_variable_size); 12766 D.setInvalidType(); 12767 } 12768 12769 // Get the visibility (access control) for this ivar. 12770 ObjCIvarDecl::AccessControl ac = 12771 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 12772 : ObjCIvarDecl::None; 12773 // Must set ivar's DeclContext to its enclosing interface. 12774 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 12775 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 12776 return nullptr; 12777 ObjCContainerDecl *EnclosingContext; 12778 if (ObjCImplementationDecl *IMPDecl = 12779 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12780 if (LangOpts.ObjCRuntime.isFragile()) { 12781 // Case of ivar declared in an implementation. Context is that of its class. 12782 EnclosingContext = IMPDecl->getClassInterface(); 12783 assert(EnclosingContext && "Implementation has no class interface!"); 12784 } 12785 else 12786 EnclosingContext = EnclosingDecl; 12787 } else { 12788 if (ObjCCategoryDecl *CDecl = 12789 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12790 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12791 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12792 return nullptr; 12793 } 12794 } 12795 EnclosingContext = EnclosingDecl; 12796 } 12797 12798 // Construct the decl. 12799 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12800 DeclStart, Loc, II, T, 12801 TInfo, ac, (Expr *)BitfieldWidth); 12802 12803 if (II) { 12804 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12805 ForRedeclaration); 12806 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12807 && !isa<TagDecl>(PrevDecl)) { 12808 Diag(Loc, diag::err_duplicate_member) << II; 12809 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12810 NewID->setInvalidDecl(); 12811 } 12812 } 12813 12814 // Process attributes attached to the ivar. 12815 ProcessDeclAttributes(S, NewID, D); 12816 12817 if (D.isInvalidType()) 12818 NewID->setInvalidDecl(); 12819 12820 // In ARC, infer 'retaining' for ivars of retainable type. 12821 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12822 NewID->setInvalidDecl(); 12823 12824 if (D.getDeclSpec().isModulePrivateSpecified()) 12825 NewID->setModulePrivate(); 12826 12827 if (II) { 12828 // FIXME: When interfaces are DeclContexts, we'll need to add 12829 // these to the interface. 12830 S->AddDecl(NewID); 12831 IdResolver.AddDecl(NewID); 12832 } 12833 12834 if (LangOpts.ObjCRuntime.isNonFragile() && 12835 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12836 Diag(Loc, diag::warn_ivars_in_interface); 12837 12838 return NewID; 12839 } 12840 12841 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12842 /// class and class extensions. For every class \@interface and class 12843 /// extension \@interface, if the last ivar is a bitfield of any type, 12844 /// then add an implicit `char :0` ivar to the end of that interface. 12845 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12846 SmallVectorImpl<Decl *> &AllIvarDecls) { 12847 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12848 return; 12849 12850 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12851 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12852 12853 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12854 return; 12855 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12856 if (!ID) { 12857 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12858 if (!CD->IsClassExtension()) 12859 return; 12860 } 12861 // No need to add this to end of @implementation. 12862 else 12863 return; 12864 } 12865 // All conditions are met. Add a new bitfield to the tail end of ivars. 12866 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12867 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12868 12869 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12870 DeclLoc, DeclLoc, nullptr, 12871 Context.CharTy, 12872 Context.getTrivialTypeSourceInfo(Context.CharTy, 12873 DeclLoc), 12874 ObjCIvarDecl::Private, BW, 12875 true); 12876 AllIvarDecls.push_back(Ivar); 12877 } 12878 12879 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12880 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12881 SourceLocation RBrac, AttributeList *Attr) { 12882 assert(EnclosingDecl && "missing record or interface decl"); 12883 12884 // If this is an Objective-C @implementation or category and we have 12885 // new fields here we should reset the layout of the interface since 12886 // it will now change. 12887 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12888 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12889 switch (DC->getKind()) { 12890 default: break; 12891 case Decl::ObjCCategory: 12892 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12893 break; 12894 case Decl::ObjCImplementation: 12895 Context. 12896 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12897 break; 12898 } 12899 } 12900 12901 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12902 12903 // Start counting up the number of named members; make sure to include 12904 // members of anonymous structs and unions in the total. 12905 unsigned NumNamedMembers = 0; 12906 if (Record) { 12907 for (const auto *I : Record->decls()) { 12908 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12909 if (IFD->getDeclName()) 12910 ++NumNamedMembers; 12911 } 12912 } 12913 12914 // Verify that all the fields are okay. 12915 SmallVector<FieldDecl*, 32> RecFields; 12916 12917 bool ARCErrReported = false; 12918 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12919 i != end; ++i) { 12920 FieldDecl *FD = cast<FieldDecl>(*i); 12921 12922 // Get the type for the field. 12923 const Type *FDTy = FD->getType().getTypePtr(); 12924 12925 if (!FD->isAnonymousStructOrUnion()) { 12926 // Remember all fields written by the user. 12927 RecFields.push_back(FD); 12928 } 12929 12930 // If the field is already invalid for some reason, don't emit more 12931 // diagnostics about it. 12932 if (FD->isInvalidDecl()) { 12933 EnclosingDecl->setInvalidDecl(); 12934 continue; 12935 } 12936 12937 // C99 6.7.2.1p2: 12938 // A structure or union shall not contain a member with 12939 // incomplete or function type (hence, a structure shall not 12940 // contain an instance of itself, but may contain a pointer to 12941 // an instance of itself), except that the last member of a 12942 // structure with more than one named member may have incomplete 12943 // array type; such a structure (and any union containing, 12944 // possibly recursively, a member that is such a structure) 12945 // shall not be a member of a structure or an element of an 12946 // array. 12947 if (FDTy->isFunctionType()) { 12948 // Field declared as a function. 12949 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12950 << FD->getDeclName(); 12951 FD->setInvalidDecl(); 12952 EnclosingDecl->setInvalidDecl(); 12953 continue; 12954 } else if (FDTy->isIncompleteArrayType() && Record && 12955 ((i + 1 == Fields.end() && !Record->isUnion()) || 12956 ((getLangOpts().MicrosoftExt || 12957 getLangOpts().CPlusPlus) && 12958 (i + 1 == Fields.end() || Record->isUnion())))) { 12959 // Flexible array member. 12960 // Microsoft and g++ is more permissive regarding flexible array. 12961 // It will accept flexible array in union and also 12962 // as the sole element of a struct/class. 12963 unsigned DiagID = 0; 12964 if (Record->isUnion()) 12965 DiagID = getLangOpts().MicrosoftExt 12966 ? diag::ext_flexible_array_union_ms 12967 : getLangOpts().CPlusPlus 12968 ? diag::ext_flexible_array_union_gnu 12969 : diag::err_flexible_array_union; 12970 else if (Fields.size() == 1) 12971 DiagID = getLangOpts().MicrosoftExt 12972 ? diag::ext_flexible_array_empty_aggregate_ms 12973 : getLangOpts().CPlusPlus 12974 ? diag::ext_flexible_array_empty_aggregate_gnu 12975 : NumNamedMembers < 1 12976 ? diag::err_flexible_array_empty_aggregate 12977 : 0; 12978 12979 if (DiagID) 12980 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12981 << Record->getTagKind(); 12982 // While the layout of types that contain virtual bases is not specified 12983 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12984 // virtual bases after the derived members. This would make a flexible 12985 // array member declared at the end of an object not adjacent to the end 12986 // of the type. 12987 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12988 if (RD->getNumVBases() != 0) 12989 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12990 << FD->getDeclName() << Record->getTagKind(); 12991 if (!getLangOpts().C99) 12992 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12993 << FD->getDeclName() << Record->getTagKind(); 12994 12995 // If the element type has a non-trivial destructor, we would not 12996 // implicitly destroy the elements, so disallow it for now. 12997 // 12998 // FIXME: GCC allows this. We should probably either implicitly delete 12999 // the destructor of the containing class, or just allow this. 13000 QualType BaseElem = Context.getBaseElementType(FD->getType()); 13001 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 13002 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 13003 << FD->getDeclName() << FD->getType(); 13004 FD->setInvalidDecl(); 13005 EnclosingDecl->setInvalidDecl(); 13006 continue; 13007 } 13008 // Okay, we have a legal flexible array member at the end of the struct. 13009 Record->setHasFlexibleArrayMember(true); 13010 } else if (!FDTy->isDependentType() && 13011 RequireCompleteType(FD->getLocation(), FD->getType(), 13012 diag::err_field_incomplete)) { 13013 // Incomplete type 13014 FD->setInvalidDecl(); 13015 EnclosingDecl->setInvalidDecl(); 13016 continue; 13017 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 13018 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 13019 // A type which contains a flexible array member is considered to be a 13020 // flexible array member. 13021 Record->setHasFlexibleArrayMember(true); 13022 if (!Record->isUnion()) { 13023 // If this is a struct/class and this is not the last element, reject 13024 // it. Note that GCC supports variable sized arrays in the middle of 13025 // structures. 13026 if (i + 1 != Fields.end()) 13027 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 13028 << FD->getDeclName() << FD->getType(); 13029 else { 13030 // We support flexible arrays at the end of structs in 13031 // other structs as an extension. 13032 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 13033 << FD->getDeclName(); 13034 } 13035 } 13036 } 13037 if (isa<ObjCContainerDecl>(EnclosingDecl) && 13038 RequireNonAbstractType(FD->getLocation(), FD->getType(), 13039 diag::err_abstract_type_in_decl, 13040 AbstractIvarType)) { 13041 // Ivars can not have abstract class types 13042 FD->setInvalidDecl(); 13043 } 13044 if (Record && FDTTy->getDecl()->hasObjectMember()) 13045 Record->setHasObjectMember(true); 13046 if (Record && FDTTy->getDecl()->hasVolatileMember()) 13047 Record->setHasVolatileMember(true); 13048 } else if (FDTy->isObjCObjectType()) { 13049 /// A field cannot be an Objective-c object 13050 Diag(FD->getLocation(), diag::err_statically_allocated_object) 13051 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 13052 QualType T = Context.getObjCObjectPointerType(FD->getType()); 13053 FD->setType(T); 13054 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 13055 (!getLangOpts().CPlusPlus || Record->isUnion())) { 13056 // It's an error in ARC if a field has lifetime. 13057 // We don't want to report this in a system header, though, 13058 // so we just make the field unavailable. 13059 // FIXME: that's really not sufficient; we need to make the type 13060 // itself invalid to, say, initialize or copy. 13061 QualType T = FD->getType(); 13062 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 13063 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 13064 SourceLocation loc = FD->getLocation(); 13065 if (getSourceManager().isInSystemHeader(loc)) { 13066 if (!FD->hasAttr<UnavailableAttr>()) { 13067 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 13068 "this system field has retaining ownership", 13069 loc)); 13070 } 13071 } else { 13072 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 13073 << T->isBlockPointerType() << Record->getTagKind(); 13074 } 13075 ARCErrReported = true; 13076 } 13077 } else if (getLangOpts().ObjC1 && 13078 getLangOpts().getGC() != LangOptions::NonGC && 13079 Record && !Record->hasObjectMember()) { 13080 if (FD->getType()->isObjCObjectPointerType() || 13081 FD->getType().isObjCGCStrong()) 13082 Record->setHasObjectMember(true); 13083 else if (Context.getAsArrayType(FD->getType())) { 13084 QualType BaseType = Context.getBaseElementType(FD->getType()); 13085 if (BaseType->isRecordType() && 13086 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 13087 Record->setHasObjectMember(true); 13088 else if (BaseType->isObjCObjectPointerType() || 13089 BaseType.isObjCGCStrong()) 13090 Record->setHasObjectMember(true); 13091 } 13092 } 13093 if (Record && FD->getType().isVolatileQualified()) 13094 Record->setHasVolatileMember(true); 13095 // Keep track of the number of named members. 13096 if (FD->getIdentifier()) 13097 ++NumNamedMembers; 13098 } 13099 13100 // Okay, we successfully defined 'Record'. 13101 if (Record) { 13102 bool Completed = false; 13103 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 13104 if (!CXXRecord->isInvalidDecl()) { 13105 // Set access bits correctly on the directly-declared conversions. 13106 for (CXXRecordDecl::conversion_iterator 13107 I = CXXRecord->conversion_begin(), 13108 E = CXXRecord->conversion_end(); I != E; ++I) 13109 I.setAccess((*I)->getAccess()); 13110 13111 if (!CXXRecord->isDependentType()) { 13112 if (CXXRecord->hasUserDeclaredDestructor()) { 13113 // Adjust user-defined destructor exception spec. 13114 if (getLangOpts().CPlusPlus11) 13115 AdjustDestructorExceptionSpec(CXXRecord, 13116 CXXRecord->getDestructor()); 13117 } 13118 13119 // Add any implicitly-declared members to this class. 13120 AddImplicitlyDeclaredMembersToClass(CXXRecord); 13121 13122 // If we have virtual base classes, we may end up finding multiple 13123 // final overriders for a given virtual function. Check for this 13124 // problem now. 13125 if (CXXRecord->getNumVBases()) { 13126 CXXFinalOverriderMap FinalOverriders; 13127 CXXRecord->getFinalOverriders(FinalOverriders); 13128 13129 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 13130 MEnd = FinalOverriders.end(); 13131 M != MEnd; ++M) { 13132 for (OverridingMethods::iterator SO = M->second.begin(), 13133 SOEnd = M->second.end(); 13134 SO != SOEnd; ++SO) { 13135 assert(SO->second.size() > 0 && 13136 "Virtual function without overridding functions?"); 13137 if (SO->second.size() == 1) 13138 continue; 13139 13140 // C++ [class.virtual]p2: 13141 // In a derived class, if a virtual member function of a base 13142 // class subobject has more than one final overrider the 13143 // program is ill-formed. 13144 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 13145 << (const NamedDecl *)M->first << Record; 13146 Diag(M->first->getLocation(), 13147 diag::note_overridden_virtual_function); 13148 for (OverridingMethods::overriding_iterator 13149 OM = SO->second.begin(), 13150 OMEnd = SO->second.end(); 13151 OM != OMEnd; ++OM) 13152 Diag(OM->Method->getLocation(), diag::note_final_overrider) 13153 << (const NamedDecl *)M->first << OM->Method->getParent(); 13154 13155 Record->setInvalidDecl(); 13156 } 13157 } 13158 CXXRecord->completeDefinition(&FinalOverriders); 13159 Completed = true; 13160 } 13161 } 13162 } 13163 } 13164 13165 if (!Completed) 13166 Record->completeDefinition(); 13167 13168 if (Record->hasAttrs()) { 13169 CheckAlignasUnderalignment(Record); 13170 13171 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 13172 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 13173 IA->getRange(), IA->getBestCase(), 13174 IA->getSemanticSpelling()); 13175 } 13176 13177 // Check if the structure/union declaration is a type that can have zero 13178 // size in C. For C this is a language extension, for C++ it may cause 13179 // compatibility problems. 13180 bool CheckForZeroSize; 13181 if (!getLangOpts().CPlusPlus) { 13182 CheckForZeroSize = true; 13183 } else { 13184 // For C++ filter out types that cannot be referenced in C code. 13185 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 13186 CheckForZeroSize = 13187 CXXRecord->getLexicalDeclContext()->isExternCContext() && 13188 !CXXRecord->isDependentType() && 13189 CXXRecord->isCLike(); 13190 } 13191 if (CheckForZeroSize) { 13192 bool ZeroSize = true; 13193 bool IsEmpty = true; 13194 unsigned NonBitFields = 0; 13195 for (RecordDecl::field_iterator I = Record->field_begin(), 13196 E = Record->field_end(); 13197 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 13198 IsEmpty = false; 13199 if (I->isUnnamedBitfield()) { 13200 if (I->getBitWidthValue(Context) > 0) 13201 ZeroSize = false; 13202 } else { 13203 ++NonBitFields; 13204 QualType FieldType = I->getType(); 13205 if (FieldType->isIncompleteType() || 13206 !Context.getTypeSizeInChars(FieldType).isZero()) 13207 ZeroSize = false; 13208 } 13209 } 13210 13211 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 13212 // allowed in C++, but warn if its declaration is inside 13213 // extern "C" block. 13214 if (ZeroSize) { 13215 Diag(RecLoc, getLangOpts().CPlusPlus ? 13216 diag::warn_zero_size_struct_union_in_extern_c : 13217 diag::warn_zero_size_struct_union_compat) 13218 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 13219 } 13220 13221 // Structs without named members are extension in C (C99 6.7.2.1p7), 13222 // but are accepted by GCC. 13223 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 13224 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 13225 diag::ext_no_named_members_in_struct_union) 13226 << Record->isUnion(); 13227 } 13228 } 13229 } else { 13230 ObjCIvarDecl **ClsFields = 13231 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 13232 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 13233 ID->setEndOfDefinitionLoc(RBrac); 13234 // Add ivar's to class's DeclContext. 13235 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13236 ClsFields[i]->setLexicalDeclContext(ID); 13237 ID->addDecl(ClsFields[i]); 13238 } 13239 // Must enforce the rule that ivars in the base classes may not be 13240 // duplicates. 13241 if (ID->getSuperClass()) 13242 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 13243 } else if (ObjCImplementationDecl *IMPDecl = 13244 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13245 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 13246 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 13247 // Ivar declared in @implementation never belongs to the implementation. 13248 // Only it is in implementation's lexical context. 13249 ClsFields[I]->setLexicalDeclContext(IMPDecl); 13250 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 13251 IMPDecl->setIvarLBraceLoc(LBrac); 13252 IMPDecl->setIvarRBraceLoc(RBrac); 13253 } else if (ObjCCategoryDecl *CDecl = 13254 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13255 // case of ivars in class extension; all other cases have been 13256 // reported as errors elsewhere. 13257 // FIXME. Class extension does not have a LocEnd field. 13258 // CDecl->setLocEnd(RBrac); 13259 // Add ivar's to class extension's DeclContext. 13260 // Diagnose redeclaration of private ivars. 13261 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 13262 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13263 if (IDecl) { 13264 if (const ObjCIvarDecl *ClsIvar = 13265 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 13266 Diag(ClsFields[i]->getLocation(), 13267 diag::err_duplicate_ivar_declaration); 13268 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 13269 continue; 13270 } 13271 for (const auto *Ext : IDecl->known_extensions()) { 13272 if (const ObjCIvarDecl *ClsExtIvar 13273 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 13274 Diag(ClsFields[i]->getLocation(), 13275 diag::err_duplicate_ivar_declaration); 13276 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 13277 continue; 13278 } 13279 } 13280 } 13281 ClsFields[i]->setLexicalDeclContext(CDecl); 13282 CDecl->addDecl(ClsFields[i]); 13283 } 13284 CDecl->setIvarLBraceLoc(LBrac); 13285 CDecl->setIvarRBraceLoc(RBrac); 13286 } 13287 } 13288 13289 if (Attr) 13290 ProcessDeclAttributeList(S, Record, Attr); 13291 } 13292 13293 /// \brief Determine whether the given integral value is representable within 13294 /// the given type T. 13295 static bool isRepresentableIntegerValue(ASTContext &Context, 13296 llvm::APSInt &Value, 13297 QualType T) { 13298 assert(T->isIntegralType(Context) && "Integral type required!"); 13299 unsigned BitWidth = Context.getIntWidth(T); 13300 13301 if (Value.isUnsigned() || Value.isNonNegative()) { 13302 if (T->isSignedIntegerOrEnumerationType()) 13303 --BitWidth; 13304 return Value.getActiveBits() <= BitWidth; 13305 } 13306 return Value.getMinSignedBits() <= BitWidth; 13307 } 13308 13309 // \brief Given an integral type, return the next larger integral type 13310 // (or a NULL type of no such type exists). 13311 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13312 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13313 // enum checking below. 13314 assert(T->isIntegralType(Context) && "Integral type required!"); 13315 const unsigned NumTypes = 4; 13316 QualType SignedIntegralTypes[NumTypes] = { 13317 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13318 }; 13319 QualType UnsignedIntegralTypes[NumTypes] = { 13320 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13321 Context.UnsignedLongLongTy 13322 }; 13323 13324 unsigned BitWidth = Context.getTypeSize(T); 13325 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13326 : UnsignedIntegralTypes; 13327 for (unsigned I = 0; I != NumTypes; ++I) 13328 if (Context.getTypeSize(Types[I]) > BitWidth) 13329 return Types[I]; 13330 13331 return QualType(); 13332 } 13333 13334 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13335 EnumConstantDecl *LastEnumConst, 13336 SourceLocation IdLoc, 13337 IdentifierInfo *Id, 13338 Expr *Val) { 13339 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13340 llvm::APSInt EnumVal(IntWidth); 13341 QualType EltTy; 13342 13343 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13344 Val = nullptr; 13345 13346 if (Val) 13347 Val = DefaultLvalueConversion(Val).get(); 13348 13349 if (Val) { 13350 if (Enum->isDependentType() || Val->isTypeDependent()) 13351 EltTy = Context.DependentTy; 13352 else { 13353 SourceLocation ExpLoc; 13354 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 13355 !getLangOpts().MSVCCompat) { 13356 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 13357 // constant-expression in the enumerator-definition shall be a converted 13358 // constant expression of the underlying type. 13359 EltTy = Enum->getIntegerType(); 13360 ExprResult Converted = 13361 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 13362 CCEK_Enumerator); 13363 if (Converted.isInvalid()) 13364 Val = nullptr; 13365 else 13366 Val = Converted.get(); 13367 } else if (!Val->isValueDependent() && 13368 !(Val = VerifyIntegerConstantExpression(Val, 13369 &EnumVal).get())) { 13370 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 13371 } else { 13372 if (Enum->isFixed()) { 13373 EltTy = Enum->getIntegerType(); 13374 13375 // In Obj-C and Microsoft mode, require the enumeration value to be 13376 // representable in the underlying type of the enumeration. In C++11, 13377 // we perform a non-narrowing conversion as part of converted constant 13378 // expression checking. 13379 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13380 if (getLangOpts().MSVCCompat) { 13381 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 13382 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13383 } else 13384 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 13385 } else 13386 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13387 } else if (getLangOpts().CPlusPlus) { 13388 // C++11 [dcl.enum]p5: 13389 // If the underlying type is not fixed, the type of each enumerator 13390 // is the type of its initializing value: 13391 // - If an initializer is specified for an enumerator, the 13392 // initializing value has the same type as the expression. 13393 EltTy = Val->getType(); 13394 } else { 13395 // C99 6.7.2.2p2: 13396 // The expression that defines the value of an enumeration constant 13397 // shall be an integer constant expression that has a value 13398 // representable as an int. 13399 13400 // Complain if the value is not representable in an int. 13401 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 13402 Diag(IdLoc, diag::ext_enum_value_not_int) 13403 << EnumVal.toString(10) << Val->getSourceRange() 13404 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 13405 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 13406 // Force the type of the expression to 'int'. 13407 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 13408 } 13409 EltTy = Val->getType(); 13410 } 13411 } 13412 } 13413 } 13414 13415 if (!Val) { 13416 if (Enum->isDependentType()) 13417 EltTy = Context.DependentTy; 13418 else if (!LastEnumConst) { 13419 // C++0x [dcl.enum]p5: 13420 // If the underlying type is not fixed, the type of each enumerator 13421 // is the type of its initializing value: 13422 // - If no initializer is specified for the first enumerator, the 13423 // initializing value has an unspecified integral type. 13424 // 13425 // GCC uses 'int' for its unspecified integral type, as does 13426 // C99 6.7.2.2p3. 13427 if (Enum->isFixed()) { 13428 EltTy = Enum->getIntegerType(); 13429 } 13430 else { 13431 EltTy = Context.IntTy; 13432 } 13433 } else { 13434 // Assign the last value + 1. 13435 EnumVal = LastEnumConst->getInitVal(); 13436 ++EnumVal; 13437 EltTy = LastEnumConst->getType(); 13438 13439 // Check for overflow on increment. 13440 if (EnumVal < LastEnumConst->getInitVal()) { 13441 // C++0x [dcl.enum]p5: 13442 // If the underlying type is not fixed, the type of each enumerator 13443 // is the type of its initializing value: 13444 // 13445 // - Otherwise the type of the initializing value is the same as 13446 // the type of the initializing value of the preceding enumerator 13447 // unless the incremented value is not representable in that type, 13448 // in which case the type is an unspecified integral type 13449 // sufficient to contain the incremented value. If no such type 13450 // exists, the program is ill-formed. 13451 QualType T = getNextLargerIntegralType(Context, EltTy); 13452 if (T.isNull() || Enum->isFixed()) { 13453 // There is no integral type larger enough to represent this 13454 // value. Complain, then allow the value to wrap around. 13455 EnumVal = LastEnumConst->getInitVal(); 13456 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 13457 ++EnumVal; 13458 if (Enum->isFixed()) 13459 // When the underlying type is fixed, this is ill-formed. 13460 Diag(IdLoc, diag::err_enumerator_wrapped) 13461 << EnumVal.toString(10) 13462 << EltTy; 13463 else 13464 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 13465 << EnumVal.toString(10); 13466 } else { 13467 EltTy = T; 13468 } 13469 13470 // Retrieve the last enumerator's value, extent that type to the 13471 // type that is supposed to be large enough to represent the incremented 13472 // value, then increment. 13473 EnumVal = LastEnumConst->getInitVal(); 13474 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13475 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 13476 ++EnumVal; 13477 13478 // If we're not in C++, diagnose the overflow of enumerator values, 13479 // which in C99 means that the enumerator value is not representable in 13480 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 13481 // permits enumerator values that are representable in some larger 13482 // integral type. 13483 if (!getLangOpts().CPlusPlus && !T.isNull()) 13484 Diag(IdLoc, diag::warn_enum_value_overflow); 13485 } else if (!getLangOpts().CPlusPlus && 13486 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13487 // Enforce C99 6.7.2.2p2 even when we compute the next value. 13488 Diag(IdLoc, diag::ext_enum_value_not_int) 13489 << EnumVal.toString(10) << 1; 13490 } 13491 } 13492 } 13493 13494 if (!EltTy->isDependentType()) { 13495 // Make the enumerator value match the signedness and size of the 13496 // enumerator's type. 13497 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 13498 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13499 } 13500 13501 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 13502 Val, EnumVal); 13503 } 13504 13505 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 13506 SourceLocation IILoc) { 13507 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 13508 !getLangOpts().CPlusPlus) 13509 return SkipBodyInfo(); 13510 13511 // We have an anonymous enum definition. Look up the first enumerator to 13512 // determine if we should merge the definition with an existing one and 13513 // skip the body. 13514 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 13515 ForRedeclaration); 13516 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 13517 NamedDecl *Hidden; 13518 if (PrevECD && 13519 !hasVisibleDefinition(cast<NamedDecl>(PrevECD->getDeclContext()), 13520 &Hidden)) { 13521 SkipBodyInfo Skip; 13522 Skip.ShouldSkip = true; 13523 Skip.Previous = Hidden; 13524 return Skip; 13525 } 13526 13527 return SkipBodyInfo(); 13528 } 13529 13530 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 13531 SourceLocation IdLoc, IdentifierInfo *Id, 13532 AttributeList *Attr, 13533 SourceLocation EqualLoc, Expr *Val) { 13534 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 13535 EnumConstantDecl *LastEnumConst = 13536 cast_or_null<EnumConstantDecl>(lastEnumConst); 13537 13538 // The scope passed in may not be a decl scope. Zip up the scope tree until 13539 // we find one that is. 13540 S = getNonFieldDeclScope(S); 13541 13542 // Verify that there isn't already something declared with this name in this 13543 // scope. 13544 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 13545 ForRedeclaration); 13546 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13547 // Maybe we will complain about the shadowed template parameter. 13548 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 13549 // Just pretend that we didn't see the previous declaration. 13550 PrevDecl = nullptr; 13551 } 13552 13553 if (PrevDecl) { 13554 // When in C++, we may get a TagDecl with the same name; in this case the 13555 // enum constant will 'hide' the tag. 13556 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 13557 "Received TagDecl when not in C++!"); 13558 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 13559 if (isa<EnumConstantDecl>(PrevDecl)) 13560 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 13561 else 13562 Diag(IdLoc, diag::err_redefinition) << Id; 13563 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13564 return nullptr; 13565 } 13566 } 13567 13568 // C++ [class.mem]p15: 13569 // If T is the name of a class, then each of the following shall have a name 13570 // different from T: 13571 // - every enumerator of every member of class T that is an unscoped 13572 // enumerated type 13573 if (CXXRecordDecl *Record 13574 = dyn_cast<CXXRecordDecl>( 13575 TheEnumDecl->getDeclContext()->getRedeclContext())) 13576 if (!TheEnumDecl->isScoped() && 13577 Record->getIdentifier() && Record->getIdentifier() == Id) 13578 Diag(IdLoc, diag::err_member_name_of_class) << Id; 13579 13580 EnumConstantDecl *New = 13581 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 13582 13583 if (New) { 13584 // Process attributes. 13585 if (Attr) ProcessDeclAttributeList(S, New, Attr); 13586 13587 // Register this decl in the current scope stack. 13588 New->setAccess(TheEnumDecl->getAccess()); 13589 PushOnScopeChains(New, S); 13590 } 13591 13592 ActOnDocumentableDecl(New); 13593 13594 return New; 13595 } 13596 13597 // Returns true when the enum initial expression does not trigger the 13598 // duplicate enum warning. A few common cases are exempted as follows: 13599 // Element2 = Element1 13600 // Element2 = Element1 + 1 13601 // Element2 = Element1 - 1 13602 // Where Element2 and Element1 are from the same enum. 13603 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 13604 Expr *InitExpr = ECD->getInitExpr(); 13605 if (!InitExpr) 13606 return true; 13607 InitExpr = InitExpr->IgnoreImpCasts(); 13608 13609 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 13610 if (!BO->isAdditiveOp()) 13611 return true; 13612 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 13613 if (!IL) 13614 return true; 13615 if (IL->getValue() != 1) 13616 return true; 13617 13618 InitExpr = BO->getLHS(); 13619 } 13620 13621 // This checks if the elements are from the same enum. 13622 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 13623 if (!DRE) 13624 return true; 13625 13626 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 13627 if (!EnumConstant) 13628 return true; 13629 13630 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 13631 Enum) 13632 return true; 13633 13634 return false; 13635 } 13636 13637 struct DupKey { 13638 int64_t val; 13639 bool isTombstoneOrEmptyKey; 13640 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 13641 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 13642 }; 13643 13644 static DupKey GetDupKey(const llvm::APSInt& Val) { 13645 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 13646 false); 13647 } 13648 13649 struct DenseMapInfoDupKey { 13650 static DupKey getEmptyKey() { return DupKey(0, true); } 13651 static DupKey getTombstoneKey() { return DupKey(1, true); } 13652 static unsigned getHashValue(const DupKey Key) { 13653 return (unsigned)(Key.val * 37); 13654 } 13655 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 13656 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 13657 LHS.val == RHS.val; 13658 } 13659 }; 13660 13661 // Emits a warning when an element is implicitly set a value that 13662 // a previous element has already been set to. 13663 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 13664 EnumDecl *Enum, 13665 QualType EnumType) { 13666 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 13667 return; 13668 // Avoid anonymous enums 13669 if (!Enum->getIdentifier()) 13670 return; 13671 13672 // Only check for small enums. 13673 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 13674 return; 13675 13676 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 13677 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 13678 13679 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 13680 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 13681 ValueToVectorMap; 13682 13683 DuplicatesVector DupVector; 13684 ValueToVectorMap EnumMap; 13685 13686 // Populate the EnumMap with all values represented by enum constants without 13687 // an initialier. 13688 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13689 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13690 13691 // Null EnumConstantDecl means a previous diagnostic has been emitted for 13692 // this constant. Skip this enum since it may be ill-formed. 13693 if (!ECD) { 13694 return; 13695 } 13696 13697 if (ECD->getInitExpr()) 13698 continue; 13699 13700 DupKey Key = GetDupKey(ECD->getInitVal()); 13701 DeclOrVector &Entry = EnumMap[Key]; 13702 13703 // First time encountering this value. 13704 if (Entry.isNull()) 13705 Entry = ECD; 13706 } 13707 13708 // Create vectors for any values that has duplicates. 13709 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13710 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 13711 if (!ValidDuplicateEnum(ECD, Enum)) 13712 continue; 13713 13714 DupKey Key = GetDupKey(ECD->getInitVal()); 13715 13716 DeclOrVector& Entry = EnumMap[Key]; 13717 if (Entry.isNull()) 13718 continue; 13719 13720 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 13721 // Ensure constants are different. 13722 if (D == ECD) 13723 continue; 13724 13725 // Create new vector and push values onto it. 13726 ECDVector *Vec = new ECDVector(); 13727 Vec->push_back(D); 13728 Vec->push_back(ECD); 13729 13730 // Update entry to point to the duplicates vector. 13731 Entry = Vec; 13732 13733 // Store the vector somewhere we can consult later for quick emission of 13734 // diagnostics. 13735 DupVector.push_back(Vec); 13736 continue; 13737 } 13738 13739 ECDVector *Vec = Entry.get<ECDVector*>(); 13740 // Make sure constants are not added more than once. 13741 if (*Vec->begin() == ECD) 13742 continue; 13743 13744 Vec->push_back(ECD); 13745 } 13746 13747 // Emit diagnostics. 13748 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 13749 DupVectorEnd = DupVector.end(); 13750 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 13751 ECDVector *Vec = *DupVectorIter; 13752 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 13753 13754 // Emit warning for one enum constant. 13755 ECDVector::iterator I = Vec->begin(); 13756 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 13757 << (*I)->getName() << (*I)->getInitVal().toString(10) 13758 << (*I)->getSourceRange(); 13759 ++I; 13760 13761 // Emit one note for each of the remaining enum constants with 13762 // the same value. 13763 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 13764 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 13765 << (*I)->getName() << (*I)->getInitVal().toString(10) 13766 << (*I)->getSourceRange(); 13767 delete Vec; 13768 } 13769 } 13770 13771 bool 13772 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 13773 bool AllowMask) const { 13774 FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>(); 13775 assert(FEAttr && "looking for value in non-flag enum"); 13776 13777 llvm::APInt FlagMask = ~FEAttr->getFlagBits(); 13778 unsigned Width = FlagMask.getBitWidth(); 13779 13780 // We will try a zero-extended value for the regular check first. 13781 llvm::APInt ExtVal = Val.zextOrSelf(Width); 13782 13783 // A value is in a flag enum if either its bits are a subset of the enum's 13784 // flag bits (the first condition) or we are allowing masks and the same is 13785 // true of its complement (the second condition). When masks are allowed, we 13786 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 13787 // 13788 // While it's true that any value could be used as a mask, the assumption is 13789 // that a mask will have all of the insignificant bits set. Anything else is 13790 // likely a logic error. 13791 if (!(FlagMask & ExtVal)) 13792 return true; 13793 13794 if (AllowMask) { 13795 // Try a one-extended value instead. This can happen if the enum is wider 13796 // than the constant used, in C with extensions to allow for wider enums. 13797 // The mask will still have the correct behaviour, so we give the user the 13798 // benefit of the doubt. 13799 // 13800 // FIXME: This heuristic can cause weird results if the enum was extended 13801 // to a larger type and is signed, because then bit-masks of smaller types 13802 // that get extended will fall out of range (e.g. ~0x1u). We currently don't 13803 // detect that case and will get a false positive for it. In most cases, 13804 // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may 13805 // be fine just to accept this as a warning. 13806 ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth()); 13807 if (!(FlagMask & ~ExtVal)) 13808 return true; 13809 } 13810 13811 return false; 13812 } 13813 13814 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 13815 SourceLocation RBraceLoc, Decl *EnumDeclX, 13816 ArrayRef<Decl *> Elements, 13817 Scope *S, AttributeList *Attr) { 13818 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 13819 QualType EnumType = Context.getTypeDeclType(Enum); 13820 13821 if (Attr) 13822 ProcessDeclAttributeList(S, Enum, Attr); 13823 13824 if (Enum->isDependentType()) { 13825 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13826 EnumConstantDecl *ECD = 13827 cast_or_null<EnumConstantDecl>(Elements[i]); 13828 if (!ECD) continue; 13829 13830 ECD->setType(EnumType); 13831 } 13832 13833 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 13834 return; 13835 } 13836 13837 // TODO: If the result value doesn't fit in an int, it must be a long or long 13838 // long value. ISO C does not support this, but GCC does as an extension, 13839 // emit a warning. 13840 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13841 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 13842 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 13843 13844 // Verify that all the values are okay, compute the size of the values, and 13845 // reverse the list. 13846 unsigned NumNegativeBits = 0; 13847 unsigned NumPositiveBits = 0; 13848 13849 // Keep track of whether all elements have type int. 13850 bool AllElementsInt = true; 13851 13852 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13853 EnumConstantDecl *ECD = 13854 cast_or_null<EnumConstantDecl>(Elements[i]); 13855 if (!ECD) continue; // Already issued a diagnostic. 13856 13857 const llvm::APSInt &InitVal = ECD->getInitVal(); 13858 13859 // Keep track of the size of positive and negative values. 13860 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13861 NumPositiveBits = std::max(NumPositiveBits, 13862 (unsigned)InitVal.getActiveBits()); 13863 else 13864 NumNegativeBits = std::max(NumNegativeBits, 13865 (unsigned)InitVal.getMinSignedBits()); 13866 13867 // Keep track of whether every enum element has type int (very commmon). 13868 if (AllElementsInt) 13869 AllElementsInt = ECD->getType() == Context.IntTy; 13870 } 13871 13872 // Figure out the type that should be used for this enum. 13873 QualType BestType; 13874 unsigned BestWidth; 13875 13876 // C++0x N3000 [conv.prom]p3: 13877 // An rvalue of an unscoped enumeration type whose underlying 13878 // type is not fixed can be converted to an rvalue of the first 13879 // of the following types that can represent all the values of 13880 // the enumeration: int, unsigned int, long int, unsigned long 13881 // int, long long int, or unsigned long long int. 13882 // C99 6.4.4.3p2: 13883 // An identifier declared as an enumeration constant has type int. 13884 // The C99 rule is modified by a gcc extension 13885 QualType BestPromotionType; 13886 13887 bool Packed = Enum->hasAttr<PackedAttr>(); 13888 // -fshort-enums is the equivalent to specifying the packed attribute on all 13889 // enum definitions. 13890 if (LangOpts.ShortEnums) 13891 Packed = true; 13892 13893 if (Enum->isFixed()) { 13894 BestType = Enum->getIntegerType(); 13895 if (BestType->isPromotableIntegerType()) 13896 BestPromotionType = Context.getPromotedIntegerType(BestType); 13897 else 13898 BestPromotionType = BestType; 13899 13900 BestWidth = Context.getIntWidth(BestType); 13901 } 13902 else if (NumNegativeBits) { 13903 // If there is a negative value, figure out the smallest integer type (of 13904 // int/long/longlong) that fits. 13905 // If it's packed, check also if it fits a char or a short. 13906 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13907 BestType = Context.SignedCharTy; 13908 BestWidth = CharWidth; 13909 } else if (Packed && NumNegativeBits <= ShortWidth && 13910 NumPositiveBits < ShortWidth) { 13911 BestType = Context.ShortTy; 13912 BestWidth = ShortWidth; 13913 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13914 BestType = Context.IntTy; 13915 BestWidth = IntWidth; 13916 } else { 13917 BestWidth = Context.getTargetInfo().getLongWidth(); 13918 13919 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13920 BestType = Context.LongTy; 13921 } else { 13922 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13923 13924 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13925 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13926 BestType = Context.LongLongTy; 13927 } 13928 } 13929 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13930 } else { 13931 // If there is no negative value, figure out the smallest type that fits 13932 // all of the enumerator values. 13933 // If it's packed, check also if it fits a char or a short. 13934 if (Packed && NumPositiveBits <= CharWidth) { 13935 BestType = Context.UnsignedCharTy; 13936 BestPromotionType = Context.IntTy; 13937 BestWidth = CharWidth; 13938 } else if (Packed && NumPositiveBits <= ShortWidth) { 13939 BestType = Context.UnsignedShortTy; 13940 BestPromotionType = Context.IntTy; 13941 BestWidth = ShortWidth; 13942 } else if (NumPositiveBits <= IntWidth) { 13943 BestType = Context.UnsignedIntTy; 13944 BestWidth = IntWidth; 13945 BestPromotionType 13946 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13947 ? Context.UnsignedIntTy : Context.IntTy; 13948 } else if (NumPositiveBits <= 13949 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13950 BestType = Context.UnsignedLongTy; 13951 BestPromotionType 13952 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13953 ? Context.UnsignedLongTy : Context.LongTy; 13954 } else { 13955 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13956 assert(NumPositiveBits <= BestWidth && 13957 "How could an initializer get larger than ULL?"); 13958 BestType = Context.UnsignedLongLongTy; 13959 BestPromotionType 13960 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13961 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13962 } 13963 } 13964 13965 FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>(); 13966 if (FEAttr) 13967 FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0); 13968 13969 // Loop over all of the enumerator constants, changing their types to match 13970 // the type of the enum if needed. If we have a flag type, we also prepare the 13971 // FlagBits cache. 13972 for (auto *D : Elements) { 13973 auto *ECD = cast_or_null<EnumConstantDecl>(D); 13974 if (!ECD) continue; // Already issued a diagnostic. 13975 13976 // Standard C says the enumerators have int type, but we allow, as an 13977 // extension, the enumerators to be larger than int size. If each 13978 // enumerator value fits in an int, type it as an int, otherwise type it the 13979 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13980 // that X has type 'int', not 'unsigned'. 13981 13982 // Determine whether the value fits into an int. 13983 llvm::APSInt InitVal = ECD->getInitVal(); 13984 13985 // If it fits into an integer type, force it. Otherwise force it to match 13986 // the enum decl type. 13987 QualType NewTy; 13988 unsigned NewWidth; 13989 bool NewSign; 13990 if (!getLangOpts().CPlusPlus && 13991 !Enum->isFixed() && 13992 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13993 NewTy = Context.IntTy; 13994 NewWidth = IntWidth; 13995 NewSign = true; 13996 } else if (ECD->getType() == BestType) { 13997 // Already the right type! 13998 if (getLangOpts().CPlusPlus) 13999 // C++ [dcl.enum]p4: Following the closing brace of an 14000 // enum-specifier, each enumerator has the type of its 14001 // enumeration. 14002 ECD->setType(EnumType); 14003 goto flagbits; 14004 } else { 14005 NewTy = BestType; 14006 NewWidth = BestWidth; 14007 NewSign = BestType->isSignedIntegerOrEnumerationType(); 14008 } 14009 14010 // Adjust the APSInt value. 14011 InitVal = InitVal.extOrTrunc(NewWidth); 14012 InitVal.setIsSigned(NewSign); 14013 ECD->setInitVal(InitVal); 14014 14015 // Adjust the Expr initializer and type. 14016 if (ECD->getInitExpr() && 14017 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 14018 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 14019 CK_IntegralCast, 14020 ECD->getInitExpr(), 14021 /*base paths*/ nullptr, 14022 VK_RValue)); 14023 if (getLangOpts().CPlusPlus) 14024 // C++ [dcl.enum]p4: Following the closing brace of an 14025 // enum-specifier, each enumerator has the type of its 14026 // enumeration. 14027 ECD->setType(EnumType); 14028 else 14029 ECD->setType(NewTy); 14030 14031 flagbits: 14032 // Check to see if we have a constant with exactly one bit set. Note that x 14033 // & (x - 1) will be nonzero if and only if x has more than one bit set. 14034 if (FEAttr) { 14035 llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth); 14036 if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) { 14037 FEAttr->getFlagBits() |= ExtVal; 14038 } 14039 } 14040 } 14041 14042 if (FEAttr) { 14043 for (Decl *D : Elements) { 14044 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 14045 if (!ECD) continue; // Already issued a diagnostic. 14046 14047 llvm::APSInt InitVal = ECD->getInitVal(); 14048 if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true)) 14049 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 14050 << ECD << Enum; 14051 } 14052 } 14053 14054 14055 14056 Enum->completeDefinition(BestType, BestPromotionType, 14057 NumPositiveBits, NumNegativeBits); 14058 14059 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 14060 14061 // Now that the enum type is defined, ensure it's not been underaligned. 14062 if (Enum->hasAttrs()) 14063 CheckAlignasUnderalignment(Enum); 14064 } 14065 14066 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 14067 SourceLocation StartLoc, 14068 SourceLocation EndLoc) { 14069 StringLiteral *AsmString = cast<StringLiteral>(expr); 14070 14071 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 14072 AsmString, StartLoc, 14073 EndLoc); 14074 CurContext->addDecl(New); 14075 return New; 14076 } 14077 14078 static void checkModuleImportContext(Sema &S, Module *M, 14079 SourceLocation ImportLoc, 14080 DeclContext *DC) { 14081 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 14082 switch (LSD->getLanguage()) { 14083 case LinkageSpecDecl::lang_c: 14084 if (!M->IsExternC) { 14085 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 14086 << M->getFullModuleName(); 14087 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 14088 return; 14089 } 14090 break; 14091 case LinkageSpecDecl::lang_cxx: 14092 break; 14093 } 14094 DC = LSD->getParent(); 14095 } 14096 14097 while (isa<LinkageSpecDecl>(DC)) 14098 DC = DC->getParent(); 14099 if (!isa<TranslationUnitDecl>(DC)) { 14100 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 14101 << M->getFullModuleName() << DC; 14102 S.Diag(cast<Decl>(DC)->getLocStart(), 14103 diag::note_module_import_not_at_top_level) 14104 << DC; 14105 } 14106 } 14107 14108 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 14109 SourceLocation ImportLoc, 14110 ModuleIdPath Path) { 14111 Module *Mod = 14112 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 14113 /*IsIncludeDirective=*/false); 14114 if (!Mod) 14115 return true; 14116 14117 VisibleModules.setVisible(Mod, ImportLoc); 14118 14119 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 14120 14121 // FIXME: we should support importing a submodule within a different submodule 14122 // of the same top-level module. Until we do, make it an error rather than 14123 // silently ignoring the import. 14124 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 14125 Diag(ImportLoc, diag::err_module_self_import) 14126 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 14127 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule) 14128 Diag(ImportLoc, diag::err_module_import_in_implementation) 14129 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule; 14130 14131 SmallVector<SourceLocation, 2> IdentifierLocs; 14132 Module *ModCheck = Mod; 14133 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 14134 // If we've run out of module parents, just drop the remaining identifiers. 14135 // We need the length to be consistent. 14136 if (!ModCheck) 14137 break; 14138 ModCheck = ModCheck->Parent; 14139 14140 IdentifierLocs.push_back(Path[I].second); 14141 } 14142 14143 ImportDecl *Import = ImportDecl::Create(Context, 14144 Context.getTranslationUnitDecl(), 14145 AtLoc.isValid()? AtLoc : ImportLoc, 14146 Mod, IdentifierLocs); 14147 Context.getTranslationUnitDecl()->addDecl(Import); 14148 return Import; 14149 } 14150 14151 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 14152 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14153 14154 // Determine whether we're in the #include buffer for a module. The #includes 14155 // in that buffer do not qualify as module imports; they're just an 14156 // implementation detail of us building the module. 14157 // 14158 // FIXME: Should we even get ActOnModuleInclude calls for those? 14159 bool IsInModuleIncludes = 14160 TUKind == TU_Module && 14161 getSourceManager().isWrittenInMainFile(DirectiveLoc); 14162 14163 // If this module import was due to an inclusion directive, create an 14164 // implicit import declaration to capture it in the AST. 14165 if (!IsInModuleIncludes) { 14166 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14167 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14168 DirectiveLoc, Mod, 14169 DirectiveLoc); 14170 TU->addDecl(ImportD); 14171 Consumer.HandleImplicitImportDecl(ImportD); 14172 } 14173 14174 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 14175 VisibleModules.setVisible(Mod, DirectiveLoc); 14176 } 14177 14178 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 14179 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14180 14181 if (getLangOpts().ModulesLocalVisibility) 14182 VisibleModulesStack.push_back(std::move(VisibleModules)); 14183 VisibleModules.setVisible(Mod, DirectiveLoc); 14184 } 14185 14186 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) { 14187 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14188 14189 if (getLangOpts().ModulesLocalVisibility) { 14190 VisibleModules = std::move(VisibleModulesStack.back()); 14191 VisibleModulesStack.pop_back(); 14192 VisibleModules.setVisible(Mod, DirectiveLoc); 14193 } 14194 } 14195 14196 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 14197 Module *Mod) { 14198 // Bail if we're not allowed to implicitly import a module here. 14199 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 14200 return; 14201 14202 // Create the implicit import declaration. 14203 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14204 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14205 Loc, Mod, Loc); 14206 TU->addDecl(ImportD); 14207 Consumer.HandleImplicitImportDecl(ImportD); 14208 14209 // Make the module visible. 14210 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 14211 VisibleModules.setVisible(Mod, Loc); 14212 } 14213 14214 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 14215 IdentifierInfo* AliasName, 14216 SourceLocation PragmaLoc, 14217 SourceLocation NameLoc, 14218 SourceLocation AliasNameLoc) { 14219 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 14220 LookupOrdinaryName); 14221 AsmLabelAttr *Attr = 14222 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 14223 14224 // If a declaration that: 14225 // 1) declares a function or a variable 14226 // 2) has external linkage 14227 // already exists, add a label attribute to it. 14228 if (PrevDecl && 14229 (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)) && 14230 PrevDecl->hasExternalFormalLinkage()) 14231 PrevDecl->addAttr(Attr); 14232 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 14233 else 14234 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 14235 } 14236 14237 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 14238 SourceLocation PragmaLoc, 14239 SourceLocation NameLoc) { 14240 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 14241 14242 if (PrevDecl) { 14243 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 14244 } else { 14245 (void)WeakUndeclaredIdentifiers.insert( 14246 std::pair<IdentifierInfo*,WeakInfo> 14247 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 14248 } 14249 } 14250 14251 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 14252 IdentifierInfo* AliasName, 14253 SourceLocation PragmaLoc, 14254 SourceLocation NameLoc, 14255 SourceLocation AliasNameLoc) { 14256 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 14257 LookupOrdinaryName); 14258 WeakInfo W = WeakInfo(Name, NameLoc); 14259 14260 if (PrevDecl) { 14261 if (!PrevDecl->hasAttr<AliasAttr>()) 14262 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 14263 DeclApplyPragmaWeak(TUScope, ND, W); 14264 } else { 14265 (void)WeakUndeclaredIdentifiers.insert( 14266 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 14267 } 14268 } 14269 14270 Decl *Sema::getObjCDeclContext() const { 14271 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 14272 } 14273 14274 AvailabilityResult Sema::getCurContextAvailability() const { 14275 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 14276 if (!D) 14277 return AR_Available; 14278 14279 // If we are within an Objective-C method, we should consult 14280 // both the availability of the method as well as the 14281 // enclosing class. If the class is (say) deprecated, 14282 // the entire method is considered deprecated from the 14283 // purpose of checking if the current context is deprecated. 14284 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 14285 AvailabilityResult R = MD->getAvailability(); 14286 if (R != AR_Available) 14287 return R; 14288 D = MD->getClassInterface(); 14289 } 14290 // If we are within an Objective-c @implementation, it 14291 // gets the same availability context as the @interface. 14292 else if (const ObjCImplementationDecl *ID = 14293 dyn_cast<ObjCImplementationDecl>(D)) { 14294 D = ID->getClassInterface(); 14295 } 14296 // Recover from user error. 14297 return D ? D->getAvailability() : AR_Available; 14298 } 14299