1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/CommentDiagnostic.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false, 68 bool AllowTemplates=false) 69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 70 AllowClassTemplates(AllowTemplates) { 71 WantExpressionKeywords = false; 72 WantCXXNamedCasts = false; 73 WantRemainingKeywords = false; 74 } 75 76 bool ValidateCandidate(const TypoCorrection &candidate) override { 77 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND); 80 return (IsType || AllowedTemplate) && 81 (AllowInvalidDecl || !ND->isInvalidDecl()); 82 } 83 return !WantClassName && candidate.isKeyword(); 84 } 85 86 private: 87 bool AllowInvalidDecl; 88 bool WantClassName; 89 bool AllowClassTemplates; 90 }; 91 92 } // end anonymous namespace 93 94 /// \brief Determine whether the token kind starts a simple-type-specifier. 95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 96 switch (Kind) { 97 // FIXME: Take into account the current language when deciding whether a 98 // token kind is a valid type specifier 99 case tok::kw_short: 100 case tok::kw_long: 101 case tok::kw___int64: 102 case tok::kw___int128: 103 case tok::kw_signed: 104 case tok::kw_unsigned: 105 case tok::kw_void: 106 case tok::kw_char: 107 case tok::kw_int: 108 case tok::kw_half: 109 case tok::kw_float: 110 case tok::kw_double: 111 case tok::kw_wchar_t: 112 case tok::kw_bool: 113 case tok::kw___underlying_type: 114 case tok::kw___auto_type: 115 return true; 116 117 case tok::annot_typename: 118 case tok::kw_char16_t: 119 case tok::kw_char32_t: 120 case tok::kw_typeof: 121 case tok::annot_decltype: 122 case tok::kw_decltype: 123 return getLangOpts().CPlusPlus; 124 125 default: 126 break; 127 } 128 129 return false; 130 } 131 132 namespace { 133 enum class UnqualifiedTypeNameLookupResult { 134 NotFound, 135 FoundNonType, 136 FoundType 137 }; 138 } // end anonymous namespace 139 140 /// \brief Tries to perform unqualified lookup of the type decls in bases for 141 /// dependent class. 142 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 143 /// type decl, \a FoundType if only type decls are found. 144 static UnqualifiedTypeNameLookupResult 145 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 146 SourceLocation NameLoc, 147 const CXXRecordDecl *RD) { 148 if (!RD->hasDefinition()) 149 return UnqualifiedTypeNameLookupResult::NotFound; 150 // Look for type decls in base classes. 151 UnqualifiedTypeNameLookupResult FoundTypeDecl = 152 UnqualifiedTypeNameLookupResult::NotFound; 153 for (const auto &Base : RD->bases()) { 154 const CXXRecordDecl *BaseRD = nullptr; 155 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 156 BaseRD = BaseTT->getAsCXXRecordDecl(); 157 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 158 // Look for type decls in dependent base classes that have known primary 159 // templates. 160 if (!TST || !TST->isDependentType()) 161 continue; 162 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 163 if (!TD) 164 continue; 165 auto *BasePrimaryTemplate = 166 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl()); 167 if (!BasePrimaryTemplate) 168 continue; 169 BaseRD = BasePrimaryTemplate; 170 } 171 if (BaseRD) { 172 for (NamedDecl *ND : BaseRD->lookup(&II)) { 173 if (!isa<TypeDecl>(ND)) 174 return UnqualifiedTypeNameLookupResult::FoundNonType; 175 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 176 } 177 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 178 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 179 case UnqualifiedTypeNameLookupResult::FoundNonType: 180 return UnqualifiedTypeNameLookupResult::FoundNonType; 181 case UnqualifiedTypeNameLookupResult::FoundType: 182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 183 break; 184 case UnqualifiedTypeNameLookupResult::NotFound: 185 break; 186 } 187 } 188 } 189 } 190 191 return FoundTypeDecl; 192 } 193 194 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 195 const IdentifierInfo &II, 196 SourceLocation NameLoc) { 197 // Lookup in the parent class template context, if any. 198 const CXXRecordDecl *RD = nullptr; 199 UnqualifiedTypeNameLookupResult FoundTypeDecl = 200 UnqualifiedTypeNameLookupResult::NotFound; 201 for (DeclContext *DC = S.CurContext; 202 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 203 DC = DC->getParent()) { 204 // Look for type decls in dependent base classes that have known primary 205 // templates. 206 RD = dyn_cast<CXXRecordDecl>(DC); 207 if (RD && RD->getDescribedClassTemplate()) 208 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 209 } 210 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 211 return nullptr; 212 213 // We found some types in dependent base classes. Recover as if the user 214 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 215 // lookup during template instantiation. 216 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 217 218 ASTContext &Context = S.Context; 219 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 220 cast<Type>(Context.getRecordType(RD))); 221 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 222 223 CXXScopeSpec SS; 224 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 225 226 TypeLocBuilder Builder; 227 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 228 DepTL.setNameLoc(NameLoc); 229 DepTL.setElaboratedKeywordLoc(SourceLocation()); 230 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 231 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 232 } 233 234 /// \brief If the identifier refers to a type name within this scope, 235 /// return the declaration of that type. 236 /// 237 /// This routine performs ordinary name lookup of the identifier II 238 /// within the given scope, with optional C++ scope specifier SS, to 239 /// determine whether the name refers to a type. If so, returns an 240 /// opaque pointer (actually a QualType) corresponding to that 241 /// type. Otherwise, returns NULL. 242 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 243 Scope *S, CXXScopeSpec *SS, 244 bool isClassName, bool HasTrailingDot, 245 ParsedType ObjectTypePtr, 246 bool IsCtorOrDtorName, 247 bool WantNontrivialTypeSourceInfo, 248 IdentifierInfo **CorrectedII) { 249 // Determine where we will perform name lookup. 250 DeclContext *LookupCtx = nullptr; 251 if (ObjectTypePtr) { 252 QualType ObjectType = ObjectTypePtr.get(); 253 if (ObjectType->isRecordType()) 254 LookupCtx = computeDeclContext(ObjectType); 255 } else if (SS && SS->isNotEmpty()) { 256 LookupCtx = computeDeclContext(*SS, false); 257 258 if (!LookupCtx) { 259 if (isDependentScopeSpecifier(*SS)) { 260 // C++ [temp.res]p3: 261 // A qualified-id that refers to a type and in which the 262 // nested-name-specifier depends on a template-parameter (14.6.2) 263 // shall be prefixed by the keyword typename to indicate that the 264 // qualified-id denotes a type, forming an 265 // elaborated-type-specifier (7.1.5.3). 266 // 267 // We therefore do not perform any name lookup if the result would 268 // refer to a member of an unknown specialization. 269 if (!isClassName && !IsCtorOrDtorName) 270 return nullptr; 271 272 // We know from the grammar that this name refers to a type, 273 // so build a dependent node to describe the type. 274 if (WantNontrivialTypeSourceInfo) 275 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 276 277 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 278 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 279 II, NameLoc); 280 return ParsedType::make(T); 281 } 282 283 return nullptr; 284 } 285 286 if (!LookupCtx->isDependentContext() && 287 RequireCompleteDeclContext(*SS, LookupCtx)) 288 return nullptr; 289 } 290 291 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 292 // lookup for class-names. 293 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 294 LookupOrdinaryName; 295 LookupResult Result(*this, &II, NameLoc, Kind); 296 if (LookupCtx) { 297 // Perform "qualified" name lookup into the declaration context we 298 // computed, which is either the type of the base of a member access 299 // expression or the declaration context associated with a prior 300 // nested-name-specifier. 301 LookupQualifiedName(Result, LookupCtx); 302 303 if (ObjectTypePtr && Result.empty()) { 304 // C++ [basic.lookup.classref]p3: 305 // If the unqualified-id is ~type-name, the type-name is looked up 306 // in the context of the entire postfix-expression. If the type T of 307 // the object expression is of a class type C, the type-name is also 308 // looked up in the scope of class C. At least one of the lookups shall 309 // find a name that refers to (possibly cv-qualified) T. 310 LookupName(Result, S); 311 } 312 } else { 313 // Perform unqualified name lookup. 314 LookupName(Result, S); 315 316 // For unqualified lookup in a class template in MSVC mode, look into 317 // dependent base classes where the primary class template is known. 318 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 319 if (ParsedType TypeInBase = 320 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 321 return TypeInBase; 322 } 323 } 324 325 NamedDecl *IIDecl = nullptr; 326 switch (Result.getResultKind()) { 327 case LookupResult::NotFound: 328 case LookupResult::NotFoundInCurrentInstantiation: 329 if (CorrectedII) { 330 TypoCorrection Correction = CorrectTypo( 331 Result.getLookupNameInfo(), Kind, S, SS, 332 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName), 333 CTK_ErrorRecovery); 334 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 335 TemplateTy Template; 336 bool MemberOfUnknownSpecialization; 337 UnqualifiedId TemplateName; 338 TemplateName.setIdentifier(NewII, NameLoc); 339 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 340 CXXScopeSpec NewSS, *NewSSPtr = SS; 341 if (SS && NNS) { 342 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 343 NewSSPtr = &NewSS; 344 } 345 if (Correction && (NNS || NewII != &II) && 346 // Ignore a correction to a template type as the to-be-corrected 347 // identifier is not a template (typo correction for template names 348 // is handled elsewhere). 349 !(getLangOpts().CPlusPlus && NewSSPtr && 350 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 351 Template, MemberOfUnknownSpecialization))) { 352 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 353 isClassName, HasTrailingDot, ObjectTypePtr, 354 IsCtorOrDtorName, 355 WantNontrivialTypeSourceInfo); 356 if (Ty) { 357 diagnoseTypo(Correction, 358 PDiag(diag::err_unknown_type_or_class_name_suggest) 359 << Result.getLookupName() << isClassName); 360 if (SS && NNS) 361 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 362 *CorrectedII = NewII; 363 return Ty; 364 } 365 } 366 } 367 // If typo correction failed or was not performed, fall through 368 case LookupResult::FoundOverloaded: 369 case LookupResult::FoundUnresolvedValue: 370 Result.suppressDiagnostics(); 371 return nullptr; 372 373 case LookupResult::Ambiguous: 374 // Recover from type-hiding ambiguities by hiding the type. We'll 375 // do the lookup again when looking for an object, and we can 376 // diagnose the error then. If we don't do this, then the error 377 // about hiding the type will be immediately followed by an error 378 // that only makes sense if the identifier was treated like a type. 379 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 380 Result.suppressDiagnostics(); 381 return nullptr; 382 } 383 384 // Look to see if we have a type anywhere in the list of results. 385 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 386 Res != ResEnd; ++Res) { 387 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 388 if (!IIDecl || 389 (*Res)->getLocation().getRawEncoding() < 390 IIDecl->getLocation().getRawEncoding()) 391 IIDecl = *Res; 392 } 393 } 394 395 if (!IIDecl) { 396 // None of the entities we found is a type, so there is no way 397 // to even assume that the result is a type. In this case, don't 398 // complain about the ambiguity. The parser will either try to 399 // perform this lookup again (e.g., as an object name), which 400 // will produce the ambiguity, or will complain that it expected 401 // a type name. 402 Result.suppressDiagnostics(); 403 return nullptr; 404 } 405 406 // We found a type within the ambiguous lookup; diagnose the 407 // ambiguity and then return that type. This might be the right 408 // answer, or it might not be, but it suppresses any attempt to 409 // perform the name lookup again. 410 break; 411 412 case LookupResult::Found: 413 IIDecl = Result.getFoundDecl(); 414 break; 415 } 416 417 assert(IIDecl && "Didn't find decl"); 418 419 QualType T; 420 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 421 DiagnoseUseOfDecl(IIDecl, NameLoc); 422 423 T = Context.getTypeDeclType(TD); 424 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 425 426 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 427 // constructor or destructor name (in such a case, the scope specifier 428 // will be attached to the enclosing Expr or Decl node). 429 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 430 if (WantNontrivialTypeSourceInfo) { 431 // Construct a type with type-source information. 432 TypeLocBuilder Builder; 433 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 434 435 T = getElaboratedType(ETK_None, *SS, T); 436 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 437 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 438 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 439 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 440 } else { 441 T = getElaboratedType(ETK_None, *SS, T); 442 } 443 } 444 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 445 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 446 if (!HasTrailingDot) 447 T = Context.getObjCInterfaceType(IDecl); 448 } 449 450 if (T.isNull()) { 451 // If it's not plausibly a type, suppress diagnostics. 452 Result.suppressDiagnostics(); 453 return nullptr; 454 } 455 return ParsedType::make(T); 456 } 457 458 // Builds a fake NNS for the given decl context. 459 static NestedNameSpecifier * 460 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 461 for (;; DC = DC->getLookupParent()) { 462 DC = DC->getPrimaryContext(); 463 auto *ND = dyn_cast<NamespaceDecl>(DC); 464 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 465 return NestedNameSpecifier::Create(Context, nullptr, ND); 466 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 467 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 468 RD->getTypeForDecl()); 469 else if (isa<TranslationUnitDecl>(DC)) 470 return NestedNameSpecifier::GlobalSpecifier(Context); 471 } 472 llvm_unreachable("something isn't in TU scope?"); 473 } 474 475 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 476 SourceLocation NameLoc) { 477 // Accepting an undeclared identifier as a default argument for a template 478 // type parameter is a Microsoft extension. 479 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 480 481 // Build a fake DependentNameType that will perform lookup into CurContext at 482 // instantiation time. The name specifier isn't dependent, so template 483 // instantiation won't transform it. It will retry the lookup, however. 484 NestedNameSpecifier *NNS = 485 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 486 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 487 488 // Build type location information. We synthesized the qualifier, so we have 489 // to build a fake NestedNameSpecifierLoc. 490 NestedNameSpecifierLocBuilder NNSLocBuilder; 491 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 492 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 493 494 TypeLocBuilder Builder; 495 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 496 DepTL.setNameLoc(NameLoc); 497 DepTL.setElaboratedKeywordLoc(SourceLocation()); 498 DepTL.setQualifierLoc(QualifierLoc); 499 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 500 } 501 502 /// isTagName() - This method is called *for error recovery purposes only* 503 /// to determine if the specified name is a valid tag name ("struct foo"). If 504 /// so, this returns the TST for the tag corresponding to it (TST_enum, 505 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 506 /// cases in C where the user forgot to specify the tag. 507 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 508 // Do a tag name lookup in this scope. 509 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 510 LookupName(R, S, false); 511 R.suppressDiagnostics(); 512 if (R.getResultKind() == LookupResult::Found) 513 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 514 switch (TD->getTagKind()) { 515 case TTK_Struct: return DeclSpec::TST_struct; 516 case TTK_Interface: return DeclSpec::TST_interface; 517 case TTK_Union: return DeclSpec::TST_union; 518 case TTK_Class: return DeclSpec::TST_class; 519 case TTK_Enum: return DeclSpec::TST_enum; 520 } 521 } 522 523 return DeclSpec::TST_unspecified; 524 } 525 526 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 527 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 528 /// then downgrade the missing typename error to a warning. 529 /// This is needed for MSVC compatibility; Example: 530 /// @code 531 /// template<class T> class A { 532 /// public: 533 /// typedef int TYPE; 534 /// }; 535 /// template<class T> class B : public A<T> { 536 /// public: 537 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 538 /// }; 539 /// @endcode 540 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 541 if (CurContext->isRecord()) { 542 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 543 return true; 544 545 const Type *Ty = SS->getScopeRep()->getAsType(); 546 547 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 548 for (const auto &Base : RD->bases()) 549 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 550 return true; 551 return S->isFunctionPrototypeScope(); 552 } 553 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 554 } 555 556 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 557 SourceLocation IILoc, 558 Scope *S, 559 CXXScopeSpec *SS, 560 ParsedType &SuggestedType, 561 bool AllowClassTemplates) { 562 // We don't have anything to suggest (yet). 563 SuggestedType = nullptr; 564 565 // There may have been a typo in the name of the type. Look up typo 566 // results, in case we have something that we can suggest. 567 if (TypoCorrection Corrected = 568 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 569 llvm::make_unique<TypeNameValidatorCCC>( 570 false, false, AllowClassTemplates), 571 CTK_ErrorRecovery)) { 572 if (Corrected.isKeyword()) { 573 // We corrected to a keyword. 574 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 575 II = Corrected.getCorrectionAsIdentifierInfo(); 576 } else { 577 // We found a similarly-named type or interface; suggest that. 578 if (!SS || !SS->isSet()) { 579 diagnoseTypo(Corrected, 580 PDiag(diag::err_unknown_typename_suggest) << II); 581 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 582 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 583 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 584 II->getName().equals(CorrectedStr); 585 diagnoseTypo(Corrected, 586 PDiag(diag::err_unknown_nested_typename_suggest) 587 << II << DC << DroppedSpecifier << SS->getRange()); 588 } else { 589 llvm_unreachable("could not have corrected a typo here"); 590 } 591 592 CXXScopeSpec tmpSS; 593 if (Corrected.getCorrectionSpecifier()) 594 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 595 SourceRange(IILoc)); 596 SuggestedType = 597 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 598 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 599 /*IsCtorOrDtorName=*/false, 600 /*NonTrivialTypeSourceInfo=*/true); 601 } 602 return; 603 } 604 605 if (getLangOpts().CPlusPlus) { 606 // See if II is a class template that the user forgot to pass arguments to. 607 UnqualifiedId Name; 608 Name.setIdentifier(II, IILoc); 609 CXXScopeSpec EmptySS; 610 TemplateTy TemplateResult; 611 bool MemberOfUnknownSpecialization; 612 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 613 Name, nullptr, true, TemplateResult, 614 MemberOfUnknownSpecialization) == TNK_Type_template) { 615 TemplateName TplName = TemplateResult.get(); 616 Diag(IILoc, diag::err_template_missing_args) << TplName; 617 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 618 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 619 << TplDecl->getTemplateParameters()->getSourceRange(); 620 } 621 return; 622 } 623 } 624 625 // FIXME: Should we move the logic that tries to recover from a missing tag 626 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 627 628 if (!SS || (!SS->isSet() && !SS->isInvalid())) 629 Diag(IILoc, diag::err_unknown_typename) << II; 630 else if (DeclContext *DC = computeDeclContext(*SS, false)) 631 Diag(IILoc, diag::err_typename_nested_not_found) 632 << II << DC << SS->getRange(); 633 else if (isDependentScopeSpecifier(*SS)) { 634 unsigned DiagID = diag::err_typename_missing; 635 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 636 DiagID = diag::ext_typename_missing; 637 638 Diag(SS->getRange().getBegin(), DiagID) 639 << SS->getScopeRep() << II->getName() 640 << SourceRange(SS->getRange().getBegin(), IILoc) 641 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 642 SuggestedType = ActOnTypenameType(S, SourceLocation(), 643 *SS, *II, IILoc).get(); 644 } else { 645 assert(SS && SS->isInvalid() && 646 "Invalid scope specifier has already been diagnosed"); 647 } 648 } 649 650 /// \brief Determine whether the given result set contains either a type name 651 /// or 652 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 653 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 654 NextToken.is(tok::less); 655 656 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 657 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 658 return true; 659 660 if (CheckTemplate && isa<TemplateDecl>(*I)) 661 return true; 662 } 663 664 return false; 665 } 666 667 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 668 Scope *S, CXXScopeSpec &SS, 669 IdentifierInfo *&Name, 670 SourceLocation NameLoc) { 671 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 672 SemaRef.LookupParsedName(R, S, &SS); 673 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 674 StringRef FixItTagName; 675 switch (Tag->getTagKind()) { 676 case TTK_Class: 677 FixItTagName = "class "; 678 break; 679 680 case TTK_Enum: 681 FixItTagName = "enum "; 682 break; 683 684 case TTK_Struct: 685 FixItTagName = "struct "; 686 break; 687 688 case TTK_Interface: 689 FixItTagName = "__interface "; 690 break; 691 692 case TTK_Union: 693 FixItTagName = "union "; 694 break; 695 } 696 697 StringRef TagName = FixItTagName.drop_back(); 698 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 699 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 700 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 701 702 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 703 I != IEnd; ++I) 704 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 705 << Name << TagName; 706 707 // Replace lookup results with just the tag decl. 708 Result.clear(Sema::LookupTagName); 709 SemaRef.LookupParsedName(Result, S, &SS); 710 return true; 711 } 712 713 return false; 714 } 715 716 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 717 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 718 QualType T, SourceLocation NameLoc) { 719 ASTContext &Context = S.Context; 720 721 TypeLocBuilder Builder; 722 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 723 724 T = S.getElaboratedType(ETK_None, SS, T); 725 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 726 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 727 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 728 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 729 } 730 731 Sema::NameClassification 732 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 733 SourceLocation NameLoc, const Token &NextToken, 734 bool IsAddressOfOperand, 735 std::unique_ptr<CorrectionCandidateCallback> CCC) { 736 DeclarationNameInfo NameInfo(Name, NameLoc); 737 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 738 739 if (NextToken.is(tok::coloncolon)) { 740 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 741 QualType(), false, SS, nullptr, false); 742 } 743 744 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 745 LookupParsedName(Result, S, &SS, !CurMethod); 746 747 // For unqualified lookup in a class template in MSVC mode, look into 748 // dependent base classes where the primary class template is known. 749 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 750 if (ParsedType TypeInBase = 751 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 752 return TypeInBase; 753 } 754 755 // Perform lookup for Objective-C instance variables (including automatically 756 // synthesized instance variables), if we're in an Objective-C method. 757 // FIXME: This lookup really, really needs to be folded in to the normal 758 // unqualified lookup mechanism. 759 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 760 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 761 if (E.get() || E.isInvalid()) 762 return E; 763 } 764 765 bool SecondTry = false; 766 bool IsFilteredTemplateName = false; 767 768 Corrected: 769 switch (Result.getResultKind()) { 770 case LookupResult::NotFound: 771 // If an unqualified-id is followed by a '(', then we have a function 772 // call. 773 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 774 // In C++, this is an ADL-only call. 775 // FIXME: Reference? 776 if (getLangOpts().CPlusPlus) 777 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 778 779 // C90 6.3.2.2: 780 // If the expression that precedes the parenthesized argument list in a 781 // function call consists solely of an identifier, and if no 782 // declaration is visible for this identifier, the identifier is 783 // implicitly declared exactly as if, in the innermost block containing 784 // the function call, the declaration 785 // 786 // extern int identifier (); 787 // 788 // appeared. 789 // 790 // We also allow this in C99 as an extension. 791 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 792 Result.addDecl(D); 793 Result.resolveKind(); 794 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 795 } 796 } 797 798 // In C, we first see whether there is a tag type by the same name, in 799 // which case it's likely that the user just forgot to write "enum", 800 // "struct", or "union". 801 if (!getLangOpts().CPlusPlus && !SecondTry && 802 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 803 break; 804 } 805 806 // Perform typo correction to determine if there is another name that is 807 // close to this name. 808 if (!SecondTry && CCC) { 809 SecondTry = true; 810 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 811 Result.getLookupKind(), S, 812 &SS, std::move(CCC), 813 CTK_ErrorRecovery)) { 814 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 815 unsigned QualifiedDiag = diag::err_no_member_suggest; 816 817 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 818 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 819 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 820 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 821 UnqualifiedDiag = diag::err_no_template_suggest; 822 QualifiedDiag = diag::err_no_member_template_suggest; 823 } else if (UnderlyingFirstDecl && 824 (isa<TypeDecl>(UnderlyingFirstDecl) || 825 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 826 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 827 UnqualifiedDiag = diag::err_unknown_typename_suggest; 828 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 829 } 830 831 if (SS.isEmpty()) { 832 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 833 } else {// FIXME: is this even reachable? Test it. 834 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 835 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 836 Name->getName().equals(CorrectedStr); 837 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 838 << Name << computeDeclContext(SS, false) 839 << DroppedSpecifier << SS.getRange()); 840 } 841 842 // Update the name, so that the caller has the new name. 843 Name = Corrected.getCorrectionAsIdentifierInfo(); 844 845 // Typo correction corrected to a keyword. 846 if (Corrected.isKeyword()) 847 return Name; 848 849 // Also update the LookupResult... 850 // FIXME: This should probably go away at some point 851 Result.clear(); 852 Result.setLookupName(Corrected.getCorrection()); 853 if (FirstDecl) 854 Result.addDecl(FirstDecl); 855 856 // If we found an Objective-C instance variable, let 857 // LookupInObjCMethod build the appropriate expression to 858 // reference the ivar. 859 // FIXME: This is a gross hack. 860 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 861 Result.clear(); 862 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 863 return E; 864 } 865 866 goto Corrected; 867 } 868 } 869 870 // We failed to correct; just fall through and let the parser deal with it. 871 Result.suppressDiagnostics(); 872 return NameClassification::Unknown(); 873 874 case LookupResult::NotFoundInCurrentInstantiation: { 875 // We performed name lookup into the current instantiation, and there were 876 // dependent bases, so we treat this result the same way as any other 877 // dependent nested-name-specifier. 878 879 // C++ [temp.res]p2: 880 // A name used in a template declaration or definition and that is 881 // dependent on a template-parameter is assumed not to name a type 882 // unless the applicable name lookup finds a type name or the name is 883 // qualified by the keyword typename. 884 // 885 // FIXME: If the next token is '<', we might want to ask the parser to 886 // perform some heroics to see if we actually have a 887 // template-argument-list, which would indicate a missing 'template' 888 // keyword here. 889 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 890 NameInfo, IsAddressOfOperand, 891 /*TemplateArgs=*/nullptr); 892 } 893 894 case LookupResult::Found: 895 case LookupResult::FoundOverloaded: 896 case LookupResult::FoundUnresolvedValue: 897 break; 898 899 case LookupResult::Ambiguous: 900 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 901 hasAnyAcceptableTemplateNames(Result)) { 902 // C++ [temp.local]p3: 903 // A lookup that finds an injected-class-name (10.2) can result in an 904 // ambiguity in certain cases (for example, if it is found in more than 905 // one base class). If all of the injected-class-names that are found 906 // refer to specializations of the same class template, and if the name 907 // is followed by a template-argument-list, the reference refers to the 908 // class template itself and not a specialization thereof, and is not 909 // ambiguous. 910 // 911 // This filtering can make an ambiguous result into an unambiguous one, 912 // so try again after filtering out template names. 913 FilterAcceptableTemplateNames(Result); 914 if (!Result.isAmbiguous()) { 915 IsFilteredTemplateName = true; 916 break; 917 } 918 } 919 920 // Diagnose the ambiguity and return an error. 921 return NameClassification::Error(); 922 } 923 924 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 925 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 926 // C++ [temp.names]p3: 927 // After name lookup (3.4) finds that a name is a template-name or that 928 // an operator-function-id or a literal- operator-id refers to a set of 929 // overloaded functions any member of which is a function template if 930 // this is followed by a <, the < is always taken as the delimiter of a 931 // template-argument-list and never as the less-than operator. 932 if (!IsFilteredTemplateName) 933 FilterAcceptableTemplateNames(Result); 934 935 if (!Result.empty()) { 936 bool IsFunctionTemplate; 937 bool IsVarTemplate; 938 TemplateName Template; 939 if (Result.end() - Result.begin() > 1) { 940 IsFunctionTemplate = true; 941 Template = Context.getOverloadedTemplateName(Result.begin(), 942 Result.end()); 943 } else { 944 TemplateDecl *TD 945 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 946 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 947 IsVarTemplate = isa<VarTemplateDecl>(TD); 948 949 if (SS.isSet() && !SS.isInvalid()) 950 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 951 /*TemplateKeyword=*/false, 952 TD); 953 else 954 Template = TemplateName(TD); 955 } 956 957 if (IsFunctionTemplate) { 958 // Function templates always go through overload resolution, at which 959 // point we'll perform the various checks (e.g., accessibility) we need 960 // to based on which function we selected. 961 Result.suppressDiagnostics(); 962 963 return NameClassification::FunctionTemplate(Template); 964 } 965 966 return IsVarTemplate ? NameClassification::VarTemplate(Template) 967 : NameClassification::TypeTemplate(Template); 968 } 969 } 970 971 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 972 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 973 DiagnoseUseOfDecl(Type, NameLoc); 974 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 975 QualType T = Context.getTypeDeclType(Type); 976 if (SS.isNotEmpty()) 977 return buildNestedType(*this, SS, T, NameLoc); 978 return ParsedType::make(T); 979 } 980 981 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 982 if (!Class) { 983 // FIXME: It's unfortunate that we don't have a Type node for handling this. 984 if (ObjCCompatibleAliasDecl *Alias = 985 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 986 Class = Alias->getClassInterface(); 987 } 988 989 if (Class) { 990 DiagnoseUseOfDecl(Class, NameLoc); 991 992 if (NextToken.is(tok::period)) { 993 // Interface. <something> is parsed as a property reference expression. 994 // Just return "unknown" as a fall-through for now. 995 Result.suppressDiagnostics(); 996 return NameClassification::Unknown(); 997 } 998 999 QualType T = Context.getObjCInterfaceType(Class); 1000 return ParsedType::make(T); 1001 } 1002 1003 // We can have a type template here if we're classifying a template argument. 1004 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 1005 return NameClassification::TypeTemplate( 1006 TemplateName(cast<TemplateDecl>(FirstDecl))); 1007 1008 // Check for a tag type hidden by a non-type decl in a few cases where it 1009 // seems likely a type is wanted instead of the non-type that was found. 1010 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1011 if ((NextToken.is(tok::identifier) || 1012 (NextIsOp && 1013 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1014 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1015 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1016 DiagnoseUseOfDecl(Type, NameLoc); 1017 QualType T = Context.getTypeDeclType(Type); 1018 if (SS.isNotEmpty()) 1019 return buildNestedType(*this, SS, T, NameLoc); 1020 return ParsedType::make(T); 1021 } 1022 1023 if (FirstDecl->isCXXClassMember()) 1024 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1025 nullptr, S); 1026 1027 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1028 return BuildDeclarationNameExpr(SS, Result, ADL); 1029 } 1030 1031 // Determines the context to return to after temporarily entering a 1032 // context. This depends in an unnecessarily complicated way on the 1033 // exact ordering of callbacks from the parser. 1034 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1035 1036 // Functions defined inline within classes aren't parsed until we've 1037 // finished parsing the top-level class, so the top-level class is 1038 // the context we'll need to return to. 1039 // A Lambda call operator whose parent is a class must not be treated 1040 // as an inline member function. A Lambda can be used legally 1041 // either as an in-class member initializer or a default argument. These 1042 // are parsed once the class has been marked complete and so the containing 1043 // context would be the nested class (when the lambda is defined in one); 1044 // If the class is not complete, then the lambda is being used in an 1045 // ill-formed fashion (such as to specify the width of a bit-field, or 1046 // in an array-bound) - in which case we still want to return the 1047 // lexically containing DC (which could be a nested class). 1048 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1049 DC = DC->getLexicalParent(); 1050 1051 // A function not defined within a class will always return to its 1052 // lexical context. 1053 if (!isa<CXXRecordDecl>(DC)) 1054 return DC; 1055 1056 // A C++ inline method/friend is parsed *after* the topmost class 1057 // it was declared in is fully parsed ("complete"); the topmost 1058 // class is the context we need to return to. 1059 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1060 DC = RD; 1061 1062 // Return the declaration context of the topmost class the inline method is 1063 // declared in. 1064 return DC; 1065 } 1066 1067 return DC->getLexicalParent(); 1068 } 1069 1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1071 assert(getContainingDC(DC) == CurContext && 1072 "The next DeclContext should be lexically contained in the current one."); 1073 CurContext = DC; 1074 S->setEntity(DC); 1075 } 1076 1077 void Sema::PopDeclContext() { 1078 assert(CurContext && "DeclContext imbalance!"); 1079 1080 CurContext = getContainingDC(CurContext); 1081 assert(CurContext && "Popped translation unit!"); 1082 } 1083 1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1085 Decl *D) { 1086 // Unlike PushDeclContext, the context to which we return is not necessarily 1087 // the containing DC of TD, because the new context will be some pre-existing 1088 // TagDecl definition instead of a fresh one. 1089 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1090 CurContext = cast<TagDecl>(D)->getDefinition(); 1091 assert(CurContext && "skipping definition of undefined tag"); 1092 // Start lookups from the parent of the current context; we don't want to look 1093 // into the pre-existing complete definition. 1094 S->setEntity(CurContext->getLookupParent()); 1095 return Result; 1096 } 1097 1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1099 CurContext = static_cast<decltype(CurContext)>(Context); 1100 } 1101 1102 /// EnterDeclaratorContext - Used when we must lookup names in the context 1103 /// of a declarator's nested name specifier. 1104 /// 1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1106 // C++0x [basic.lookup.unqual]p13: 1107 // A name used in the definition of a static data member of class 1108 // X (after the qualified-id of the static member) is looked up as 1109 // if the name was used in a member function of X. 1110 // C++0x [basic.lookup.unqual]p14: 1111 // If a variable member of a namespace is defined outside of the 1112 // scope of its namespace then any name used in the definition of 1113 // the variable member (after the declarator-id) is looked up as 1114 // if the definition of the variable member occurred in its 1115 // namespace. 1116 // Both of these imply that we should push a scope whose context 1117 // is the semantic context of the declaration. We can't use 1118 // PushDeclContext here because that context is not necessarily 1119 // lexically contained in the current context. Fortunately, 1120 // the containing scope should have the appropriate information. 1121 1122 assert(!S->getEntity() && "scope already has entity"); 1123 1124 #ifndef NDEBUG 1125 Scope *Ancestor = S->getParent(); 1126 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1127 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1128 #endif 1129 1130 CurContext = DC; 1131 S->setEntity(DC); 1132 } 1133 1134 void Sema::ExitDeclaratorContext(Scope *S) { 1135 assert(S->getEntity() == CurContext && "Context imbalance!"); 1136 1137 // Switch back to the lexical context. The safety of this is 1138 // enforced by an assert in EnterDeclaratorContext. 1139 Scope *Ancestor = S->getParent(); 1140 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1141 CurContext = Ancestor->getEntity(); 1142 1143 // We don't need to do anything with the scope, which is going to 1144 // disappear. 1145 } 1146 1147 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1148 // We assume that the caller has already called 1149 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1150 FunctionDecl *FD = D->getAsFunction(); 1151 if (!FD) 1152 return; 1153 1154 // Same implementation as PushDeclContext, but enters the context 1155 // from the lexical parent, rather than the top-level class. 1156 assert(CurContext == FD->getLexicalParent() && 1157 "The next DeclContext should be lexically contained in the current one."); 1158 CurContext = FD; 1159 S->setEntity(CurContext); 1160 1161 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1162 ParmVarDecl *Param = FD->getParamDecl(P); 1163 // If the parameter has an identifier, then add it to the scope 1164 if (Param->getIdentifier()) { 1165 S->AddDecl(Param); 1166 IdResolver.AddDecl(Param); 1167 } 1168 } 1169 } 1170 1171 void Sema::ActOnExitFunctionContext() { 1172 // Same implementation as PopDeclContext, but returns to the lexical parent, 1173 // rather than the top-level class. 1174 assert(CurContext && "DeclContext imbalance!"); 1175 CurContext = CurContext->getLexicalParent(); 1176 assert(CurContext && "Popped translation unit!"); 1177 } 1178 1179 /// \brief Determine whether we allow overloading of the function 1180 /// PrevDecl with another declaration. 1181 /// 1182 /// This routine determines whether overloading is possible, not 1183 /// whether some new function is actually an overload. It will return 1184 /// true in C++ (where we can always provide overloads) or, as an 1185 /// extension, in C when the previous function is already an 1186 /// overloaded function declaration or has the "overloadable" 1187 /// attribute. 1188 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1189 ASTContext &Context) { 1190 if (Context.getLangOpts().CPlusPlus) 1191 return true; 1192 1193 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1194 return true; 1195 1196 return (Previous.getResultKind() == LookupResult::Found 1197 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1198 } 1199 1200 /// Add this decl to the scope shadowed decl chains. 1201 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1202 // Move up the scope chain until we find the nearest enclosing 1203 // non-transparent context. The declaration will be introduced into this 1204 // scope. 1205 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1206 S = S->getParent(); 1207 1208 // Add scoped declarations into their context, so that they can be 1209 // found later. Declarations without a context won't be inserted 1210 // into any context. 1211 if (AddToContext) 1212 CurContext->addDecl(D); 1213 1214 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1215 // are function-local declarations. 1216 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1217 !D->getDeclContext()->getRedeclContext()->Equals( 1218 D->getLexicalDeclContext()->getRedeclContext()) && 1219 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1220 return; 1221 1222 // Template instantiations should also not be pushed into scope. 1223 if (isa<FunctionDecl>(D) && 1224 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1225 return; 1226 1227 // If this replaces anything in the current scope, 1228 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1229 IEnd = IdResolver.end(); 1230 for (; I != IEnd; ++I) { 1231 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1232 S->RemoveDecl(*I); 1233 IdResolver.RemoveDecl(*I); 1234 1235 // Should only need to replace one decl. 1236 break; 1237 } 1238 } 1239 1240 S->AddDecl(D); 1241 1242 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1243 // Implicitly-generated labels may end up getting generated in an order that 1244 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1245 // the label at the appropriate place in the identifier chain. 1246 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1247 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1248 if (IDC == CurContext) { 1249 if (!S->isDeclScope(*I)) 1250 continue; 1251 } else if (IDC->Encloses(CurContext)) 1252 break; 1253 } 1254 1255 IdResolver.InsertDeclAfter(I, D); 1256 } else { 1257 IdResolver.AddDecl(D); 1258 } 1259 } 1260 1261 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1262 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1263 TUScope->AddDecl(D); 1264 } 1265 1266 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1267 bool AllowInlineNamespace) { 1268 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1269 } 1270 1271 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1272 DeclContext *TargetDC = DC->getPrimaryContext(); 1273 do { 1274 if (DeclContext *ScopeDC = S->getEntity()) 1275 if (ScopeDC->getPrimaryContext() == TargetDC) 1276 return S; 1277 } while ((S = S->getParent())); 1278 1279 return nullptr; 1280 } 1281 1282 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1283 DeclContext*, 1284 ASTContext&); 1285 1286 /// Filters out lookup results that don't fall within the given scope 1287 /// as determined by isDeclInScope. 1288 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1289 bool ConsiderLinkage, 1290 bool AllowInlineNamespace) { 1291 LookupResult::Filter F = R.makeFilter(); 1292 while (F.hasNext()) { 1293 NamedDecl *D = F.next(); 1294 1295 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1296 continue; 1297 1298 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1299 continue; 1300 1301 F.erase(); 1302 } 1303 1304 F.done(); 1305 } 1306 1307 static bool isUsingDecl(NamedDecl *D) { 1308 return isa<UsingShadowDecl>(D) || 1309 isa<UnresolvedUsingTypenameDecl>(D) || 1310 isa<UnresolvedUsingValueDecl>(D); 1311 } 1312 1313 /// Removes using shadow declarations from the lookup results. 1314 static void RemoveUsingDecls(LookupResult &R) { 1315 LookupResult::Filter F = R.makeFilter(); 1316 while (F.hasNext()) 1317 if (isUsingDecl(F.next())) 1318 F.erase(); 1319 1320 F.done(); 1321 } 1322 1323 /// \brief Check for this common pattern: 1324 /// @code 1325 /// class S { 1326 /// S(const S&); // DO NOT IMPLEMENT 1327 /// void operator=(const S&); // DO NOT IMPLEMENT 1328 /// }; 1329 /// @endcode 1330 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1331 // FIXME: Should check for private access too but access is set after we get 1332 // the decl here. 1333 if (D->doesThisDeclarationHaveABody()) 1334 return false; 1335 1336 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1337 return CD->isCopyConstructor(); 1338 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1339 return Method->isCopyAssignmentOperator(); 1340 return false; 1341 } 1342 1343 // We need this to handle 1344 // 1345 // typedef struct { 1346 // void *foo() { return 0; } 1347 // } A; 1348 // 1349 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1350 // for example. If 'A', foo will have external linkage. If we have '*A', 1351 // foo will have no linkage. Since we can't know until we get to the end 1352 // of the typedef, this function finds out if D might have non-external linkage. 1353 // Callers should verify at the end of the TU if it D has external linkage or 1354 // not. 1355 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1356 const DeclContext *DC = D->getDeclContext(); 1357 while (!DC->isTranslationUnit()) { 1358 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1359 if (!RD->hasNameForLinkage()) 1360 return true; 1361 } 1362 DC = DC->getParent(); 1363 } 1364 1365 return !D->isExternallyVisible(); 1366 } 1367 1368 // FIXME: This needs to be refactored; some other isInMainFile users want 1369 // these semantics. 1370 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1371 if (S.TUKind != TU_Complete) 1372 return false; 1373 return S.SourceMgr.isInMainFile(Loc); 1374 } 1375 1376 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1377 assert(D); 1378 1379 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1380 return false; 1381 1382 // Ignore all entities declared within templates, and out-of-line definitions 1383 // of members of class templates. 1384 if (D->getDeclContext()->isDependentContext() || 1385 D->getLexicalDeclContext()->isDependentContext()) 1386 return false; 1387 1388 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1389 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1390 return false; 1391 1392 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1393 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1394 return false; 1395 } else { 1396 // 'static inline' functions are defined in headers; don't warn. 1397 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1398 return false; 1399 } 1400 1401 if (FD->doesThisDeclarationHaveABody() && 1402 Context.DeclMustBeEmitted(FD)) 1403 return false; 1404 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1405 // Constants and utility variables are defined in headers with internal 1406 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1407 // like "inline".) 1408 if (!isMainFileLoc(*this, VD->getLocation())) 1409 return false; 1410 1411 if (Context.DeclMustBeEmitted(VD)) 1412 return false; 1413 1414 if (VD->isStaticDataMember() && 1415 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1416 return false; 1417 } else { 1418 return false; 1419 } 1420 1421 // Only warn for unused decls internal to the translation unit. 1422 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1423 // for inline functions defined in the main source file, for instance. 1424 return mightHaveNonExternalLinkage(D); 1425 } 1426 1427 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1428 if (!D) 1429 return; 1430 1431 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1432 const FunctionDecl *First = FD->getFirstDecl(); 1433 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1434 return; // First should already be in the vector. 1435 } 1436 1437 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1438 const VarDecl *First = VD->getFirstDecl(); 1439 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1440 return; // First should already be in the vector. 1441 } 1442 1443 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1444 UnusedFileScopedDecls.push_back(D); 1445 } 1446 1447 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1448 if (D->isInvalidDecl()) 1449 return false; 1450 1451 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1452 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1453 return false; 1454 1455 if (isa<LabelDecl>(D)) 1456 return true; 1457 1458 // Except for labels, we only care about unused decls that are local to 1459 // functions. 1460 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1461 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1462 // For dependent types, the diagnostic is deferred. 1463 WithinFunction = 1464 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1465 if (!WithinFunction) 1466 return false; 1467 1468 if (isa<TypedefNameDecl>(D)) 1469 return true; 1470 1471 // White-list anything that isn't a local variable. 1472 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1473 return false; 1474 1475 // Types of valid local variables should be complete, so this should succeed. 1476 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1477 1478 // White-list anything with an __attribute__((unused)) type. 1479 QualType Ty = VD->getType(); 1480 1481 // Only look at the outermost level of typedef. 1482 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1483 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1484 return false; 1485 } 1486 1487 // If we failed to complete the type for some reason, or if the type is 1488 // dependent, don't diagnose the variable. 1489 if (Ty->isIncompleteType() || Ty->isDependentType()) 1490 return false; 1491 1492 if (const TagType *TT = Ty->getAs<TagType>()) { 1493 const TagDecl *Tag = TT->getDecl(); 1494 if (Tag->hasAttr<UnusedAttr>()) 1495 return false; 1496 1497 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1498 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1499 return false; 1500 1501 if (const Expr *Init = VD->getInit()) { 1502 if (const ExprWithCleanups *Cleanups = 1503 dyn_cast<ExprWithCleanups>(Init)) 1504 Init = Cleanups->getSubExpr(); 1505 const CXXConstructExpr *Construct = 1506 dyn_cast<CXXConstructExpr>(Init); 1507 if (Construct && !Construct->isElidable()) { 1508 CXXConstructorDecl *CD = Construct->getConstructor(); 1509 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1510 return false; 1511 } 1512 } 1513 } 1514 } 1515 1516 // TODO: __attribute__((unused)) templates? 1517 } 1518 1519 return true; 1520 } 1521 1522 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1523 FixItHint &Hint) { 1524 if (isa<LabelDecl>(D)) { 1525 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1526 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1527 if (AfterColon.isInvalid()) 1528 return; 1529 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1530 getCharRange(D->getLocStart(), AfterColon)); 1531 } 1532 } 1533 1534 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1535 if (D->getTypeForDecl()->isDependentType()) 1536 return; 1537 1538 for (auto *TmpD : D->decls()) { 1539 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1540 DiagnoseUnusedDecl(T); 1541 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1542 DiagnoseUnusedNestedTypedefs(R); 1543 } 1544 } 1545 1546 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1547 /// unless they are marked attr(unused). 1548 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1549 if (!ShouldDiagnoseUnusedDecl(D)) 1550 return; 1551 1552 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1553 // typedefs can be referenced later on, so the diagnostics are emitted 1554 // at end-of-translation-unit. 1555 UnusedLocalTypedefNameCandidates.insert(TD); 1556 return; 1557 } 1558 1559 FixItHint Hint; 1560 GenerateFixForUnusedDecl(D, Context, Hint); 1561 1562 unsigned DiagID; 1563 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1564 DiagID = diag::warn_unused_exception_param; 1565 else if (isa<LabelDecl>(D)) 1566 DiagID = diag::warn_unused_label; 1567 else 1568 DiagID = diag::warn_unused_variable; 1569 1570 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1571 } 1572 1573 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1574 // Verify that we have no forward references left. If so, there was a goto 1575 // or address of a label taken, but no definition of it. Label fwd 1576 // definitions are indicated with a null substmt which is also not a resolved 1577 // MS inline assembly label name. 1578 bool Diagnose = false; 1579 if (L->isMSAsmLabel()) 1580 Diagnose = !L->isResolvedMSAsmLabel(); 1581 else 1582 Diagnose = L->getStmt() == nullptr; 1583 if (Diagnose) 1584 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1585 } 1586 1587 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1588 S->mergeNRVOIntoParent(); 1589 1590 if (S->decl_empty()) return; 1591 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1592 "Scope shouldn't contain decls!"); 1593 1594 for (auto *TmpD : S->decls()) { 1595 assert(TmpD && "This decl didn't get pushed??"); 1596 1597 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1598 NamedDecl *D = cast<NamedDecl>(TmpD); 1599 1600 if (!D->getDeclName()) continue; 1601 1602 // Diagnose unused variables in this scope. 1603 if (!S->hasUnrecoverableErrorOccurred()) { 1604 DiagnoseUnusedDecl(D); 1605 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1606 DiagnoseUnusedNestedTypedefs(RD); 1607 } 1608 1609 // If this was a forward reference to a label, verify it was defined. 1610 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1611 CheckPoppedLabel(LD, *this); 1612 1613 // Remove this name from our lexical scope. 1614 IdResolver.RemoveDecl(D); 1615 } 1616 } 1617 1618 /// \brief Look for an Objective-C class in the translation unit. 1619 /// 1620 /// \param Id The name of the Objective-C class we're looking for. If 1621 /// typo-correction fixes this name, the Id will be updated 1622 /// to the fixed name. 1623 /// 1624 /// \param IdLoc The location of the name in the translation unit. 1625 /// 1626 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1627 /// if there is no class with the given name. 1628 /// 1629 /// \returns The declaration of the named Objective-C class, or NULL if the 1630 /// class could not be found. 1631 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1632 SourceLocation IdLoc, 1633 bool DoTypoCorrection) { 1634 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1635 // creation from this context. 1636 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1637 1638 if (!IDecl && DoTypoCorrection) { 1639 // Perform typo correction at the given location, but only if we 1640 // find an Objective-C class name. 1641 if (TypoCorrection C = CorrectTypo( 1642 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1643 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1644 CTK_ErrorRecovery)) { 1645 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1646 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1647 Id = IDecl->getIdentifier(); 1648 } 1649 } 1650 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1651 // This routine must always return a class definition, if any. 1652 if (Def && Def->getDefinition()) 1653 Def = Def->getDefinition(); 1654 return Def; 1655 } 1656 1657 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1658 /// from S, where a non-field would be declared. This routine copes 1659 /// with the difference between C and C++ scoping rules in structs and 1660 /// unions. For example, the following code is well-formed in C but 1661 /// ill-formed in C++: 1662 /// @code 1663 /// struct S6 { 1664 /// enum { BAR } e; 1665 /// }; 1666 /// 1667 /// void test_S6() { 1668 /// struct S6 a; 1669 /// a.e = BAR; 1670 /// } 1671 /// @endcode 1672 /// For the declaration of BAR, this routine will return a different 1673 /// scope. The scope S will be the scope of the unnamed enumeration 1674 /// within S6. In C++, this routine will return the scope associated 1675 /// with S6, because the enumeration's scope is a transparent 1676 /// context but structures can contain non-field names. In C, this 1677 /// routine will return the translation unit scope, since the 1678 /// enumeration's scope is a transparent context and structures cannot 1679 /// contain non-field names. 1680 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1681 while (((S->getFlags() & Scope::DeclScope) == 0) || 1682 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1683 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1684 S = S->getParent(); 1685 return S; 1686 } 1687 1688 /// \brief Looks up the declaration of "struct objc_super" and 1689 /// saves it for later use in building builtin declaration of 1690 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1691 /// pre-existing declaration exists no action takes place. 1692 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1693 IdentifierInfo *II) { 1694 if (!II->isStr("objc_msgSendSuper")) 1695 return; 1696 ASTContext &Context = ThisSema.Context; 1697 1698 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1699 SourceLocation(), Sema::LookupTagName); 1700 ThisSema.LookupName(Result, S); 1701 if (Result.getResultKind() == LookupResult::Found) 1702 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1703 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1704 } 1705 1706 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1707 switch (Error) { 1708 case ASTContext::GE_None: 1709 return ""; 1710 case ASTContext::GE_Missing_stdio: 1711 return "stdio.h"; 1712 case ASTContext::GE_Missing_setjmp: 1713 return "setjmp.h"; 1714 case ASTContext::GE_Missing_ucontext: 1715 return "ucontext.h"; 1716 } 1717 llvm_unreachable("unhandled error kind"); 1718 } 1719 1720 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1721 /// file scope. lazily create a decl for it. ForRedeclaration is true 1722 /// if we're creating this built-in in anticipation of redeclaring the 1723 /// built-in. 1724 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1725 Scope *S, bool ForRedeclaration, 1726 SourceLocation Loc) { 1727 LookupPredefedObjCSuperType(*this, S, II); 1728 1729 ASTContext::GetBuiltinTypeError Error; 1730 QualType R = Context.GetBuiltinType(ID, Error); 1731 if (Error) { 1732 if (ForRedeclaration) 1733 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1734 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1735 return nullptr; 1736 } 1737 1738 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1739 Diag(Loc, diag::ext_implicit_lib_function_decl) 1740 << Context.BuiltinInfo.getName(ID) << R; 1741 if (Context.BuiltinInfo.getHeaderName(ID) && 1742 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1743 Diag(Loc, diag::note_include_header_or_declare) 1744 << Context.BuiltinInfo.getHeaderName(ID) 1745 << Context.BuiltinInfo.getName(ID); 1746 } 1747 1748 if (R.isNull()) 1749 return nullptr; 1750 1751 DeclContext *Parent = Context.getTranslationUnitDecl(); 1752 if (getLangOpts().CPlusPlus) { 1753 LinkageSpecDecl *CLinkageDecl = 1754 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1755 LinkageSpecDecl::lang_c, false); 1756 CLinkageDecl->setImplicit(); 1757 Parent->addDecl(CLinkageDecl); 1758 Parent = CLinkageDecl; 1759 } 1760 1761 FunctionDecl *New = FunctionDecl::Create(Context, 1762 Parent, 1763 Loc, Loc, II, R, /*TInfo=*/nullptr, 1764 SC_Extern, 1765 false, 1766 R->isFunctionProtoType()); 1767 New->setImplicit(); 1768 1769 // Create Decl objects for each parameter, adding them to the 1770 // FunctionDecl. 1771 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1772 SmallVector<ParmVarDecl*, 16> Params; 1773 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1774 ParmVarDecl *parm = 1775 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1776 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1777 SC_None, nullptr); 1778 parm->setScopeInfo(0, i); 1779 Params.push_back(parm); 1780 } 1781 New->setParams(Params); 1782 } 1783 1784 AddKnownFunctionAttributes(New); 1785 RegisterLocallyScopedExternCDecl(New, S); 1786 1787 // TUScope is the translation-unit scope to insert this function into. 1788 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1789 // relate Scopes to DeclContexts, and probably eliminate CurContext 1790 // entirely, but we're not there yet. 1791 DeclContext *SavedContext = CurContext; 1792 CurContext = Parent; 1793 PushOnScopeChains(New, TUScope); 1794 CurContext = SavedContext; 1795 return New; 1796 } 1797 1798 /// Typedef declarations don't have linkage, but they still denote the same 1799 /// entity if their types are the same. 1800 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1801 /// isSameEntity. 1802 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1803 TypedefNameDecl *Decl, 1804 LookupResult &Previous) { 1805 // This is only interesting when modules are enabled. 1806 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1807 return; 1808 1809 // Empty sets are uninteresting. 1810 if (Previous.empty()) 1811 return; 1812 1813 LookupResult::Filter Filter = Previous.makeFilter(); 1814 while (Filter.hasNext()) { 1815 NamedDecl *Old = Filter.next(); 1816 1817 // Non-hidden declarations are never ignored. 1818 if (S.isVisible(Old)) 1819 continue; 1820 1821 // Declarations of the same entity are not ignored, even if they have 1822 // different linkages. 1823 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1824 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1825 Decl->getUnderlyingType())) 1826 continue; 1827 1828 // If both declarations give a tag declaration a typedef name for linkage 1829 // purposes, then they declare the same entity. 1830 if (S.getLangOpts().CPlusPlus && 1831 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1832 Decl->getAnonDeclWithTypedefName()) 1833 continue; 1834 } 1835 1836 Filter.erase(); 1837 } 1838 1839 Filter.done(); 1840 } 1841 1842 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1843 QualType OldType; 1844 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1845 OldType = OldTypedef->getUnderlyingType(); 1846 else 1847 OldType = Context.getTypeDeclType(Old); 1848 QualType NewType = New->getUnderlyingType(); 1849 1850 if (NewType->isVariablyModifiedType()) { 1851 // Must not redefine a typedef with a variably-modified type. 1852 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1853 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1854 << Kind << NewType; 1855 if (Old->getLocation().isValid()) 1856 Diag(Old->getLocation(), diag::note_previous_definition); 1857 New->setInvalidDecl(); 1858 return true; 1859 } 1860 1861 if (OldType != NewType && 1862 !OldType->isDependentType() && 1863 !NewType->isDependentType() && 1864 !Context.hasSameType(OldType, NewType)) { 1865 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1866 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1867 << Kind << NewType << OldType; 1868 if (Old->getLocation().isValid()) 1869 Diag(Old->getLocation(), diag::note_previous_definition); 1870 New->setInvalidDecl(); 1871 return true; 1872 } 1873 return false; 1874 } 1875 1876 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1877 /// same name and scope as a previous declaration 'Old'. Figure out 1878 /// how to resolve this situation, merging decls or emitting 1879 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1880 /// 1881 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 1882 LookupResult &OldDecls) { 1883 // If the new decl is known invalid already, don't bother doing any 1884 // merging checks. 1885 if (New->isInvalidDecl()) return; 1886 1887 // Allow multiple definitions for ObjC built-in typedefs. 1888 // FIXME: Verify the underlying types are equivalent! 1889 if (getLangOpts().ObjC1) { 1890 const IdentifierInfo *TypeID = New->getIdentifier(); 1891 switch (TypeID->getLength()) { 1892 default: break; 1893 case 2: 1894 { 1895 if (!TypeID->isStr("id")) 1896 break; 1897 QualType T = New->getUnderlyingType(); 1898 if (!T->isPointerType()) 1899 break; 1900 if (!T->isVoidPointerType()) { 1901 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1902 if (!PT->isStructureType()) 1903 break; 1904 } 1905 Context.setObjCIdRedefinitionType(T); 1906 // Install the built-in type for 'id', ignoring the current definition. 1907 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1908 return; 1909 } 1910 case 5: 1911 if (!TypeID->isStr("Class")) 1912 break; 1913 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1914 // Install the built-in type for 'Class', ignoring the current definition. 1915 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1916 return; 1917 case 3: 1918 if (!TypeID->isStr("SEL")) 1919 break; 1920 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1921 // Install the built-in type for 'SEL', ignoring the current definition. 1922 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1923 return; 1924 } 1925 // Fall through - the typedef name was not a builtin type. 1926 } 1927 1928 // Verify the old decl was also a type. 1929 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1930 if (!Old) { 1931 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1932 << New->getDeclName(); 1933 1934 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1935 if (OldD->getLocation().isValid()) 1936 Diag(OldD->getLocation(), diag::note_previous_definition); 1937 1938 return New->setInvalidDecl(); 1939 } 1940 1941 // If the old declaration is invalid, just give up here. 1942 if (Old->isInvalidDecl()) 1943 return New->setInvalidDecl(); 1944 1945 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1946 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 1947 auto *NewTag = New->getAnonDeclWithTypedefName(); 1948 NamedDecl *Hidden = nullptr; 1949 if (getLangOpts().CPlusPlus && OldTag && NewTag && 1950 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 1951 !hasVisibleDefinition(OldTag, &Hidden)) { 1952 // There is a definition of this tag, but it is not visible. Use it 1953 // instead of our tag. 1954 New->setTypeForDecl(OldTD->getTypeForDecl()); 1955 if (OldTD->isModed()) 1956 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 1957 OldTD->getUnderlyingType()); 1958 else 1959 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 1960 1961 // Make the old tag definition visible. 1962 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 1963 1964 // If this was an unscoped enumeration, yank all of its enumerators 1965 // out of the scope. 1966 if (isa<EnumDecl>(NewTag)) { 1967 Scope *EnumScope = getNonFieldDeclScope(S); 1968 for (auto *D : NewTag->decls()) { 1969 auto *ED = cast<EnumConstantDecl>(D); 1970 assert(EnumScope->isDeclScope(ED)); 1971 EnumScope->RemoveDecl(ED); 1972 IdResolver.RemoveDecl(ED); 1973 ED->getLexicalDeclContext()->removeDecl(ED); 1974 } 1975 } 1976 } 1977 } 1978 1979 // If the typedef types are not identical, reject them in all languages and 1980 // with any extensions enabled. 1981 if (isIncompatibleTypedef(Old, New)) 1982 return; 1983 1984 // The types match. Link up the redeclaration chain and merge attributes if 1985 // the old declaration was a typedef. 1986 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1987 New->setPreviousDecl(Typedef); 1988 mergeDeclAttributes(New, Old); 1989 } 1990 1991 if (getLangOpts().MicrosoftExt) 1992 return; 1993 1994 if (getLangOpts().CPlusPlus) { 1995 // C++ [dcl.typedef]p2: 1996 // In a given non-class scope, a typedef specifier can be used to 1997 // redefine the name of any type declared in that scope to refer 1998 // to the type to which it already refers. 1999 if (!isa<CXXRecordDecl>(CurContext)) 2000 return; 2001 2002 // C++0x [dcl.typedef]p4: 2003 // In a given class scope, a typedef specifier can be used to redefine 2004 // any class-name declared in that scope that is not also a typedef-name 2005 // to refer to the type to which it already refers. 2006 // 2007 // This wording came in via DR424, which was a correction to the 2008 // wording in DR56, which accidentally banned code like: 2009 // 2010 // struct S { 2011 // typedef struct A { } A; 2012 // }; 2013 // 2014 // in the C++03 standard. We implement the C++0x semantics, which 2015 // allow the above but disallow 2016 // 2017 // struct S { 2018 // typedef int I; 2019 // typedef int I; 2020 // }; 2021 // 2022 // since that was the intent of DR56. 2023 if (!isa<TypedefNameDecl>(Old)) 2024 return; 2025 2026 Diag(New->getLocation(), diag::err_redefinition) 2027 << New->getDeclName(); 2028 Diag(Old->getLocation(), diag::note_previous_definition); 2029 return New->setInvalidDecl(); 2030 } 2031 2032 // Modules always permit redefinition of typedefs, as does C11. 2033 if (getLangOpts().Modules || getLangOpts().C11) 2034 return; 2035 2036 // If we have a redefinition of a typedef in C, emit a warning. This warning 2037 // is normally mapped to an error, but can be controlled with 2038 // -Wtypedef-redefinition. If either the original or the redefinition is 2039 // in a system header, don't emit this for compatibility with GCC. 2040 if (getDiagnostics().getSuppressSystemWarnings() && 2041 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2042 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2043 return; 2044 2045 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2046 << New->getDeclName(); 2047 Diag(Old->getLocation(), diag::note_previous_definition); 2048 } 2049 2050 /// DeclhasAttr - returns true if decl Declaration already has the target 2051 /// attribute. 2052 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2053 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2054 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2055 for (const auto *i : D->attrs()) 2056 if (i->getKind() == A->getKind()) { 2057 if (Ann) { 2058 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2059 return true; 2060 continue; 2061 } 2062 // FIXME: Don't hardcode this check 2063 if (OA && isa<OwnershipAttr>(i)) 2064 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2065 return true; 2066 } 2067 2068 return false; 2069 } 2070 2071 static bool isAttributeTargetADefinition(Decl *D) { 2072 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2073 return VD->isThisDeclarationADefinition(); 2074 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2075 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2076 return true; 2077 } 2078 2079 /// Merge alignment attributes from \p Old to \p New, taking into account the 2080 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2081 /// 2082 /// \return \c true if any attributes were added to \p New. 2083 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2084 // Look for alignas attributes on Old, and pick out whichever attribute 2085 // specifies the strictest alignment requirement. 2086 AlignedAttr *OldAlignasAttr = nullptr; 2087 AlignedAttr *OldStrictestAlignAttr = nullptr; 2088 unsigned OldAlign = 0; 2089 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2090 // FIXME: We have no way of representing inherited dependent alignments 2091 // in a case like: 2092 // template<int A, int B> struct alignas(A) X; 2093 // template<int A, int B> struct alignas(B) X {}; 2094 // For now, we just ignore any alignas attributes which are not on the 2095 // definition in such a case. 2096 if (I->isAlignmentDependent()) 2097 return false; 2098 2099 if (I->isAlignas()) 2100 OldAlignasAttr = I; 2101 2102 unsigned Align = I->getAlignment(S.Context); 2103 if (Align > OldAlign) { 2104 OldAlign = Align; 2105 OldStrictestAlignAttr = I; 2106 } 2107 } 2108 2109 // Look for alignas attributes on New. 2110 AlignedAttr *NewAlignasAttr = nullptr; 2111 unsigned NewAlign = 0; 2112 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2113 if (I->isAlignmentDependent()) 2114 return false; 2115 2116 if (I->isAlignas()) 2117 NewAlignasAttr = I; 2118 2119 unsigned Align = I->getAlignment(S.Context); 2120 if (Align > NewAlign) 2121 NewAlign = Align; 2122 } 2123 2124 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2125 // Both declarations have 'alignas' attributes. We require them to match. 2126 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2127 // fall short. (If two declarations both have alignas, they must both match 2128 // every definition, and so must match each other if there is a definition.) 2129 2130 // If either declaration only contains 'alignas(0)' specifiers, then it 2131 // specifies the natural alignment for the type. 2132 if (OldAlign == 0 || NewAlign == 0) { 2133 QualType Ty; 2134 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2135 Ty = VD->getType(); 2136 else 2137 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2138 2139 if (OldAlign == 0) 2140 OldAlign = S.Context.getTypeAlign(Ty); 2141 if (NewAlign == 0) 2142 NewAlign = S.Context.getTypeAlign(Ty); 2143 } 2144 2145 if (OldAlign != NewAlign) { 2146 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2147 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2148 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2149 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2150 } 2151 } 2152 2153 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2154 // C++11 [dcl.align]p6: 2155 // if any declaration of an entity has an alignment-specifier, 2156 // every defining declaration of that entity shall specify an 2157 // equivalent alignment. 2158 // C11 6.7.5/7: 2159 // If the definition of an object does not have an alignment 2160 // specifier, any other declaration of that object shall also 2161 // have no alignment specifier. 2162 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2163 << OldAlignasAttr; 2164 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2165 << OldAlignasAttr; 2166 } 2167 2168 bool AnyAdded = false; 2169 2170 // Ensure we have an attribute representing the strictest alignment. 2171 if (OldAlign > NewAlign) { 2172 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2173 Clone->setInherited(true); 2174 New->addAttr(Clone); 2175 AnyAdded = true; 2176 } 2177 2178 // Ensure we have an alignas attribute if the old declaration had one. 2179 if (OldAlignasAttr && !NewAlignasAttr && 2180 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2181 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2182 Clone->setInherited(true); 2183 New->addAttr(Clone); 2184 AnyAdded = true; 2185 } 2186 2187 return AnyAdded; 2188 } 2189 2190 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2191 const InheritableAttr *Attr, 2192 Sema::AvailabilityMergeKind AMK) { 2193 InheritableAttr *NewAttr = nullptr; 2194 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2195 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2196 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2197 AA->getIntroduced(), AA->getDeprecated(), 2198 AA->getObsoleted(), AA->getUnavailable(), 2199 AA->getMessage(), AA->getNopartial(), AMK, 2200 AttrSpellingListIndex); 2201 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2202 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2203 AttrSpellingListIndex); 2204 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2205 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2206 AttrSpellingListIndex); 2207 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2208 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2209 AttrSpellingListIndex); 2210 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2211 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2212 AttrSpellingListIndex); 2213 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2214 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2215 FA->getFormatIdx(), FA->getFirstArg(), 2216 AttrSpellingListIndex); 2217 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2218 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2219 AttrSpellingListIndex); 2220 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2221 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2222 AttrSpellingListIndex, 2223 IA->getSemanticSpelling()); 2224 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2225 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2226 &S.Context.Idents.get(AA->getSpelling()), 2227 AttrSpellingListIndex); 2228 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2229 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2230 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2231 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2232 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2233 NewAttr = S.mergeInternalLinkageAttr( 2234 D, InternalLinkageA->getRange(), 2235 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2236 AttrSpellingListIndex); 2237 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2238 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2239 &S.Context.Idents.get(CommonA->getSpelling()), 2240 AttrSpellingListIndex); 2241 else if (isa<AlignedAttr>(Attr)) 2242 // AlignedAttrs are handled separately, because we need to handle all 2243 // such attributes on a declaration at the same time. 2244 NewAttr = nullptr; 2245 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2246 (AMK == Sema::AMK_Override || 2247 AMK == Sema::AMK_ProtocolImplementation)) 2248 NewAttr = nullptr; 2249 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2250 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2251 2252 if (NewAttr) { 2253 NewAttr->setInherited(true); 2254 D->addAttr(NewAttr); 2255 if (isa<MSInheritanceAttr>(NewAttr)) 2256 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2257 return true; 2258 } 2259 2260 return false; 2261 } 2262 2263 static const Decl *getDefinition(const Decl *D) { 2264 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2265 return TD->getDefinition(); 2266 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2267 const VarDecl *Def = VD->getDefinition(); 2268 if (Def) 2269 return Def; 2270 return VD->getActingDefinition(); 2271 } 2272 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2273 const FunctionDecl* Def; 2274 if (FD->isDefined(Def)) 2275 return Def; 2276 } 2277 return nullptr; 2278 } 2279 2280 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2281 for (const auto *Attribute : D->attrs()) 2282 if (Attribute->getKind() == Kind) 2283 return true; 2284 return false; 2285 } 2286 2287 /// checkNewAttributesAfterDef - If we already have a definition, check that 2288 /// there are no new attributes in this declaration. 2289 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2290 if (!New->hasAttrs()) 2291 return; 2292 2293 const Decl *Def = getDefinition(Old); 2294 if (!Def || Def == New) 2295 return; 2296 2297 AttrVec &NewAttributes = New->getAttrs(); 2298 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2299 const Attr *NewAttribute = NewAttributes[I]; 2300 2301 if (isa<AliasAttr>(NewAttribute)) { 2302 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2303 Sema::SkipBodyInfo SkipBody; 2304 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2305 2306 // If we're skipping this definition, drop the "alias" attribute. 2307 if (SkipBody.ShouldSkip) { 2308 NewAttributes.erase(NewAttributes.begin() + I); 2309 --E; 2310 continue; 2311 } 2312 } else { 2313 VarDecl *VD = cast<VarDecl>(New); 2314 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2315 VarDecl::TentativeDefinition 2316 ? diag::err_alias_after_tentative 2317 : diag::err_redefinition; 2318 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2319 S.Diag(Def->getLocation(), diag::note_previous_definition); 2320 VD->setInvalidDecl(); 2321 } 2322 ++I; 2323 continue; 2324 } 2325 2326 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2327 // Tentative definitions are only interesting for the alias check above. 2328 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2329 ++I; 2330 continue; 2331 } 2332 } 2333 2334 if (hasAttribute(Def, NewAttribute->getKind())) { 2335 ++I; 2336 continue; // regular attr merging will take care of validating this. 2337 } 2338 2339 if (isa<C11NoReturnAttr>(NewAttribute)) { 2340 // C's _Noreturn is allowed to be added to a function after it is defined. 2341 ++I; 2342 continue; 2343 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2344 if (AA->isAlignas()) { 2345 // C++11 [dcl.align]p6: 2346 // if any declaration of an entity has an alignment-specifier, 2347 // every defining declaration of that entity shall specify an 2348 // equivalent alignment. 2349 // C11 6.7.5/7: 2350 // If the definition of an object does not have an alignment 2351 // specifier, any other declaration of that object shall also 2352 // have no alignment specifier. 2353 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2354 << AA; 2355 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2356 << AA; 2357 NewAttributes.erase(NewAttributes.begin() + I); 2358 --E; 2359 continue; 2360 } 2361 } 2362 2363 S.Diag(NewAttribute->getLocation(), 2364 diag::warn_attribute_precede_definition); 2365 S.Diag(Def->getLocation(), diag::note_previous_definition); 2366 NewAttributes.erase(NewAttributes.begin() + I); 2367 --E; 2368 } 2369 } 2370 2371 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2372 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2373 AvailabilityMergeKind AMK) { 2374 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2375 UsedAttr *NewAttr = OldAttr->clone(Context); 2376 NewAttr->setInherited(true); 2377 New->addAttr(NewAttr); 2378 } 2379 2380 if (!Old->hasAttrs() && !New->hasAttrs()) 2381 return; 2382 2383 // Attributes declared post-definition are currently ignored. 2384 checkNewAttributesAfterDef(*this, New, Old); 2385 2386 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2387 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2388 if (OldA->getLabel() != NewA->getLabel()) { 2389 // This redeclaration changes __asm__ label. 2390 Diag(New->getLocation(), diag::err_different_asm_label); 2391 Diag(OldA->getLocation(), diag::note_previous_declaration); 2392 } 2393 } else if (Old->isUsed()) { 2394 // This redeclaration adds an __asm__ label to a declaration that has 2395 // already been ODR-used. 2396 Diag(New->getLocation(), diag::err_late_asm_label_name) 2397 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2398 } 2399 } 2400 2401 if (!Old->hasAttrs()) 2402 return; 2403 2404 bool foundAny = New->hasAttrs(); 2405 2406 // Ensure that any moving of objects within the allocated map is done before 2407 // we process them. 2408 if (!foundAny) New->setAttrs(AttrVec()); 2409 2410 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2411 // Ignore deprecated/unavailable/availability attributes if requested. 2412 AvailabilityMergeKind LocalAMK = AMK_None; 2413 if (isa<DeprecatedAttr>(I) || 2414 isa<UnavailableAttr>(I) || 2415 isa<AvailabilityAttr>(I)) { 2416 switch (AMK) { 2417 case AMK_None: 2418 continue; 2419 2420 case AMK_Redeclaration: 2421 case AMK_Override: 2422 case AMK_ProtocolImplementation: 2423 LocalAMK = AMK; 2424 break; 2425 } 2426 } 2427 2428 // Already handled. 2429 if (isa<UsedAttr>(I)) 2430 continue; 2431 2432 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2433 foundAny = true; 2434 } 2435 2436 if (mergeAlignedAttrs(*this, New, Old)) 2437 foundAny = true; 2438 2439 if (!foundAny) New->dropAttrs(); 2440 } 2441 2442 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2443 /// to the new one. 2444 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2445 const ParmVarDecl *oldDecl, 2446 Sema &S) { 2447 // C++11 [dcl.attr.depend]p2: 2448 // The first declaration of a function shall specify the 2449 // carries_dependency attribute for its declarator-id if any declaration 2450 // of the function specifies the carries_dependency attribute. 2451 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2452 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2453 S.Diag(CDA->getLocation(), 2454 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2455 // Find the first declaration of the parameter. 2456 // FIXME: Should we build redeclaration chains for function parameters? 2457 const FunctionDecl *FirstFD = 2458 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2459 const ParmVarDecl *FirstVD = 2460 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2461 S.Diag(FirstVD->getLocation(), 2462 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2463 } 2464 2465 if (!oldDecl->hasAttrs()) 2466 return; 2467 2468 bool foundAny = newDecl->hasAttrs(); 2469 2470 // Ensure that any moving of objects within the allocated map is 2471 // done before we process them. 2472 if (!foundAny) newDecl->setAttrs(AttrVec()); 2473 2474 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2475 if (!DeclHasAttr(newDecl, I)) { 2476 InheritableAttr *newAttr = 2477 cast<InheritableParamAttr>(I->clone(S.Context)); 2478 newAttr->setInherited(true); 2479 newDecl->addAttr(newAttr); 2480 foundAny = true; 2481 } 2482 } 2483 2484 if (!foundAny) newDecl->dropAttrs(); 2485 } 2486 2487 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2488 const ParmVarDecl *OldParam, 2489 Sema &S) { 2490 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2491 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2492 if (*Oldnullability != *Newnullability) { 2493 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2494 << DiagNullabilityKind( 2495 *Newnullability, 2496 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2497 != 0)) 2498 << DiagNullabilityKind( 2499 *Oldnullability, 2500 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2501 != 0)); 2502 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2503 } 2504 } else { 2505 QualType NewT = NewParam->getType(); 2506 NewT = S.Context.getAttributedType( 2507 AttributedType::getNullabilityAttrKind(*Oldnullability), 2508 NewT, NewT); 2509 NewParam->setType(NewT); 2510 } 2511 } 2512 } 2513 2514 namespace { 2515 2516 /// Used in MergeFunctionDecl to keep track of function parameters in 2517 /// C. 2518 struct GNUCompatibleParamWarning { 2519 ParmVarDecl *OldParm; 2520 ParmVarDecl *NewParm; 2521 QualType PromotedType; 2522 }; 2523 2524 } // end anonymous namespace 2525 2526 /// getSpecialMember - get the special member enum for a method. 2527 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2528 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2529 if (Ctor->isDefaultConstructor()) 2530 return Sema::CXXDefaultConstructor; 2531 2532 if (Ctor->isCopyConstructor()) 2533 return Sema::CXXCopyConstructor; 2534 2535 if (Ctor->isMoveConstructor()) 2536 return Sema::CXXMoveConstructor; 2537 } else if (isa<CXXDestructorDecl>(MD)) { 2538 return Sema::CXXDestructor; 2539 } else if (MD->isCopyAssignmentOperator()) { 2540 return Sema::CXXCopyAssignment; 2541 } else if (MD->isMoveAssignmentOperator()) { 2542 return Sema::CXXMoveAssignment; 2543 } 2544 2545 return Sema::CXXInvalid; 2546 } 2547 2548 // Determine whether the previous declaration was a definition, implicit 2549 // declaration, or a declaration. 2550 template <typename T> 2551 static std::pair<diag::kind, SourceLocation> 2552 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2553 diag::kind PrevDiag; 2554 SourceLocation OldLocation = Old->getLocation(); 2555 if (Old->isThisDeclarationADefinition()) 2556 PrevDiag = diag::note_previous_definition; 2557 else if (Old->isImplicit()) { 2558 PrevDiag = diag::note_previous_implicit_declaration; 2559 if (OldLocation.isInvalid()) 2560 OldLocation = New->getLocation(); 2561 } else 2562 PrevDiag = diag::note_previous_declaration; 2563 return std::make_pair(PrevDiag, OldLocation); 2564 } 2565 2566 /// canRedefineFunction - checks if a function can be redefined. Currently, 2567 /// only extern inline functions can be redefined, and even then only in 2568 /// GNU89 mode. 2569 static bool canRedefineFunction(const FunctionDecl *FD, 2570 const LangOptions& LangOpts) { 2571 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2572 !LangOpts.CPlusPlus && 2573 FD->isInlineSpecified() && 2574 FD->getStorageClass() == SC_Extern); 2575 } 2576 2577 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2578 const AttributedType *AT = T->getAs<AttributedType>(); 2579 while (AT && !AT->isCallingConv()) 2580 AT = AT->getModifiedType()->getAs<AttributedType>(); 2581 return AT; 2582 } 2583 2584 template <typename T> 2585 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2586 const DeclContext *DC = Old->getDeclContext(); 2587 if (DC->isRecord()) 2588 return false; 2589 2590 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2591 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2592 return true; 2593 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2594 return true; 2595 return false; 2596 } 2597 2598 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2599 static bool isExternC(VarTemplateDecl *) { return false; } 2600 2601 /// \brief Check whether a redeclaration of an entity introduced by a 2602 /// using-declaration is valid, given that we know it's not an overload 2603 /// (nor a hidden tag declaration). 2604 template<typename ExpectedDecl> 2605 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2606 ExpectedDecl *New) { 2607 // C++11 [basic.scope.declarative]p4: 2608 // Given a set of declarations in a single declarative region, each of 2609 // which specifies the same unqualified name, 2610 // -- they shall all refer to the same entity, or all refer to functions 2611 // and function templates; or 2612 // -- exactly one declaration shall declare a class name or enumeration 2613 // name that is not a typedef name and the other declarations shall all 2614 // refer to the same variable or enumerator, or all refer to functions 2615 // and function templates; in this case the class name or enumeration 2616 // name is hidden (3.3.10). 2617 2618 // C++11 [namespace.udecl]p14: 2619 // If a function declaration in namespace scope or block scope has the 2620 // same name and the same parameter-type-list as a function introduced 2621 // by a using-declaration, and the declarations do not declare the same 2622 // function, the program is ill-formed. 2623 2624 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2625 if (Old && 2626 !Old->getDeclContext()->getRedeclContext()->Equals( 2627 New->getDeclContext()->getRedeclContext()) && 2628 !(isExternC(Old) && isExternC(New))) 2629 Old = nullptr; 2630 2631 if (!Old) { 2632 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2633 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2634 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2635 return true; 2636 } 2637 return false; 2638 } 2639 2640 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2641 const FunctionDecl *B) { 2642 assert(A->getNumParams() == B->getNumParams()); 2643 2644 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2645 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2646 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2647 if (AttrA == AttrB) 2648 return true; 2649 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2650 }; 2651 2652 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2653 } 2654 2655 /// MergeFunctionDecl - We just parsed a function 'New' from 2656 /// declarator D which has the same name and scope as a previous 2657 /// declaration 'Old'. Figure out how to resolve this situation, 2658 /// merging decls or emitting diagnostics as appropriate. 2659 /// 2660 /// In C++, New and Old must be declarations that are not 2661 /// overloaded. Use IsOverload to determine whether New and Old are 2662 /// overloaded, and to select the Old declaration that New should be 2663 /// merged with. 2664 /// 2665 /// Returns true if there was an error, false otherwise. 2666 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2667 Scope *S, bool MergeTypeWithOld) { 2668 // Verify the old decl was also a function. 2669 FunctionDecl *Old = OldD->getAsFunction(); 2670 if (!Old) { 2671 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2672 if (New->getFriendObjectKind()) { 2673 Diag(New->getLocation(), diag::err_using_decl_friend); 2674 Diag(Shadow->getTargetDecl()->getLocation(), 2675 diag::note_using_decl_target); 2676 Diag(Shadow->getUsingDecl()->getLocation(), 2677 diag::note_using_decl) << 0; 2678 return true; 2679 } 2680 2681 // Check whether the two declarations might declare the same function. 2682 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2683 return true; 2684 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2685 } else { 2686 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2687 << New->getDeclName(); 2688 Diag(OldD->getLocation(), diag::note_previous_definition); 2689 return true; 2690 } 2691 } 2692 2693 // If the old declaration is invalid, just give up here. 2694 if (Old->isInvalidDecl()) 2695 return true; 2696 2697 diag::kind PrevDiag; 2698 SourceLocation OldLocation; 2699 std::tie(PrevDiag, OldLocation) = 2700 getNoteDiagForInvalidRedeclaration(Old, New); 2701 2702 // Don't complain about this if we're in GNU89 mode and the old function 2703 // is an extern inline function. 2704 // Don't complain about specializations. They are not supposed to have 2705 // storage classes. 2706 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2707 New->getStorageClass() == SC_Static && 2708 Old->hasExternalFormalLinkage() && 2709 !New->getTemplateSpecializationInfo() && 2710 !canRedefineFunction(Old, getLangOpts())) { 2711 if (getLangOpts().MicrosoftExt) { 2712 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2713 Diag(OldLocation, PrevDiag); 2714 } else { 2715 Diag(New->getLocation(), diag::err_static_non_static) << New; 2716 Diag(OldLocation, PrevDiag); 2717 return true; 2718 } 2719 } 2720 2721 if (New->hasAttr<InternalLinkageAttr>() && 2722 !Old->hasAttr<InternalLinkageAttr>()) { 2723 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2724 << New->getDeclName(); 2725 Diag(Old->getLocation(), diag::note_previous_definition); 2726 New->dropAttr<InternalLinkageAttr>(); 2727 } 2728 2729 // If a function is first declared with a calling convention, but is later 2730 // declared or defined without one, all following decls assume the calling 2731 // convention of the first. 2732 // 2733 // It's OK if a function is first declared without a calling convention, 2734 // but is later declared or defined with the default calling convention. 2735 // 2736 // To test if either decl has an explicit calling convention, we look for 2737 // AttributedType sugar nodes on the type as written. If they are missing or 2738 // were canonicalized away, we assume the calling convention was implicit. 2739 // 2740 // Note also that we DO NOT return at this point, because we still have 2741 // other tests to run. 2742 QualType OldQType = Context.getCanonicalType(Old->getType()); 2743 QualType NewQType = Context.getCanonicalType(New->getType()); 2744 const FunctionType *OldType = cast<FunctionType>(OldQType); 2745 const FunctionType *NewType = cast<FunctionType>(NewQType); 2746 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2747 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2748 bool RequiresAdjustment = false; 2749 2750 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2751 FunctionDecl *First = Old->getFirstDecl(); 2752 const FunctionType *FT = 2753 First->getType().getCanonicalType()->castAs<FunctionType>(); 2754 FunctionType::ExtInfo FI = FT->getExtInfo(); 2755 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2756 if (!NewCCExplicit) { 2757 // Inherit the CC from the previous declaration if it was specified 2758 // there but not here. 2759 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2760 RequiresAdjustment = true; 2761 } else { 2762 // Calling conventions aren't compatible, so complain. 2763 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2764 Diag(New->getLocation(), diag::err_cconv_change) 2765 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2766 << !FirstCCExplicit 2767 << (!FirstCCExplicit ? "" : 2768 FunctionType::getNameForCallConv(FI.getCC())); 2769 2770 // Put the note on the first decl, since it is the one that matters. 2771 Diag(First->getLocation(), diag::note_previous_declaration); 2772 return true; 2773 } 2774 } 2775 2776 // FIXME: diagnose the other way around? 2777 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2778 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2779 RequiresAdjustment = true; 2780 } 2781 2782 // Merge regparm attribute. 2783 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2784 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2785 if (NewTypeInfo.getHasRegParm()) { 2786 Diag(New->getLocation(), diag::err_regparm_mismatch) 2787 << NewType->getRegParmType() 2788 << OldType->getRegParmType(); 2789 Diag(OldLocation, diag::note_previous_declaration); 2790 return true; 2791 } 2792 2793 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2794 RequiresAdjustment = true; 2795 } 2796 2797 // Merge ns_returns_retained attribute. 2798 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2799 if (NewTypeInfo.getProducesResult()) { 2800 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2801 Diag(OldLocation, diag::note_previous_declaration); 2802 return true; 2803 } 2804 2805 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2806 RequiresAdjustment = true; 2807 } 2808 2809 if (RequiresAdjustment) { 2810 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2811 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2812 New->setType(QualType(AdjustedType, 0)); 2813 NewQType = Context.getCanonicalType(New->getType()); 2814 NewType = cast<FunctionType>(NewQType); 2815 } 2816 2817 // If this redeclaration makes the function inline, we may need to add it to 2818 // UndefinedButUsed. 2819 if (!Old->isInlined() && New->isInlined() && 2820 !New->hasAttr<GNUInlineAttr>() && 2821 !getLangOpts().GNUInline && 2822 Old->isUsed(false) && 2823 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2824 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2825 SourceLocation())); 2826 2827 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2828 // about it. 2829 if (New->hasAttr<GNUInlineAttr>() && 2830 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2831 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2832 } 2833 2834 // If pass_object_size params don't match up perfectly, this isn't a valid 2835 // redeclaration. 2836 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 2837 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 2838 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 2839 << New->getDeclName(); 2840 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2841 return true; 2842 } 2843 2844 if (getLangOpts().CPlusPlus) { 2845 // (C++98 13.1p2): 2846 // Certain function declarations cannot be overloaded: 2847 // -- Function declarations that differ only in the return type 2848 // cannot be overloaded. 2849 2850 // Go back to the type source info to compare the declared return types, 2851 // per C++1y [dcl.type.auto]p13: 2852 // Redeclarations or specializations of a function or function template 2853 // with a declared return type that uses a placeholder type shall also 2854 // use that placeholder, not a deduced type. 2855 QualType OldDeclaredReturnType = 2856 (Old->getTypeSourceInfo() 2857 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2858 : OldType)->getReturnType(); 2859 QualType NewDeclaredReturnType = 2860 (New->getTypeSourceInfo() 2861 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2862 : NewType)->getReturnType(); 2863 QualType ResQT; 2864 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2865 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2866 New->isLocalExternDecl())) { 2867 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2868 OldDeclaredReturnType->isObjCObjectPointerType()) 2869 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2870 if (ResQT.isNull()) { 2871 if (New->isCXXClassMember() && New->isOutOfLine()) 2872 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2873 << New << New->getReturnTypeSourceRange(); 2874 else 2875 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2876 << New->getReturnTypeSourceRange(); 2877 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2878 << Old->getReturnTypeSourceRange(); 2879 return true; 2880 } 2881 else 2882 NewQType = ResQT; 2883 } 2884 2885 QualType OldReturnType = OldType->getReturnType(); 2886 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2887 if (OldReturnType != NewReturnType) { 2888 // If this function has a deduced return type and has already been 2889 // defined, copy the deduced value from the old declaration. 2890 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2891 if (OldAT && OldAT->isDeduced()) { 2892 New->setType( 2893 SubstAutoType(New->getType(), 2894 OldAT->isDependentType() ? Context.DependentTy 2895 : OldAT->getDeducedType())); 2896 NewQType = Context.getCanonicalType( 2897 SubstAutoType(NewQType, 2898 OldAT->isDependentType() ? Context.DependentTy 2899 : OldAT->getDeducedType())); 2900 } 2901 } 2902 2903 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2904 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2905 if (OldMethod && NewMethod) { 2906 // Preserve triviality. 2907 NewMethod->setTrivial(OldMethod->isTrivial()); 2908 2909 // MSVC allows explicit template specialization at class scope: 2910 // 2 CXXMethodDecls referring to the same function will be injected. 2911 // We don't want a redeclaration error. 2912 bool IsClassScopeExplicitSpecialization = 2913 OldMethod->isFunctionTemplateSpecialization() && 2914 NewMethod->isFunctionTemplateSpecialization(); 2915 bool isFriend = NewMethod->getFriendObjectKind(); 2916 2917 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2918 !IsClassScopeExplicitSpecialization) { 2919 // -- Member function declarations with the same name and the 2920 // same parameter types cannot be overloaded if any of them 2921 // is a static member function declaration. 2922 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2923 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2924 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2925 return true; 2926 } 2927 2928 // C++ [class.mem]p1: 2929 // [...] A member shall not be declared twice in the 2930 // member-specification, except that a nested class or member 2931 // class template can be declared and then later defined. 2932 if (ActiveTemplateInstantiations.empty()) { 2933 unsigned NewDiag; 2934 if (isa<CXXConstructorDecl>(OldMethod)) 2935 NewDiag = diag::err_constructor_redeclared; 2936 else if (isa<CXXDestructorDecl>(NewMethod)) 2937 NewDiag = diag::err_destructor_redeclared; 2938 else if (isa<CXXConversionDecl>(NewMethod)) 2939 NewDiag = diag::err_conv_function_redeclared; 2940 else 2941 NewDiag = diag::err_member_redeclared; 2942 2943 Diag(New->getLocation(), NewDiag); 2944 } else { 2945 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2946 << New << New->getType(); 2947 } 2948 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2949 return true; 2950 2951 // Complain if this is an explicit declaration of a special 2952 // member that was initially declared implicitly. 2953 // 2954 // As an exception, it's okay to befriend such methods in order 2955 // to permit the implicit constructor/destructor/operator calls. 2956 } else if (OldMethod->isImplicit()) { 2957 if (isFriend) { 2958 NewMethod->setImplicit(); 2959 } else { 2960 Diag(NewMethod->getLocation(), 2961 diag::err_definition_of_implicitly_declared_member) 2962 << New << getSpecialMember(OldMethod); 2963 return true; 2964 } 2965 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2966 Diag(NewMethod->getLocation(), 2967 diag::err_definition_of_explicitly_defaulted_member) 2968 << getSpecialMember(OldMethod); 2969 return true; 2970 } 2971 } 2972 2973 // C++11 [dcl.attr.noreturn]p1: 2974 // The first declaration of a function shall specify the noreturn 2975 // attribute if any declaration of that function specifies the noreturn 2976 // attribute. 2977 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2978 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2979 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2980 Diag(Old->getFirstDecl()->getLocation(), 2981 diag::note_noreturn_missing_first_decl); 2982 } 2983 2984 // C++11 [dcl.attr.depend]p2: 2985 // The first declaration of a function shall specify the 2986 // carries_dependency attribute for its declarator-id if any declaration 2987 // of the function specifies the carries_dependency attribute. 2988 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2989 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2990 Diag(CDA->getLocation(), 2991 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2992 Diag(Old->getFirstDecl()->getLocation(), 2993 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2994 } 2995 2996 // (C++98 8.3.5p3): 2997 // All declarations for a function shall agree exactly in both the 2998 // return type and the parameter-type-list. 2999 // We also want to respect all the extended bits except noreturn. 3000 3001 // noreturn should now match unless the old type info didn't have it. 3002 QualType OldQTypeForComparison = OldQType; 3003 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3004 assert(OldQType == QualType(OldType, 0)); 3005 const FunctionType *OldTypeForComparison 3006 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3007 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3008 assert(OldQTypeForComparison.isCanonical()); 3009 } 3010 3011 if (haveIncompatibleLanguageLinkages(Old, New)) { 3012 // As a special case, retain the language linkage from previous 3013 // declarations of a friend function as an extension. 3014 // 3015 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3016 // and is useful because there's otherwise no way to specify language 3017 // linkage within class scope. 3018 // 3019 // Check cautiously as the friend object kind isn't yet complete. 3020 if (New->getFriendObjectKind() != Decl::FOK_None) { 3021 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3022 Diag(OldLocation, PrevDiag); 3023 } else { 3024 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3025 Diag(OldLocation, PrevDiag); 3026 return true; 3027 } 3028 } 3029 3030 if (OldQTypeForComparison == NewQType) 3031 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3032 3033 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3034 New->isLocalExternDecl()) { 3035 // It's OK if we couldn't merge types for a local function declaraton 3036 // if either the old or new type is dependent. We'll merge the types 3037 // when we instantiate the function. 3038 return false; 3039 } 3040 3041 // Fall through for conflicting redeclarations and redefinitions. 3042 } 3043 3044 // C: Function types need to be compatible, not identical. This handles 3045 // duplicate function decls like "void f(int); void f(enum X);" properly. 3046 if (!getLangOpts().CPlusPlus && 3047 Context.typesAreCompatible(OldQType, NewQType)) { 3048 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3049 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3050 const FunctionProtoType *OldProto = nullptr; 3051 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3052 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3053 // The old declaration provided a function prototype, but the 3054 // new declaration does not. Merge in the prototype. 3055 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3056 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3057 NewQType = 3058 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3059 OldProto->getExtProtoInfo()); 3060 New->setType(NewQType); 3061 New->setHasInheritedPrototype(); 3062 3063 // Synthesize parameters with the same types. 3064 SmallVector<ParmVarDecl*, 16> Params; 3065 for (const auto &ParamType : OldProto->param_types()) { 3066 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3067 SourceLocation(), nullptr, 3068 ParamType, /*TInfo=*/nullptr, 3069 SC_None, nullptr); 3070 Param->setScopeInfo(0, Params.size()); 3071 Param->setImplicit(); 3072 Params.push_back(Param); 3073 } 3074 3075 New->setParams(Params); 3076 } 3077 3078 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3079 } 3080 3081 // GNU C permits a K&R definition to follow a prototype declaration 3082 // if the declared types of the parameters in the K&R definition 3083 // match the types in the prototype declaration, even when the 3084 // promoted types of the parameters from the K&R definition differ 3085 // from the types in the prototype. GCC then keeps the types from 3086 // the prototype. 3087 // 3088 // If a variadic prototype is followed by a non-variadic K&R definition, 3089 // the K&R definition becomes variadic. This is sort of an edge case, but 3090 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3091 // C99 6.9.1p8. 3092 if (!getLangOpts().CPlusPlus && 3093 Old->hasPrototype() && !New->hasPrototype() && 3094 New->getType()->getAs<FunctionProtoType>() && 3095 Old->getNumParams() == New->getNumParams()) { 3096 SmallVector<QualType, 16> ArgTypes; 3097 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3098 const FunctionProtoType *OldProto 3099 = Old->getType()->getAs<FunctionProtoType>(); 3100 const FunctionProtoType *NewProto 3101 = New->getType()->getAs<FunctionProtoType>(); 3102 3103 // Determine whether this is the GNU C extension. 3104 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3105 NewProto->getReturnType()); 3106 bool LooseCompatible = !MergedReturn.isNull(); 3107 for (unsigned Idx = 0, End = Old->getNumParams(); 3108 LooseCompatible && Idx != End; ++Idx) { 3109 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3110 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3111 if (Context.typesAreCompatible(OldParm->getType(), 3112 NewProto->getParamType(Idx))) { 3113 ArgTypes.push_back(NewParm->getType()); 3114 } else if (Context.typesAreCompatible(OldParm->getType(), 3115 NewParm->getType(), 3116 /*CompareUnqualified=*/true)) { 3117 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3118 NewProto->getParamType(Idx) }; 3119 Warnings.push_back(Warn); 3120 ArgTypes.push_back(NewParm->getType()); 3121 } else 3122 LooseCompatible = false; 3123 } 3124 3125 if (LooseCompatible) { 3126 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3127 Diag(Warnings[Warn].NewParm->getLocation(), 3128 diag::ext_param_promoted_not_compatible_with_prototype) 3129 << Warnings[Warn].PromotedType 3130 << Warnings[Warn].OldParm->getType(); 3131 if (Warnings[Warn].OldParm->getLocation().isValid()) 3132 Diag(Warnings[Warn].OldParm->getLocation(), 3133 diag::note_previous_declaration); 3134 } 3135 3136 if (MergeTypeWithOld) 3137 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3138 OldProto->getExtProtoInfo())); 3139 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3140 } 3141 3142 // Fall through to diagnose conflicting types. 3143 } 3144 3145 // A function that has already been declared has been redeclared or 3146 // defined with a different type; show an appropriate diagnostic. 3147 3148 // If the previous declaration was an implicitly-generated builtin 3149 // declaration, then at the very least we should use a specialized note. 3150 unsigned BuiltinID; 3151 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3152 // If it's actually a library-defined builtin function like 'malloc' 3153 // or 'printf', just warn about the incompatible redeclaration. 3154 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3155 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3156 Diag(OldLocation, diag::note_previous_builtin_declaration) 3157 << Old << Old->getType(); 3158 3159 // If this is a global redeclaration, just forget hereafter 3160 // about the "builtin-ness" of the function. 3161 // 3162 // Doing this for local extern declarations is problematic. If 3163 // the builtin declaration remains visible, a second invalid 3164 // local declaration will produce a hard error; if it doesn't 3165 // remain visible, a single bogus local redeclaration (which is 3166 // actually only a warning) could break all the downstream code. 3167 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3168 New->getIdentifier()->revertBuiltin(); 3169 3170 return false; 3171 } 3172 3173 PrevDiag = diag::note_previous_builtin_declaration; 3174 } 3175 3176 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3177 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3178 return true; 3179 } 3180 3181 /// \brief Completes the merge of two function declarations that are 3182 /// known to be compatible. 3183 /// 3184 /// This routine handles the merging of attributes and other 3185 /// properties of function declarations from the old declaration to 3186 /// the new declaration, once we know that New is in fact a 3187 /// redeclaration of Old. 3188 /// 3189 /// \returns false 3190 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3191 Scope *S, bool MergeTypeWithOld) { 3192 // Merge the attributes 3193 mergeDeclAttributes(New, Old); 3194 3195 // Merge "pure" flag. 3196 if (Old->isPure()) 3197 New->setPure(); 3198 3199 // Merge "used" flag. 3200 if (Old->getMostRecentDecl()->isUsed(false)) 3201 New->setIsUsed(); 3202 3203 // Merge attributes from the parameters. These can mismatch with K&R 3204 // declarations. 3205 if (New->getNumParams() == Old->getNumParams()) 3206 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3207 ParmVarDecl *NewParam = New->getParamDecl(i); 3208 ParmVarDecl *OldParam = Old->getParamDecl(i); 3209 mergeParamDeclAttributes(NewParam, OldParam, *this); 3210 mergeParamDeclTypes(NewParam, OldParam, *this); 3211 } 3212 3213 if (getLangOpts().CPlusPlus) 3214 return MergeCXXFunctionDecl(New, Old, S); 3215 3216 // Merge the function types so the we get the composite types for the return 3217 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3218 // was visible. 3219 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3220 if (!Merged.isNull() && MergeTypeWithOld) 3221 New->setType(Merged); 3222 3223 return false; 3224 } 3225 3226 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3227 ObjCMethodDecl *oldMethod) { 3228 // Merge the attributes, including deprecated/unavailable 3229 AvailabilityMergeKind MergeKind = 3230 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3231 ? AMK_ProtocolImplementation 3232 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3233 : AMK_Override; 3234 3235 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3236 3237 // Merge attributes from the parameters. 3238 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3239 oe = oldMethod->param_end(); 3240 for (ObjCMethodDecl::param_iterator 3241 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3242 ni != ne && oi != oe; ++ni, ++oi) 3243 mergeParamDeclAttributes(*ni, *oi, *this); 3244 3245 CheckObjCMethodOverride(newMethod, oldMethod); 3246 } 3247 3248 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3249 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3250 /// emitting diagnostics as appropriate. 3251 /// 3252 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3253 /// to here in AddInitializerToDecl. We can't check them before the initializer 3254 /// is attached. 3255 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3256 bool MergeTypeWithOld) { 3257 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3258 return; 3259 3260 QualType MergedT; 3261 if (getLangOpts().CPlusPlus) { 3262 if (New->getType()->isUndeducedType()) { 3263 // We don't know what the new type is until the initializer is attached. 3264 return; 3265 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3266 // These could still be something that needs exception specs checked. 3267 return MergeVarDeclExceptionSpecs(New, Old); 3268 } 3269 // C++ [basic.link]p10: 3270 // [...] the types specified by all declarations referring to a given 3271 // object or function shall be identical, except that declarations for an 3272 // array object can specify array types that differ by the presence or 3273 // absence of a major array bound (8.3.4). 3274 else if (Old->getType()->isIncompleteArrayType() && 3275 New->getType()->isArrayType()) { 3276 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3277 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3278 if (Context.hasSameType(OldArray->getElementType(), 3279 NewArray->getElementType())) 3280 MergedT = New->getType(); 3281 } else if (Old->getType()->isArrayType() && 3282 New->getType()->isIncompleteArrayType()) { 3283 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3284 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3285 if (Context.hasSameType(OldArray->getElementType(), 3286 NewArray->getElementType())) 3287 MergedT = Old->getType(); 3288 } else if (New->getType()->isObjCObjectPointerType() && 3289 Old->getType()->isObjCObjectPointerType()) { 3290 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3291 Old->getType()); 3292 } 3293 } else { 3294 // C 6.2.7p2: 3295 // All declarations that refer to the same object or function shall have 3296 // compatible type. 3297 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3298 } 3299 if (MergedT.isNull()) { 3300 // It's OK if we couldn't merge types if either type is dependent, for a 3301 // block-scope variable. In other cases (static data members of class 3302 // templates, variable templates, ...), we require the types to be 3303 // equivalent. 3304 // FIXME: The C++ standard doesn't say anything about this. 3305 if ((New->getType()->isDependentType() || 3306 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3307 // If the old type was dependent, we can't merge with it, so the new type 3308 // becomes dependent for now. We'll reproduce the original type when we 3309 // instantiate the TypeSourceInfo for the variable. 3310 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3311 New->setType(Context.DependentTy); 3312 return; 3313 } 3314 3315 // FIXME: Even if this merging succeeds, some other non-visible declaration 3316 // of this variable might have an incompatible type. For instance: 3317 // 3318 // extern int arr[]; 3319 // void f() { extern int arr[2]; } 3320 // void g() { extern int arr[3]; } 3321 // 3322 // Neither C nor C++ requires a diagnostic for this, but we should still try 3323 // to diagnose it. 3324 Diag(New->getLocation(), New->isThisDeclarationADefinition() 3325 ? diag::err_redefinition_different_type 3326 : diag::err_redeclaration_different_type) 3327 << New->getDeclName() << New->getType() << Old->getType(); 3328 3329 diag::kind PrevDiag; 3330 SourceLocation OldLocation; 3331 std::tie(PrevDiag, OldLocation) = 3332 getNoteDiagForInvalidRedeclaration(Old, New); 3333 Diag(OldLocation, PrevDiag); 3334 return New->setInvalidDecl(); 3335 } 3336 3337 // Don't actually update the type on the new declaration if the old 3338 // declaration was an extern declaration in a different scope. 3339 if (MergeTypeWithOld) 3340 New->setType(MergedT); 3341 } 3342 3343 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3344 LookupResult &Previous) { 3345 // C11 6.2.7p4: 3346 // For an identifier with internal or external linkage declared 3347 // in a scope in which a prior declaration of that identifier is 3348 // visible, if the prior declaration specifies internal or 3349 // external linkage, the type of the identifier at the later 3350 // declaration becomes the composite type. 3351 // 3352 // If the variable isn't visible, we do not merge with its type. 3353 if (Previous.isShadowed()) 3354 return false; 3355 3356 if (S.getLangOpts().CPlusPlus) { 3357 // C++11 [dcl.array]p3: 3358 // If there is a preceding declaration of the entity in the same 3359 // scope in which the bound was specified, an omitted array bound 3360 // is taken to be the same as in that earlier declaration. 3361 return NewVD->isPreviousDeclInSameBlockScope() || 3362 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3363 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3364 } else { 3365 // If the old declaration was function-local, don't merge with its 3366 // type unless we're in the same function. 3367 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3368 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3369 } 3370 } 3371 3372 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3373 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3374 /// situation, merging decls or emitting diagnostics as appropriate. 3375 /// 3376 /// Tentative definition rules (C99 6.9.2p2) are checked by 3377 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3378 /// definitions here, since the initializer hasn't been attached. 3379 /// 3380 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3381 // If the new decl is already invalid, don't do any other checking. 3382 if (New->isInvalidDecl()) 3383 return; 3384 3385 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3386 return; 3387 3388 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3389 3390 // Verify the old decl was also a variable or variable template. 3391 VarDecl *Old = nullptr; 3392 VarTemplateDecl *OldTemplate = nullptr; 3393 if (Previous.isSingleResult()) { 3394 if (NewTemplate) { 3395 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3396 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3397 3398 if (auto *Shadow = 3399 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3400 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3401 return New->setInvalidDecl(); 3402 } else { 3403 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3404 3405 if (auto *Shadow = 3406 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3407 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3408 return New->setInvalidDecl(); 3409 } 3410 } 3411 if (!Old) { 3412 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3413 << New->getDeclName(); 3414 Diag(Previous.getRepresentativeDecl()->getLocation(), 3415 diag::note_previous_definition); 3416 return New->setInvalidDecl(); 3417 } 3418 3419 // Ensure the template parameters are compatible. 3420 if (NewTemplate && 3421 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3422 OldTemplate->getTemplateParameters(), 3423 /*Complain=*/true, TPL_TemplateMatch)) 3424 return New->setInvalidDecl(); 3425 3426 // C++ [class.mem]p1: 3427 // A member shall not be declared twice in the member-specification [...] 3428 // 3429 // Here, we need only consider static data members. 3430 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3431 Diag(New->getLocation(), diag::err_duplicate_member) 3432 << New->getIdentifier(); 3433 Diag(Old->getLocation(), diag::note_previous_declaration); 3434 New->setInvalidDecl(); 3435 } 3436 3437 mergeDeclAttributes(New, Old); 3438 // Warn if an already-declared variable is made a weak_import in a subsequent 3439 // declaration 3440 if (New->hasAttr<WeakImportAttr>() && 3441 Old->getStorageClass() == SC_None && 3442 !Old->hasAttr<WeakImportAttr>()) { 3443 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3444 Diag(Old->getLocation(), diag::note_previous_definition); 3445 // Remove weak_import attribute on new declaration. 3446 New->dropAttr<WeakImportAttr>(); 3447 } 3448 3449 if (New->hasAttr<InternalLinkageAttr>() && 3450 !Old->hasAttr<InternalLinkageAttr>()) { 3451 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3452 << New->getDeclName(); 3453 Diag(Old->getLocation(), diag::note_previous_definition); 3454 New->dropAttr<InternalLinkageAttr>(); 3455 } 3456 3457 // Merge the types. 3458 VarDecl *MostRecent = Old->getMostRecentDecl(); 3459 if (MostRecent != Old) { 3460 MergeVarDeclTypes(New, MostRecent, 3461 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3462 if (New->isInvalidDecl()) 3463 return; 3464 } 3465 3466 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3467 if (New->isInvalidDecl()) 3468 return; 3469 3470 diag::kind PrevDiag; 3471 SourceLocation OldLocation; 3472 std::tie(PrevDiag, OldLocation) = 3473 getNoteDiagForInvalidRedeclaration(Old, New); 3474 3475 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3476 if (New->getStorageClass() == SC_Static && 3477 !New->isStaticDataMember() && 3478 Old->hasExternalFormalLinkage()) { 3479 if (getLangOpts().MicrosoftExt) { 3480 Diag(New->getLocation(), diag::ext_static_non_static) 3481 << New->getDeclName(); 3482 Diag(OldLocation, PrevDiag); 3483 } else { 3484 Diag(New->getLocation(), diag::err_static_non_static) 3485 << New->getDeclName(); 3486 Diag(OldLocation, PrevDiag); 3487 return New->setInvalidDecl(); 3488 } 3489 } 3490 // C99 6.2.2p4: 3491 // For an identifier declared with the storage-class specifier 3492 // extern in a scope in which a prior declaration of that 3493 // identifier is visible,23) if the prior declaration specifies 3494 // internal or external linkage, the linkage of the identifier at 3495 // the later declaration is the same as the linkage specified at 3496 // the prior declaration. If no prior declaration is visible, or 3497 // if the prior declaration specifies no linkage, then the 3498 // identifier has external linkage. 3499 if (New->hasExternalStorage() && Old->hasLinkage()) 3500 /* Okay */; 3501 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3502 !New->isStaticDataMember() && 3503 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3504 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3505 Diag(OldLocation, PrevDiag); 3506 return New->setInvalidDecl(); 3507 } 3508 3509 // Check if extern is followed by non-extern and vice-versa. 3510 if (New->hasExternalStorage() && 3511 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3512 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3513 Diag(OldLocation, PrevDiag); 3514 return New->setInvalidDecl(); 3515 } 3516 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3517 !New->hasExternalStorage()) { 3518 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3519 Diag(OldLocation, PrevDiag); 3520 return New->setInvalidDecl(); 3521 } 3522 3523 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3524 3525 // FIXME: The test for external storage here seems wrong? We still 3526 // need to check for mismatches. 3527 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3528 // Don't complain about out-of-line definitions of static members. 3529 !(Old->getLexicalDeclContext()->isRecord() && 3530 !New->getLexicalDeclContext()->isRecord())) { 3531 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3532 Diag(OldLocation, PrevDiag); 3533 return New->setInvalidDecl(); 3534 } 3535 3536 if (New->getTLSKind() != Old->getTLSKind()) { 3537 if (!Old->getTLSKind()) { 3538 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3539 Diag(OldLocation, PrevDiag); 3540 } else if (!New->getTLSKind()) { 3541 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3542 Diag(OldLocation, PrevDiag); 3543 } else { 3544 // Do not allow redeclaration to change the variable between requiring 3545 // static and dynamic initialization. 3546 // FIXME: GCC allows this, but uses the TLS keyword on the first 3547 // declaration to determine the kind. Do we need to be compatible here? 3548 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3549 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3550 Diag(OldLocation, PrevDiag); 3551 } 3552 } 3553 3554 // C++ doesn't have tentative definitions, so go right ahead and check here. 3555 VarDecl *Def; 3556 if (getLangOpts().CPlusPlus && 3557 New->isThisDeclarationADefinition() == VarDecl::Definition && 3558 (Def = Old->getDefinition())) { 3559 NamedDecl *Hidden = nullptr; 3560 if (!hasVisibleDefinition(Def, &Hidden) && 3561 (New->getFormalLinkage() == InternalLinkage || 3562 New->getDescribedVarTemplate() || 3563 New->getNumTemplateParameterLists() || 3564 New->getDeclContext()->isDependentContext())) { 3565 // The previous definition is hidden, and multiple definitions are 3566 // permitted (in separate TUs). Form another definition of it. 3567 } else { 3568 Diag(New->getLocation(), diag::err_redefinition) << New; 3569 Diag(Def->getLocation(), diag::note_previous_definition); 3570 New->setInvalidDecl(); 3571 return; 3572 } 3573 } 3574 3575 if (haveIncompatibleLanguageLinkages(Old, New)) { 3576 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3577 Diag(OldLocation, PrevDiag); 3578 New->setInvalidDecl(); 3579 return; 3580 } 3581 3582 // Merge "used" flag. 3583 if (Old->getMostRecentDecl()->isUsed(false)) 3584 New->setIsUsed(); 3585 3586 // Keep a chain of previous declarations. 3587 New->setPreviousDecl(Old); 3588 if (NewTemplate) 3589 NewTemplate->setPreviousDecl(OldTemplate); 3590 3591 // Inherit access appropriately. 3592 New->setAccess(Old->getAccess()); 3593 if (NewTemplate) 3594 NewTemplate->setAccess(New->getAccess()); 3595 } 3596 3597 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3598 /// no declarator (e.g. "struct foo;") is parsed. 3599 Decl * 3600 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3601 RecordDecl *&AnonRecord) { 3602 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3603 AnonRecord); 3604 } 3605 3606 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3607 // disambiguate entities defined in different scopes. 3608 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3609 // compatibility. 3610 // We will pick our mangling number depending on which version of MSVC is being 3611 // targeted. 3612 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3613 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3614 ? S->getMSCurManglingNumber() 3615 : S->getMSLastManglingNumber(); 3616 } 3617 3618 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3619 if (!Context.getLangOpts().CPlusPlus) 3620 return; 3621 3622 if (isa<CXXRecordDecl>(Tag->getParent())) { 3623 // If this tag is the direct child of a class, number it if 3624 // it is anonymous. 3625 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3626 return; 3627 MangleNumberingContext &MCtx = 3628 Context.getManglingNumberContext(Tag->getParent()); 3629 Context.setManglingNumber( 3630 Tag, MCtx.getManglingNumber( 3631 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3632 return; 3633 } 3634 3635 // If this tag isn't a direct child of a class, number it if it is local. 3636 Decl *ManglingContextDecl; 3637 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3638 Tag->getDeclContext(), ManglingContextDecl)) { 3639 Context.setManglingNumber( 3640 Tag, MCtx->getManglingNumber( 3641 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3642 } 3643 } 3644 3645 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3646 TypedefNameDecl *NewTD) { 3647 if (TagFromDeclSpec->isInvalidDecl()) 3648 return; 3649 3650 // Do nothing if the tag already has a name for linkage purposes. 3651 if (TagFromDeclSpec->hasNameForLinkage()) 3652 return; 3653 3654 // A well-formed anonymous tag must always be a TUK_Definition. 3655 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3656 3657 // The type must match the tag exactly; no qualifiers allowed. 3658 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3659 Context.getTagDeclType(TagFromDeclSpec))) { 3660 if (getLangOpts().CPlusPlus) 3661 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3662 return; 3663 } 3664 3665 // If we've already computed linkage for the anonymous tag, then 3666 // adding a typedef name for the anonymous decl can change that 3667 // linkage, which might be a serious problem. Diagnose this as 3668 // unsupported and ignore the typedef name. TODO: we should 3669 // pursue this as a language defect and establish a formal rule 3670 // for how to handle it. 3671 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3672 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3673 3674 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3675 tagLoc = getLocForEndOfToken(tagLoc); 3676 3677 llvm::SmallString<40> textToInsert; 3678 textToInsert += ' '; 3679 textToInsert += NewTD->getIdentifier()->getName(); 3680 Diag(tagLoc, diag::note_typedef_changes_linkage) 3681 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3682 return; 3683 } 3684 3685 // Otherwise, set this is the anon-decl typedef for the tag. 3686 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3687 } 3688 3689 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3690 switch (T) { 3691 case DeclSpec::TST_class: 3692 return 0; 3693 case DeclSpec::TST_struct: 3694 return 1; 3695 case DeclSpec::TST_interface: 3696 return 2; 3697 case DeclSpec::TST_union: 3698 return 3; 3699 case DeclSpec::TST_enum: 3700 return 4; 3701 default: 3702 llvm_unreachable("unexpected type specifier"); 3703 } 3704 } 3705 3706 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3707 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3708 /// parameters to cope with template friend declarations. 3709 Decl * 3710 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3711 MultiTemplateParamsArg TemplateParams, 3712 bool IsExplicitInstantiation, 3713 RecordDecl *&AnonRecord) { 3714 Decl *TagD = nullptr; 3715 TagDecl *Tag = nullptr; 3716 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3717 DS.getTypeSpecType() == DeclSpec::TST_struct || 3718 DS.getTypeSpecType() == DeclSpec::TST_interface || 3719 DS.getTypeSpecType() == DeclSpec::TST_union || 3720 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3721 TagD = DS.getRepAsDecl(); 3722 3723 if (!TagD) // We probably had an error 3724 return nullptr; 3725 3726 // Note that the above type specs guarantee that the 3727 // type rep is a Decl, whereas in many of the others 3728 // it's a Type. 3729 if (isa<TagDecl>(TagD)) 3730 Tag = cast<TagDecl>(TagD); 3731 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3732 Tag = CTD->getTemplatedDecl(); 3733 } 3734 3735 if (Tag) { 3736 handleTagNumbering(Tag, S); 3737 Tag->setFreeStanding(); 3738 if (Tag->isInvalidDecl()) 3739 return Tag; 3740 } 3741 3742 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3743 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3744 // or incomplete types shall not be restrict-qualified." 3745 if (TypeQuals & DeclSpec::TQ_restrict) 3746 Diag(DS.getRestrictSpecLoc(), 3747 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3748 << DS.getSourceRange(); 3749 } 3750 3751 if (DS.isConstexprSpecified()) { 3752 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3753 // and definitions of functions and variables. 3754 if (Tag) 3755 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3756 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3757 else 3758 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3759 // Don't emit warnings after this error. 3760 return TagD; 3761 } 3762 3763 if (DS.isConceptSpecified()) { 3764 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3765 // either a function concept and its definition or a variable concept and 3766 // its initializer. 3767 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3768 return TagD; 3769 } 3770 3771 DiagnoseFunctionSpecifiers(DS); 3772 3773 if (DS.isFriendSpecified()) { 3774 // If we're dealing with a decl but not a TagDecl, assume that 3775 // whatever routines created it handled the friendship aspect. 3776 if (TagD && !Tag) 3777 return nullptr; 3778 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3779 } 3780 3781 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3782 bool IsExplicitSpecialization = 3783 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3784 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3785 !IsExplicitInstantiation && !IsExplicitSpecialization && 3786 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 3787 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3788 // nested-name-specifier unless it is an explicit instantiation 3789 // or an explicit specialization. 3790 // 3791 // FIXME: We allow class template partial specializations here too, per the 3792 // obvious intent of DR1819. 3793 // 3794 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3795 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3796 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 3797 return nullptr; 3798 } 3799 3800 // Track whether this decl-specifier declares anything. 3801 bool DeclaresAnything = true; 3802 3803 // Handle anonymous struct definitions. 3804 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3805 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3806 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3807 if (getLangOpts().CPlusPlus || 3808 Record->getDeclContext()->isRecord()) { 3809 // If CurContext is a DeclContext that can contain statements, 3810 // RecursiveASTVisitor won't visit the decls that 3811 // BuildAnonymousStructOrUnion() will put into CurContext. 3812 // Also store them here so that they can be part of the 3813 // DeclStmt that gets created in this case. 3814 // FIXME: Also return the IndirectFieldDecls created by 3815 // BuildAnonymousStructOr union, for the same reason? 3816 if (CurContext->isFunctionOrMethod()) 3817 AnonRecord = Record; 3818 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3819 Context.getPrintingPolicy()); 3820 } 3821 3822 DeclaresAnything = false; 3823 } 3824 } 3825 3826 // C11 6.7.2.1p2: 3827 // A struct-declaration that does not declare an anonymous structure or 3828 // anonymous union shall contain a struct-declarator-list. 3829 // 3830 // This rule also existed in C89 and C99; the grammar for struct-declaration 3831 // did not permit a struct-declaration without a struct-declarator-list. 3832 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3833 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3834 // Check for Microsoft C extension: anonymous struct/union member. 3835 // Handle 2 kinds of anonymous struct/union: 3836 // struct STRUCT; 3837 // union UNION; 3838 // and 3839 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3840 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3841 if ((Tag && Tag->getDeclName()) || 3842 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3843 RecordDecl *Record = nullptr; 3844 if (Tag) 3845 Record = dyn_cast<RecordDecl>(Tag); 3846 else if (const RecordType *RT = 3847 DS.getRepAsType().get()->getAsStructureType()) 3848 Record = RT->getDecl(); 3849 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3850 Record = UT->getDecl(); 3851 3852 if (Record && getLangOpts().MicrosoftExt) { 3853 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3854 << Record->isUnion() << DS.getSourceRange(); 3855 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3856 } 3857 3858 DeclaresAnything = false; 3859 } 3860 } 3861 3862 // Skip all the checks below if we have a type error. 3863 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3864 (TagD && TagD->isInvalidDecl())) 3865 return TagD; 3866 3867 if (getLangOpts().CPlusPlus && 3868 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3869 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3870 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3871 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3872 DeclaresAnything = false; 3873 3874 if (!DS.isMissingDeclaratorOk()) { 3875 // Customize diagnostic for a typedef missing a name. 3876 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3877 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3878 << DS.getSourceRange(); 3879 else 3880 DeclaresAnything = false; 3881 } 3882 3883 if (DS.isModulePrivateSpecified() && 3884 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3885 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3886 << Tag->getTagKind() 3887 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3888 3889 ActOnDocumentableDecl(TagD); 3890 3891 // C 6.7/2: 3892 // A declaration [...] shall declare at least a declarator [...], a tag, 3893 // or the members of an enumeration. 3894 // C++ [dcl.dcl]p3: 3895 // [If there are no declarators], and except for the declaration of an 3896 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3897 // names into the program, or shall redeclare a name introduced by a 3898 // previous declaration. 3899 if (!DeclaresAnything) { 3900 // In C, we allow this as a (popular) extension / bug. Don't bother 3901 // producing further diagnostics for redundant qualifiers after this. 3902 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3903 return TagD; 3904 } 3905 3906 // C++ [dcl.stc]p1: 3907 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3908 // init-declarator-list of the declaration shall not be empty. 3909 // C++ [dcl.fct.spec]p1: 3910 // If a cv-qualifier appears in a decl-specifier-seq, the 3911 // init-declarator-list of the declaration shall not be empty. 3912 // 3913 // Spurious qualifiers here appear to be valid in C. 3914 unsigned DiagID = diag::warn_standalone_specifier; 3915 if (getLangOpts().CPlusPlus) 3916 DiagID = diag::ext_standalone_specifier; 3917 3918 // Note that a linkage-specification sets a storage class, but 3919 // 'extern "C" struct foo;' is actually valid and not theoretically 3920 // useless. 3921 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3922 if (SCS == DeclSpec::SCS_mutable) 3923 // Since mutable is not a viable storage class specifier in C, there is 3924 // no reason to treat it as an extension. Instead, diagnose as an error. 3925 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3926 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3927 Diag(DS.getStorageClassSpecLoc(), DiagID) 3928 << DeclSpec::getSpecifierName(SCS); 3929 } 3930 3931 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3932 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3933 << DeclSpec::getSpecifierName(TSCS); 3934 if (DS.getTypeQualifiers()) { 3935 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3936 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3937 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3938 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3939 // Restrict is covered above. 3940 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3941 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3942 } 3943 3944 // Warn about ignored type attributes, for example: 3945 // __attribute__((aligned)) struct A; 3946 // Attributes should be placed after tag to apply to type declaration. 3947 if (!DS.getAttributes().empty()) { 3948 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3949 if (TypeSpecType == DeclSpec::TST_class || 3950 TypeSpecType == DeclSpec::TST_struct || 3951 TypeSpecType == DeclSpec::TST_interface || 3952 TypeSpecType == DeclSpec::TST_union || 3953 TypeSpecType == DeclSpec::TST_enum) { 3954 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 3955 attrs = attrs->getNext()) 3956 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3957 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 3958 } 3959 } 3960 3961 return TagD; 3962 } 3963 3964 /// We are trying to inject an anonymous member into the given scope; 3965 /// check if there's an existing declaration that can't be overloaded. 3966 /// 3967 /// \return true if this is a forbidden redeclaration 3968 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3969 Scope *S, 3970 DeclContext *Owner, 3971 DeclarationName Name, 3972 SourceLocation NameLoc, 3973 bool IsUnion) { 3974 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3975 Sema::ForRedeclaration); 3976 if (!SemaRef.LookupName(R, S)) return false; 3977 3978 // Pick a representative declaration. 3979 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3980 assert(PrevDecl && "Expected a non-null Decl"); 3981 3982 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3983 return false; 3984 3985 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 3986 << IsUnion << Name; 3987 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3988 3989 return true; 3990 } 3991 3992 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3993 /// anonymous struct or union AnonRecord into the owning context Owner 3994 /// and scope S. This routine will be invoked just after we realize 3995 /// that an unnamed union or struct is actually an anonymous union or 3996 /// struct, e.g., 3997 /// 3998 /// @code 3999 /// union { 4000 /// int i; 4001 /// float f; 4002 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4003 /// // f into the surrounding scope.x 4004 /// @endcode 4005 /// 4006 /// This routine is recursive, injecting the names of nested anonymous 4007 /// structs/unions into the owning context and scope as well. 4008 static bool 4009 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4010 RecordDecl *AnonRecord, AccessSpecifier AS, 4011 SmallVectorImpl<NamedDecl *> &Chaining) { 4012 bool Invalid = false; 4013 4014 // Look every FieldDecl and IndirectFieldDecl with a name. 4015 for (auto *D : AnonRecord->decls()) { 4016 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4017 cast<NamedDecl>(D)->getDeclName()) { 4018 ValueDecl *VD = cast<ValueDecl>(D); 4019 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4020 VD->getLocation(), 4021 AnonRecord->isUnion())) { 4022 // C++ [class.union]p2: 4023 // The names of the members of an anonymous union shall be 4024 // distinct from the names of any other entity in the 4025 // scope in which the anonymous union is declared. 4026 Invalid = true; 4027 } else { 4028 // C++ [class.union]p2: 4029 // For the purpose of name lookup, after the anonymous union 4030 // definition, the members of the anonymous union are 4031 // considered to have been defined in the scope in which the 4032 // anonymous union is declared. 4033 unsigned OldChainingSize = Chaining.size(); 4034 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4035 Chaining.append(IF->chain_begin(), IF->chain_end()); 4036 else 4037 Chaining.push_back(VD); 4038 4039 assert(Chaining.size() >= 2); 4040 NamedDecl **NamedChain = 4041 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4042 for (unsigned i = 0; i < Chaining.size(); i++) 4043 NamedChain[i] = Chaining[i]; 4044 4045 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4046 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4047 VD->getType(), NamedChain, Chaining.size()); 4048 4049 for (const auto *Attr : VD->attrs()) 4050 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4051 4052 IndirectField->setAccess(AS); 4053 IndirectField->setImplicit(); 4054 SemaRef.PushOnScopeChains(IndirectField, S); 4055 4056 // That includes picking up the appropriate access specifier. 4057 if (AS != AS_none) IndirectField->setAccess(AS); 4058 4059 Chaining.resize(OldChainingSize); 4060 } 4061 } 4062 } 4063 4064 return Invalid; 4065 } 4066 4067 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4068 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4069 /// illegal input values are mapped to SC_None. 4070 static StorageClass 4071 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4072 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4073 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4074 "Parser allowed 'typedef' as storage class VarDecl."); 4075 switch (StorageClassSpec) { 4076 case DeclSpec::SCS_unspecified: return SC_None; 4077 case DeclSpec::SCS_extern: 4078 if (DS.isExternInLinkageSpec()) 4079 return SC_None; 4080 return SC_Extern; 4081 case DeclSpec::SCS_static: return SC_Static; 4082 case DeclSpec::SCS_auto: return SC_Auto; 4083 case DeclSpec::SCS_register: return SC_Register; 4084 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4085 // Illegal SCSs map to None: error reporting is up to the caller. 4086 case DeclSpec::SCS_mutable: // Fall through. 4087 case DeclSpec::SCS_typedef: return SC_None; 4088 } 4089 llvm_unreachable("unknown storage class specifier"); 4090 } 4091 4092 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4093 assert(Record->hasInClassInitializer()); 4094 4095 for (const auto *I : Record->decls()) { 4096 const auto *FD = dyn_cast<FieldDecl>(I); 4097 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4098 FD = IFD->getAnonField(); 4099 if (FD && FD->hasInClassInitializer()) 4100 return FD->getLocation(); 4101 } 4102 4103 llvm_unreachable("couldn't find in-class initializer"); 4104 } 4105 4106 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4107 SourceLocation DefaultInitLoc) { 4108 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4109 return; 4110 4111 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4112 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4113 } 4114 4115 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4116 CXXRecordDecl *AnonUnion) { 4117 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4118 return; 4119 4120 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4121 } 4122 4123 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4124 /// anonymous structure or union. Anonymous unions are a C++ feature 4125 /// (C++ [class.union]) and a C11 feature; anonymous structures 4126 /// are a C11 feature and GNU C++ extension. 4127 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4128 AccessSpecifier AS, 4129 RecordDecl *Record, 4130 const PrintingPolicy &Policy) { 4131 DeclContext *Owner = Record->getDeclContext(); 4132 4133 // Diagnose whether this anonymous struct/union is an extension. 4134 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4135 Diag(Record->getLocation(), diag::ext_anonymous_union); 4136 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4137 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4138 else if (!Record->isUnion() && !getLangOpts().C11) 4139 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4140 4141 // C and C++ require different kinds of checks for anonymous 4142 // structs/unions. 4143 bool Invalid = false; 4144 if (getLangOpts().CPlusPlus) { 4145 const char *PrevSpec = nullptr; 4146 unsigned DiagID; 4147 if (Record->isUnion()) { 4148 // C++ [class.union]p6: 4149 // Anonymous unions declared in a named namespace or in the 4150 // global namespace shall be declared static. 4151 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4152 (isa<TranslationUnitDecl>(Owner) || 4153 (isa<NamespaceDecl>(Owner) && 4154 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4155 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4156 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4157 4158 // Recover by adding 'static'. 4159 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4160 PrevSpec, DiagID, Policy); 4161 } 4162 // C++ [class.union]p6: 4163 // A storage class is not allowed in a declaration of an 4164 // anonymous union in a class scope. 4165 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4166 isa<RecordDecl>(Owner)) { 4167 Diag(DS.getStorageClassSpecLoc(), 4168 diag::err_anonymous_union_with_storage_spec) 4169 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4170 4171 // Recover by removing the storage specifier. 4172 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4173 SourceLocation(), 4174 PrevSpec, DiagID, Context.getPrintingPolicy()); 4175 } 4176 } 4177 4178 // Ignore const/volatile/restrict qualifiers. 4179 if (DS.getTypeQualifiers()) { 4180 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4181 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4182 << Record->isUnion() << "const" 4183 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4184 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4185 Diag(DS.getVolatileSpecLoc(), 4186 diag::ext_anonymous_struct_union_qualified) 4187 << Record->isUnion() << "volatile" 4188 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4189 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4190 Diag(DS.getRestrictSpecLoc(), 4191 diag::ext_anonymous_struct_union_qualified) 4192 << Record->isUnion() << "restrict" 4193 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4194 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4195 Diag(DS.getAtomicSpecLoc(), 4196 diag::ext_anonymous_struct_union_qualified) 4197 << Record->isUnion() << "_Atomic" 4198 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4199 4200 DS.ClearTypeQualifiers(); 4201 } 4202 4203 // C++ [class.union]p2: 4204 // The member-specification of an anonymous union shall only 4205 // define non-static data members. [Note: nested types and 4206 // functions cannot be declared within an anonymous union. ] 4207 for (auto *Mem : Record->decls()) { 4208 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4209 // C++ [class.union]p3: 4210 // An anonymous union shall not have private or protected 4211 // members (clause 11). 4212 assert(FD->getAccess() != AS_none); 4213 if (FD->getAccess() != AS_public) { 4214 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4215 << Record->isUnion() << (FD->getAccess() == AS_protected); 4216 Invalid = true; 4217 } 4218 4219 // C++ [class.union]p1 4220 // An object of a class with a non-trivial constructor, a non-trivial 4221 // copy constructor, a non-trivial destructor, or a non-trivial copy 4222 // assignment operator cannot be a member of a union, nor can an 4223 // array of such objects. 4224 if (CheckNontrivialField(FD)) 4225 Invalid = true; 4226 } else if (Mem->isImplicit()) { 4227 // Any implicit members are fine. 4228 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4229 // This is a type that showed up in an 4230 // elaborated-type-specifier inside the anonymous struct or 4231 // union, but which actually declares a type outside of the 4232 // anonymous struct or union. It's okay. 4233 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4234 if (!MemRecord->isAnonymousStructOrUnion() && 4235 MemRecord->getDeclName()) { 4236 // Visual C++ allows type definition in anonymous struct or union. 4237 if (getLangOpts().MicrosoftExt) 4238 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4239 << Record->isUnion(); 4240 else { 4241 // This is a nested type declaration. 4242 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4243 << Record->isUnion(); 4244 Invalid = true; 4245 } 4246 } else { 4247 // This is an anonymous type definition within another anonymous type. 4248 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4249 // not part of standard C++. 4250 Diag(MemRecord->getLocation(), 4251 diag::ext_anonymous_record_with_anonymous_type) 4252 << Record->isUnion(); 4253 } 4254 } else if (isa<AccessSpecDecl>(Mem)) { 4255 // Any access specifier is fine. 4256 } else if (isa<StaticAssertDecl>(Mem)) { 4257 // In C++1z, static_assert declarations are also fine. 4258 } else { 4259 // We have something that isn't a non-static data 4260 // member. Complain about it. 4261 unsigned DK = diag::err_anonymous_record_bad_member; 4262 if (isa<TypeDecl>(Mem)) 4263 DK = diag::err_anonymous_record_with_type; 4264 else if (isa<FunctionDecl>(Mem)) 4265 DK = diag::err_anonymous_record_with_function; 4266 else if (isa<VarDecl>(Mem)) 4267 DK = diag::err_anonymous_record_with_static; 4268 4269 // Visual C++ allows type definition in anonymous struct or union. 4270 if (getLangOpts().MicrosoftExt && 4271 DK == diag::err_anonymous_record_with_type) 4272 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4273 << Record->isUnion(); 4274 else { 4275 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4276 Invalid = true; 4277 } 4278 } 4279 } 4280 4281 // C++11 [class.union]p8 (DR1460): 4282 // At most one variant member of a union may have a 4283 // brace-or-equal-initializer. 4284 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4285 Owner->isRecord()) 4286 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4287 cast<CXXRecordDecl>(Record)); 4288 } 4289 4290 if (!Record->isUnion() && !Owner->isRecord()) { 4291 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4292 << getLangOpts().CPlusPlus; 4293 Invalid = true; 4294 } 4295 4296 // Mock up a declarator. 4297 Declarator Dc(DS, Declarator::MemberContext); 4298 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4299 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4300 4301 // Create a declaration for this anonymous struct/union. 4302 NamedDecl *Anon = nullptr; 4303 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4304 Anon = FieldDecl::Create(Context, OwningClass, 4305 DS.getLocStart(), 4306 Record->getLocation(), 4307 /*IdentifierInfo=*/nullptr, 4308 Context.getTypeDeclType(Record), 4309 TInfo, 4310 /*BitWidth=*/nullptr, /*Mutable=*/false, 4311 /*InitStyle=*/ICIS_NoInit); 4312 Anon->setAccess(AS); 4313 if (getLangOpts().CPlusPlus) 4314 FieldCollector->Add(cast<FieldDecl>(Anon)); 4315 } else { 4316 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4317 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4318 if (SCSpec == DeclSpec::SCS_mutable) { 4319 // mutable can only appear on non-static class members, so it's always 4320 // an error here 4321 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4322 Invalid = true; 4323 SC = SC_None; 4324 } 4325 4326 Anon = VarDecl::Create(Context, Owner, 4327 DS.getLocStart(), 4328 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4329 Context.getTypeDeclType(Record), 4330 TInfo, SC); 4331 4332 // Default-initialize the implicit variable. This initialization will be 4333 // trivial in almost all cases, except if a union member has an in-class 4334 // initializer: 4335 // union { int n = 0; }; 4336 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4337 } 4338 Anon->setImplicit(); 4339 4340 // Mark this as an anonymous struct/union type. 4341 Record->setAnonymousStructOrUnion(true); 4342 4343 // Add the anonymous struct/union object to the current 4344 // context. We'll be referencing this object when we refer to one of 4345 // its members. 4346 Owner->addDecl(Anon); 4347 4348 // Inject the members of the anonymous struct/union into the owning 4349 // context and into the identifier resolver chain for name lookup 4350 // purposes. 4351 SmallVector<NamedDecl*, 2> Chain; 4352 Chain.push_back(Anon); 4353 4354 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4355 Invalid = true; 4356 4357 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4358 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4359 Decl *ManglingContextDecl; 4360 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4361 NewVD->getDeclContext(), ManglingContextDecl)) { 4362 Context.setManglingNumber( 4363 NewVD, MCtx->getManglingNumber( 4364 NewVD, getMSManglingNumber(getLangOpts(), S))); 4365 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4366 } 4367 } 4368 } 4369 4370 if (Invalid) 4371 Anon->setInvalidDecl(); 4372 4373 return Anon; 4374 } 4375 4376 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4377 /// Microsoft C anonymous structure. 4378 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4379 /// Example: 4380 /// 4381 /// struct A { int a; }; 4382 /// struct B { struct A; int b; }; 4383 /// 4384 /// void foo() { 4385 /// B var; 4386 /// var.a = 3; 4387 /// } 4388 /// 4389 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4390 RecordDecl *Record) { 4391 assert(Record && "expected a record!"); 4392 4393 // Mock up a declarator. 4394 Declarator Dc(DS, Declarator::TypeNameContext); 4395 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4396 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4397 4398 auto *ParentDecl = cast<RecordDecl>(CurContext); 4399 QualType RecTy = Context.getTypeDeclType(Record); 4400 4401 // Create a declaration for this anonymous struct. 4402 NamedDecl *Anon = FieldDecl::Create(Context, 4403 ParentDecl, 4404 DS.getLocStart(), 4405 DS.getLocStart(), 4406 /*IdentifierInfo=*/nullptr, 4407 RecTy, 4408 TInfo, 4409 /*BitWidth=*/nullptr, /*Mutable=*/false, 4410 /*InitStyle=*/ICIS_NoInit); 4411 Anon->setImplicit(); 4412 4413 // Add the anonymous struct object to the current context. 4414 CurContext->addDecl(Anon); 4415 4416 // Inject the members of the anonymous struct into the current 4417 // context and into the identifier resolver chain for name lookup 4418 // purposes. 4419 SmallVector<NamedDecl*, 2> Chain; 4420 Chain.push_back(Anon); 4421 4422 RecordDecl *RecordDef = Record->getDefinition(); 4423 if (RequireCompleteType(Anon->getLocation(), RecTy, 4424 diag::err_field_incomplete) || 4425 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4426 AS_none, Chain)) { 4427 Anon->setInvalidDecl(); 4428 ParentDecl->setInvalidDecl(); 4429 } 4430 4431 return Anon; 4432 } 4433 4434 /// GetNameForDeclarator - Determine the full declaration name for the 4435 /// given Declarator. 4436 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4437 return GetNameFromUnqualifiedId(D.getName()); 4438 } 4439 4440 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4441 DeclarationNameInfo 4442 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4443 DeclarationNameInfo NameInfo; 4444 NameInfo.setLoc(Name.StartLocation); 4445 4446 switch (Name.getKind()) { 4447 4448 case UnqualifiedId::IK_ImplicitSelfParam: 4449 case UnqualifiedId::IK_Identifier: 4450 NameInfo.setName(Name.Identifier); 4451 NameInfo.setLoc(Name.StartLocation); 4452 return NameInfo; 4453 4454 case UnqualifiedId::IK_OperatorFunctionId: 4455 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4456 Name.OperatorFunctionId.Operator)); 4457 NameInfo.setLoc(Name.StartLocation); 4458 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4459 = Name.OperatorFunctionId.SymbolLocations[0]; 4460 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4461 = Name.EndLocation.getRawEncoding(); 4462 return NameInfo; 4463 4464 case UnqualifiedId::IK_LiteralOperatorId: 4465 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4466 Name.Identifier)); 4467 NameInfo.setLoc(Name.StartLocation); 4468 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4469 return NameInfo; 4470 4471 case UnqualifiedId::IK_ConversionFunctionId: { 4472 TypeSourceInfo *TInfo; 4473 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4474 if (Ty.isNull()) 4475 return DeclarationNameInfo(); 4476 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4477 Context.getCanonicalType(Ty))); 4478 NameInfo.setLoc(Name.StartLocation); 4479 NameInfo.setNamedTypeInfo(TInfo); 4480 return NameInfo; 4481 } 4482 4483 case UnqualifiedId::IK_ConstructorName: { 4484 TypeSourceInfo *TInfo; 4485 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4486 if (Ty.isNull()) 4487 return DeclarationNameInfo(); 4488 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4489 Context.getCanonicalType(Ty))); 4490 NameInfo.setLoc(Name.StartLocation); 4491 NameInfo.setNamedTypeInfo(TInfo); 4492 return NameInfo; 4493 } 4494 4495 case UnqualifiedId::IK_ConstructorTemplateId: { 4496 // In well-formed code, we can only have a constructor 4497 // template-id that refers to the current context, so go there 4498 // to find the actual type being constructed. 4499 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4500 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4501 return DeclarationNameInfo(); 4502 4503 // Determine the type of the class being constructed. 4504 QualType CurClassType = Context.getTypeDeclType(CurClass); 4505 4506 // FIXME: Check two things: that the template-id names the same type as 4507 // CurClassType, and that the template-id does not occur when the name 4508 // was qualified. 4509 4510 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4511 Context.getCanonicalType(CurClassType))); 4512 NameInfo.setLoc(Name.StartLocation); 4513 // FIXME: should we retrieve TypeSourceInfo? 4514 NameInfo.setNamedTypeInfo(nullptr); 4515 return NameInfo; 4516 } 4517 4518 case UnqualifiedId::IK_DestructorName: { 4519 TypeSourceInfo *TInfo; 4520 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4521 if (Ty.isNull()) 4522 return DeclarationNameInfo(); 4523 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4524 Context.getCanonicalType(Ty))); 4525 NameInfo.setLoc(Name.StartLocation); 4526 NameInfo.setNamedTypeInfo(TInfo); 4527 return NameInfo; 4528 } 4529 4530 case UnqualifiedId::IK_TemplateId: { 4531 TemplateName TName = Name.TemplateId->Template.get(); 4532 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4533 return Context.getNameForTemplate(TName, TNameLoc); 4534 } 4535 4536 } // switch (Name.getKind()) 4537 4538 llvm_unreachable("Unknown name kind"); 4539 } 4540 4541 static QualType getCoreType(QualType Ty) { 4542 do { 4543 if (Ty->isPointerType() || Ty->isReferenceType()) 4544 Ty = Ty->getPointeeType(); 4545 else if (Ty->isArrayType()) 4546 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4547 else 4548 return Ty.withoutLocalFastQualifiers(); 4549 } while (true); 4550 } 4551 4552 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4553 /// and Definition have "nearly" matching parameters. This heuristic is 4554 /// used to improve diagnostics in the case where an out-of-line function 4555 /// definition doesn't match any declaration within the class or namespace. 4556 /// Also sets Params to the list of indices to the parameters that differ 4557 /// between the declaration and the definition. If hasSimilarParameters 4558 /// returns true and Params is empty, then all of the parameters match. 4559 static bool hasSimilarParameters(ASTContext &Context, 4560 FunctionDecl *Declaration, 4561 FunctionDecl *Definition, 4562 SmallVectorImpl<unsigned> &Params) { 4563 Params.clear(); 4564 if (Declaration->param_size() != Definition->param_size()) 4565 return false; 4566 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4567 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4568 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4569 4570 // The parameter types are identical 4571 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4572 continue; 4573 4574 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4575 QualType DefParamBaseTy = getCoreType(DefParamTy); 4576 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4577 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4578 4579 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4580 (DeclTyName && DeclTyName == DefTyName)) 4581 Params.push_back(Idx); 4582 else // The two parameters aren't even close 4583 return false; 4584 } 4585 4586 return true; 4587 } 4588 4589 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4590 /// declarator needs to be rebuilt in the current instantiation. 4591 /// Any bits of declarator which appear before the name are valid for 4592 /// consideration here. That's specifically the type in the decl spec 4593 /// and the base type in any member-pointer chunks. 4594 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4595 DeclarationName Name) { 4596 // The types we specifically need to rebuild are: 4597 // - typenames, typeofs, and decltypes 4598 // - types which will become injected class names 4599 // Of course, we also need to rebuild any type referencing such a 4600 // type. It's safest to just say "dependent", but we call out a 4601 // few cases here. 4602 4603 DeclSpec &DS = D.getMutableDeclSpec(); 4604 switch (DS.getTypeSpecType()) { 4605 case DeclSpec::TST_typename: 4606 case DeclSpec::TST_typeofType: 4607 case DeclSpec::TST_underlyingType: 4608 case DeclSpec::TST_atomic: { 4609 // Grab the type from the parser. 4610 TypeSourceInfo *TSI = nullptr; 4611 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4612 if (T.isNull() || !T->isDependentType()) break; 4613 4614 // Make sure there's a type source info. This isn't really much 4615 // of a waste; most dependent types should have type source info 4616 // attached already. 4617 if (!TSI) 4618 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4619 4620 // Rebuild the type in the current instantiation. 4621 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4622 if (!TSI) return true; 4623 4624 // Store the new type back in the decl spec. 4625 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4626 DS.UpdateTypeRep(LocType); 4627 break; 4628 } 4629 4630 case DeclSpec::TST_decltype: 4631 case DeclSpec::TST_typeofExpr: { 4632 Expr *E = DS.getRepAsExpr(); 4633 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4634 if (Result.isInvalid()) return true; 4635 DS.UpdateExprRep(Result.get()); 4636 break; 4637 } 4638 4639 default: 4640 // Nothing to do for these decl specs. 4641 break; 4642 } 4643 4644 // It doesn't matter what order we do this in. 4645 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4646 DeclaratorChunk &Chunk = D.getTypeObject(I); 4647 4648 // The only type information in the declarator which can come 4649 // before the declaration name is the base type of a member 4650 // pointer. 4651 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4652 continue; 4653 4654 // Rebuild the scope specifier in-place. 4655 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4656 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4657 return true; 4658 } 4659 4660 return false; 4661 } 4662 4663 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4664 D.setFunctionDefinitionKind(FDK_Declaration); 4665 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4666 4667 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4668 Dcl && Dcl->getDeclContext()->isFileContext()) 4669 Dcl->setTopLevelDeclInObjCContainer(); 4670 4671 return Dcl; 4672 } 4673 4674 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4675 /// If T is the name of a class, then each of the following shall have a 4676 /// name different from T: 4677 /// - every static data member of class T; 4678 /// - every member function of class T 4679 /// - every member of class T that is itself a type; 4680 /// \returns true if the declaration name violates these rules. 4681 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4682 DeclarationNameInfo NameInfo) { 4683 DeclarationName Name = NameInfo.getName(); 4684 4685 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4686 while (Record && Record->isAnonymousStructOrUnion()) 4687 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4688 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4689 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4690 return true; 4691 } 4692 4693 return false; 4694 } 4695 4696 /// \brief Diagnose a declaration whose declarator-id has the given 4697 /// nested-name-specifier. 4698 /// 4699 /// \param SS The nested-name-specifier of the declarator-id. 4700 /// 4701 /// \param DC The declaration context to which the nested-name-specifier 4702 /// resolves. 4703 /// 4704 /// \param Name The name of the entity being declared. 4705 /// 4706 /// \param Loc The location of the name of the entity being declared. 4707 /// 4708 /// \returns true if we cannot safely recover from this error, false otherwise. 4709 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4710 DeclarationName Name, 4711 SourceLocation Loc) { 4712 DeclContext *Cur = CurContext; 4713 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4714 Cur = Cur->getParent(); 4715 4716 // If the user provided a superfluous scope specifier that refers back to the 4717 // class in which the entity is already declared, diagnose and ignore it. 4718 // 4719 // class X { 4720 // void X::f(); 4721 // }; 4722 // 4723 // Note, it was once ill-formed to give redundant qualification in all 4724 // contexts, but that rule was removed by DR482. 4725 if (Cur->Equals(DC)) { 4726 if (Cur->isRecord()) { 4727 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4728 : diag::err_member_extra_qualification) 4729 << Name << FixItHint::CreateRemoval(SS.getRange()); 4730 SS.clear(); 4731 } else { 4732 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4733 } 4734 return false; 4735 } 4736 4737 // Check whether the qualifying scope encloses the scope of the original 4738 // declaration. 4739 if (!Cur->Encloses(DC)) { 4740 if (Cur->isRecord()) 4741 Diag(Loc, diag::err_member_qualification) 4742 << Name << SS.getRange(); 4743 else if (isa<TranslationUnitDecl>(DC)) 4744 Diag(Loc, diag::err_invalid_declarator_global_scope) 4745 << Name << SS.getRange(); 4746 else if (isa<FunctionDecl>(Cur)) 4747 Diag(Loc, diag::err_invalid_declarator_in_function) 4748 << Name << SS.getRange(); 4749 else if (isa<BlockDecl>(Cur)) 4750 Diag(Loc, diag::err_invalid_declarator_in_block) 4751 << Name << SS.getRange(); 4752 else 4753 Diag(Loc, diag::err_invalid_declarator_scope) 4754 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4755 4756 return true; 4757 } 4758 4759 if (Cur->isRecord()) { 4760 // Cannot qualify members within a class. 4761 Diag(Loc, diag::err_member_qualification) 4762 << Name << SS.getRange(); 4763 SS.clear(); 4764 4765 // C++ constructors and destructors with incorrect scopes can break 4766 // our AST invariants by having the wrong underlying types. If 4767 // that's the case, then drop this declaration entirely. 4768 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4769 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4770 !Context.hasSameType(Name.getCXXNameType(), 4771 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4772 return true; 4773 4774 return false; 4775 } 4776 4777 // C++11 [dcl.meaning]p1: 4778 // [...] "The nested-name-specifier of the qualified declarator-id shall 4779 // not begin with a decltype-specifer" 4780 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4781 while (SpecLoc.getPrefix()) 4782 SpecLoc = SpecLoc.getPrefix(); 4783 if (dyn_cast_or_null<DecltypeType>( 4784 SpecLoc.getNestedNameSpecifier()->getAsType())) 4785 Diag(Loc, diag::err_decltype_in_declarator) 4786 << SpecLoc.getTypeLoc().getSourceRange(); 4787 4788 return false; 4789 } 4790 4791 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4792 MultiTemplateParamsArg TemplateParamLists) { 4793 // TODO: consider using NameInfo for diagnostic. 4794 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4795 DeclarationName Name = NameInfo.getName(); 4796 4797 // All of these full declarators require an identifier. If it doesn't have 4798 // one, the ParsedFreeStandingDeclSpec action should be used. 4799 if (!Name) { 4800 if (!D.isInvalidType()) // Reject this if we think it is valid. 4801 Diag(D.getDeclSpec().getLocStart(), 4802 diag::err_declarator_need_ident) 4803 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4804 return nullptr; 4805 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4806 return nullptr; 4807 4808 // The scope passed in may not be a decl scope. Zip up the scope tree until 4809 // we find one that is. 4810 while ((S->getFlags() & Scope::DeclScope) == 0 || 4811 (S->getFlags() & Scope::TemplateParamScope) != 0) 4812 S = S->getParent(); 4813 4814 DeclContext *DC = CurContext; 4815 if (D.getCXXScopeSpec().isInvalid()) 4816 D.setInvalidType(); 4817 else if (D.getCXXScopeSpec().isSet()) { 4818 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4819 UPPC_DeclarationQualifier)) 4820 return nullptr; 4821 4822 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4823 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4824 if (!DC || isa<EnumDecl>(DC)) { 4825 // If we could not compute the declaration context, it's because the 4826 // declaration context is dependent but does not refer to a class, 4827 // class template, or class template partial specialization. Complain 4828 // and return early, to avoid the coming semantic disaster. 4829 Diag(D.getIdentifierLoc(), 4830 diag::err_template_qualified_declarator_no_match) 4831 << D.getCXXScopeSpec().getScopeRep() 4832 << D.getCXXScopeSpec().getRange(); 4833 return nullptr; 4834 } 4835 bool IsDependentContext = DC->isDependentContext(); 4836 4837 if (!IsDependentContext && 4838 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4839 return nullptr; 4840 4841 // If a class is incomplete, do not parse entities inside it. 4842 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4843 Diag(D.getIdentifierLoc(), 4844 diag::err_member_def_undefined_record) 4845 << Name << DC << D.getCXXScopeSpec().getRange(); 4846 return nullptr; 4847 } 4848 if (!D.getDeclSpec().isFriendSpecified()) { 4849 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4850 Name, D.getIdentifierLoc())) { 4851 if (DC->isRecord()) 4852 return nullptr; 4853 4854 D.setInvalidType(); 4855 } 4856 } 4857 4858 // Check whether we need to rebuild the type of the given 4859 // declaration in the current instantiation. 4860 if (EnteringContext && IsDependentContext && 4861 TemplateParamLists.size() != 0) { 4862 ContextRAII SavedContext(*this, DC); 4863 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4864 D.setInvalidType(); 4865 } 4866 } 4867 4868 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4869 QualType R = TInfo->getType(); 4870 4871 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 4872 // If this is a typedef, we'll end up spewing multiple diagnostics. 4873 // Just return early; it's safer. If this is a function, let the 4874 // "constructor cannot have a return type" diagnostic handle it. 4875 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4876 return nullptr; 4877 4878 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4879 UPPC_DeclarationType)) 4880 D.setInvalidType(); 4881 4882 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4883 ForRedeclaration); 4884 4885 // See if this is a redefinition of a variable in the same scope. 4886 if (!D.getCXXScopeSpec().isSet()) { 4887 bool IsLinkageLookup = false; 4888 bool CreateBuiltins = false; 4889 4890 // If the declaration we're planning to build will be a function 4891 // or object with linkage, then look for another declaration with 4892 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4893 // 4894 // If the declaration we're planning to build will be declared with 4895 // external linkage in the translation unit, create any builtin with 4896 // the same name. 4897 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4898 /* Do nothing*/; 4899 else if (CurContext->isFunctionOrMethod() && 4900 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4901 R->isFunctionType())) { 4902 IsLinkageLookup = true; 4903 CreateBuiltins = 4904 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4905 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4906 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4907 CreateBuiltins = true; 4908 4909 if (IsLinkageLookup) 4910 Previous.clear(LookupRedeclarationWithLinkage); 4911 4912 LookupName(Previous, S, CreateBuiltins); 4913 } else { // Something like "int foo::x;" 4914 LookupQualifiedName(Previous, DC); 4915 4916 // C++ [dcl.meaning]p1: 4917 // When the declarator-id is qualified, the declaration shall refer to a 4918 // previously declared member of the class or namespace to which the 4919 // qualifier refers (or, in the case of a namespace, of an element of the 4920 // inline namespace set of that namespace (7.3.1)) or to a specialization 4921 // thereof; [...] 4922 // 4923 // Note that we already checked the context above, and that we do not have 4924 // enough information to make sure that Previous contains the declaration 4925 // we want to match. For example, given: 4926 // 4927 // class X { 4928 // void f(); 4929 // void f(float); 4930 // }; 4931 // 4932 // void X::f(int) { } // ill-formed 4933 // 4934 // In this case, Previous will point to the overload set 4935 // containing the two f's declared in X, but neither of them 4936 // matches. 4937 4938 // C++ [dcl.meaning]p1: 4939 // [...] the member shall not merely have been introduced by a 4940 // using-declaration in the scope of the class or namespace nominated by 4941 // the nested-name-specifier of the declarator-id. 4942 RemoveUsingDecls(Previous); 4943 } 4944 4945 if (Previous.isSingleResult() && 4946 Previous.getFoundDecl()->isTemplateParameter()) { 4947 // Maybe we will complain about the shadowed template parameter. 4948 if (!D.isInvalidType()) 4949 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4950 Previous.getFoundDecl()); 4951 4952 // Just pretend that we didn't see the previous declaration. 4953 Previous.clear(); 4954 } 4955 4956 // In C++, the previous declaration we find might be a tag type 4957 // (class or enum). In this case, the new declaration will hide the 4958 // tag type. Note that this does does not apply if we're declaring a 4959 // typedef (C++ [dcl.typedef]p4). 4960 if (Previous.isSingleTagDecl() && 4961 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4962 Previous.clear(); 4963 4964 // Check that there are no default arguments other than in the parameters 4965 // of a function declaration (C++ only). 4966 if (getLangOpts().CPlusPlus) 4967 CheckExtraCXXDefaultArguments(D); 4968 4969 if (D.getDeclSpec().isConceptSpecified()) { 4970 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 4971 // applied only to the definition of a function template or variable 4972 // template, declared in namespace scope 4973 if (!TemplateParamLists.size()) { 4974 Diag(D.getDeclSpec().getConceptSpecLoc(), 4975 diag:: err_concept_wrong_decl_kind); 4976 return nullptr; 4977 } 4978 4979 if (!DC->getRedeclContext()->isFileContext()) { 4980 Diag(D.getIdentifierLoc(), 4981 diag::err_concept_decls_may_only_appear_in_namespace_scope); 4982 return nullptr; 4983 } 4984 } 4985 4986 NamedDecl *New; 4987 4988 bool AddToScope = true; 4989 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4990 if (TemplateParamLists.size()) { 4991 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4992 return nullptr; 4993 } 4994 4995 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4996 } else if (R->isFunctionType()) { 4997 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4998 TemplateParamLists, 4999 AddToScope); 5000 } else { 5001 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5002 AddToScope); 5003 } 5004 5005 if (!New) 5006 return nullptr; 5007 5008 // If this has an identifier and is not an invalid redeclaration or 5009 // function template specialization, add it to the scope stack. 5010 if (New->getDeclName() && AddToScope && 5011 !(D.isRedeclaration() && New->isInvalidDecl())) { 5012 // Only make a locally-scoped extern declaration visible if it is the first 5013 // declaration of this entity. Qualified lookup for such an entity should 5014 // only find this declaration if there is no visible declaration of it. 5015 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5016 PushOnScopeChains(New, S, AddToContext); 5017 if (!AddToContext) 5018 CurContext->addHiddenDecl(New); 5019 } 5020 5021 return New; 5022 } 5023 5024 /// Helper method to turn variable array types into constant array 5025 /// types in certain situations which would otherwise be errors (for 5026 /// GCC compatibility). 5027 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5028 ASTContext &Context, 5029 bool &SizeIsNegative, 5030 llvm::APSInt &Oversized) { 5031 // This method tries to turn a variable array into a constant 5032 // array even when the size isn't an ICE. This is necessary 5033 // for compatibility with code that depends on gcc's buggy 5034 // constant expression folding, like struct {char x[(int)(char*)2];} 5035 SizeIsNegative = false; 5036 Oversized = 0; 5037 5038 if (T->isDependentType()) 5039 return QualType(); 5040 5041 QualifierCollector Qs; 5042 const Type *Ty = Qs.strip(T); 5043 5044 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5045 QualType Pointee = PTy->getPointeeType(); 5046 QualType FixedType = 5047 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5048 Oversized); 5049 if (FixedType.isNull()) return FixedType; 5050 FixedType = Context.getPointerType(FixedType); 5051 return Qs.apply(Context, FixedType); 5052 } 5053 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5054 QualType Inner = PTy->getInnerType(); 5055 QualType FixedType = 5056 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5057 Oversized); 5058 if (FixedType.isNull()) return FixedType; 5059 FixedType = Context.getParenType(FixedType); 5060 return Qs.apply(Context, FixedType); 5061 } 5062 5063 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5064 if (!VLATy) 5065 return QualType(); 5066 // FIXME: We should probably handle this case 5067 if (VLATy->getElementType()->isVariablyModifiedType()) 5068 return QualType(); 5069 5070 llvm::APSInt Res; 5071 if (!VLATy->getSizeExpr() || 5072 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5073 return QualType(); 5074 5075 // Check whether the array size is negative. 5076 if (Res.isSigned() && Res.isNegative()) { 5077 SizeIsNegative = true; 5078 return QualType(); 5079 } 5080 5081 // Check whether the array is too large to be addressed. 5082 unsigned ActiveSizeBits 5083 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5084 Res); 5085 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5086 Oversized = Res; 5087 return QualType(); 5088 } 5089 5090 return Context.getConstantArrayType(VLATy->getElementType(), 5091 Res, ArrayType::Normal, 0); 5092 } 5093 5094 static void 5095 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5096 SrcTL = SrcTL.getUnqualifiedLoc(); 5097 DstTL = DstTL.getUnqualifiedLoc(); 5098 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5099 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5100 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5101 DstPTL.getPointeeLoc()); 5102 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5103 return; 5104 } 5105 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5106 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5107 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5108 DstPTL.getInnerLoc()); 5109 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5110 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5111 return; 5112 } 5113 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5114 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5115 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5116 TypeLoc DstElemTL = DstATL.getElementLoc(); 5117 DstElemTL.initializeFullCopy(SrcElemTL); 5118 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5119 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5120 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5121 } 5122 5123 /// Helper method to turn variable array types into constant array 5124 /// types in certain situations which would otherwise be errors (for 5125 /// GCC compatibility). 5126 static TypeSourceInfo* 5127 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5128 ASTContext &Context, 5129 bool &SizeIsNegative, 5130 llvm::APSInt &Oversized) { 5131 QualType FixedTy 5132 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5133 SizeIsNegative, Oversized); 5134 if (FixedTy.isNull()) 5135 return nullptr; 5136 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5137 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5138 FixedTInfo->getTypeLoc()); 5139 return FixedTInfo; 5140 } 5141 5142 /// \brief Register the given locally-scoped extern "C" declaration so 5143 /// that it can be found later for redeclarations. We include any extern "C" 5144 /// declaration that is not visible in the translation unit here, not just 5145 /// function-scope declarations. 5146 void 5147 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5148 if (!getLangOpts().CPlusPlus && 5149 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5150 // Don't need to track declarations in the TU in C. 5151 return; 5152 5153 // Note that we have a locally-scoped external with this name. 5154 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5155 } 5156 5157 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5158 // FIXME: We can have multiple results via __attribute__((overloadable)). 5159 auto Result = Context.getExternCContextDecl()->lookup(Name); 5160 return Result.empty() ? nullptr : *Result.begin(); 5161 } 5162 5163 /// \brief Diagnose function specifiers on a declaration of an identifier that 5164 /// does not identify a function. 5165 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5166 // FIXME: We should probably indicate the identifier in question to avoid 5167 // confusion for constructs like "inline int a(), b;" 5168 if (DS.isInlineSpecified()) 5169 Diag(DS.getInlineSpecLoc(), 5170 diag::err_inline_non_function); 5171 5172 if (DS.isVirtualSpecified()) 5173 Diag(DS.getVirtualSpecLoc(), 5174 diag::err_virtual_non_function); 5175 5176 if (DS.isExplicitSpecified()) 5177 Diag(DS.getExplicitSpecLoc(), 5178 diag::err_explicit_non_function); 5179 5180 if (DS.isNoreturnSpecified()) 5181 Diag(DS.getNoreturnSpecLoc(), 5182 diag::err_noreturn_non_function); 5183 } 5184 5185 NamedDecl* 5186 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5187 TypeSourceInfo *TInfo, LookupResult &Previous) { 5188 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5189 if (D.getCXXScopeSpec().isSet()) { 5190 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5191 << D.getCXXScopeSpec().getRange(); 5192 D.setInvalidType(); 5193 // Pretend we didn't see the scope specifier. 5194 DC = CurContext; 5195 Previous.clear(); 5196 } 5197 5198 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5199 5200 if (D.getDeclSpec().isConstexprSpecified()) 5201 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5202 << 1; 5203 if (D.getDeclSpec().isConceptSpecified()) 5204 Diag(D.getDeclSpec().getConceptSpecLoc(), 5205 diag::err_concept_wrong_decl_kind); 5206 5207 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5208 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5209 << D.getName().getSourceRange(); 5210 return nullptr; 5211 } 5212 5213 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5214 if (!NewTD) return nullptr; 5215 5216 // Handle attributes prior to checking for duplicates in MergeVarDecl 5217 ProcessDeclAttributes(S, NewTD, D); 5218 5219 CheckTypedefForVariablyModifiedType(S, NewTD); 5220 5221 bool Redeclaration = D.isRedeclaration(); 5222 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5223 D.setRedeclaration(Redeclaration); 5224 return ND; 5225 } 5226 5227 void 5228 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5229 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5230 // then it shall have block scope. 5231 // Note that variably modified types must be fixed before merging the decl so 5232 // that redeclarations will match. 5233 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5234 QualType T = TInfo->getType(); 5235 if (T->isVariablyModifiedType()) { 5236 getCurFunction()->setHasBranchProtectedScope(); 5237 5238 if (S->getFnParent() == nullptr) { 5239 bool SizeIsNegative; 5240 llvm::APSInt Oversized; 5241 TypeSourceInfo *FixedTInfo = 5242 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5243 SizeIsNegative, 5244 Oversized); 5245 if (FixedTInfo) { 5246 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5247 NewTD->setTypeSourceInfo(FixedTInfo); 5248 } else { 5249 if (SizeIsNegative) 5250 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5251 else if (T->isVariableArrayType()) 5252 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5253 else if (Oversized.getBoolValue()) 5254 Diag(NewTD->getLocation(), diag::err_array_too_large) 5255 << Oversized.toString(10); 5256 else 5257 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5258 NewTD->setInvalidDecl(); 5259 } 5260 } 5261 } 5262 } 5263 5264 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5265 /// declares a typedef-name, either using the 'typedef' type specifier or via 5266 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5267 NamedDecl* 5268 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5269 LookupResult &Previous, bool &Redeclaration) { 5270 // Merge the decl with the existing one if appropriate. If the decl is 5271 // in an outer scope, it isn't the same thing. 5272 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5273 /*AllowInlineNamespace*/false); 5274 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5275 if (!Previous.empty()) { 5276 Redeclaration = true; 5277 MergeTypedefNameDecl(S, NewTD, Previous); 5278 } 5279 5280 // If this is the C FILE type, notify the AST context. 5281 if (IdentifierInfo *II = NewTD->getIdentifier()) 5282 if (!NewTD->isInvalidDecl() && 5283 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5284 if (II->isStr("FILE")) 5285 Context.setFILEDecl(NewTD); 5286 else if (II->isStr("jmp_buf")) 5287 Context.setjmp_bufDecl(NewTD); 5288 else if (II->isStr("sigjmp_buf")) 5289 Context.setsigjmp_bufDecl(NewTD); 5290 else if (II->isStr("ucontext_t")) 5291 Context.setucontext_tDecl(NewTD); 5292 } 5293 5294 return NewTD; 5295 } 5296 5297 /// \brief Determines whether the given declaration is an out-of-scope 5298 /// previous declaration. 5299 /// 5300 /// This routine should be invoked when name lookup has found a 5301 /// previous declaration (PrevDecl) that is not in the scope where a 5302 /// new declaration by the same name is being introduced. If the new 5303 /// declaration occurs in a local scope, previous declarations with 5304 /// linkage may still be considered previous declarations (C99 5305 /// 6.2.2p4-5, C++ [basic.link]p6). 5306 /// 5307 /// \param PrevDecl the previous declaration found by name 5308 /// lookup 5309 /// 5310 /// \param DC the context in which the new declaration is being 5311 /// declared. 5312 /// 5313 /// \returns true if PrevDecl is an out-of-scope previous declaration 5314 /// for a new delcaration with the same name. 5315 static bool 5316 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5317 ASTContext &Context) { 5318 if (!PrevDecl) 5319 return false; 5320 5321 if (!PrevDecl->hasLinkage()) 5322 return false; 5323 5324 if (Context.getLangOpts().CPlusPlus) { 5325 // C++ [basic.link]p6: 5326 // If there is a visible declaration of an entity with linkage 5327 // having the same name and type, ignoring entities declared 5328 // outside the innermost enclosing namespace scope, the block 5329 // scope declaration declares that same entity and receives the 5330 // linkage of the previous declaration. 5331 DeclContext *OuterContext = DC->getRedeclContext(); 5332 if (!OuterContext->isFunctionOrMethod()) 5333 // This rule only applies to block-scope declarations. 5334 return false; 5335 5336 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5337 if (PrevOuterContext->isRecord()) 5338 // We found a member function: ignore it. 5339 return false; 5340 5341 // Find the innermost enclosing namespace for the new and 5342 // previous declarations. 5343 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5344 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5345 5346 // The previous declaration is in a different namespace, so it 5347 // isn't the same function. 5348 if (!OuterContext->Equals(PrevOuterContext)) 5349 return false; 5350 } 5351 5352 return true; 5353 } 5354 5355 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5356 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5357 if (!SS.isSet()) return; 5358 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5359 } 5360 5361 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5362 QualType type = decl->getType(); 5363 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5364 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5365 // Various kinds of declaration aren't allowed to be __autoreleasing. 5366 unsigned kind = -1U; 5367 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5368 if (var->hasAttr<BlocksAttr>()) 5369 kind = 0; // __block 5370 else if (!var->hasLocalStorage()) 5371 kind = 1; // global 5372 } else if (isa<ObjCIvarDecl>(decl)) { 5373 kind = 3; // ivar 5374 } else if (isa<FieldDecl>(decl)) { 5375 kind = 2; // field 5376 } 5377 5378 if (kind != -1U) { 5379 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5380 << kind; 5381 } 5382 } else if (lifetime == Qualifiers::OCL_None) { 5383 // Try to infer lifetime. 5384 if (!type->isObjCLifetimeType()) 5385 return false; 5386 5387 lifetime = type->getObjCARCImplicitLifetime(); 5388 type = Context.getLifetimeQualifiedType(type, lifetime); 5389 decl->setType(type); 5390 } 5391 5392 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5393 // Thread-local variables cannot have lifetime. 5394 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5395 var->getTLSKind()) { 5396 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5397 << var->getType(); 5398 return true; 5399 } 5400 } 5401 5402 return false; 5403 } 5404 5405 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5406 // Ensure that an auto decl is deduced otherwise the checks below might cache 5407 // the wrong linkage. 5408 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5409 5410 // 'weak' only applies to declarations with external linkage. 5411 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5412 if (!ND.isExternallyVisible()) { 5413 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5414 ND.dropAttr<WeakAttr>(); 5415 } 5416 } 5417 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5418 if (ND.isExternallyVisible()) { 5419 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5420 ND.dropAttr<WeakRefAttr>(); 5421 ND.dropAttr<AliasAttr>(); 5422 } 5423 } 5424 5425 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5426 if (VD->hasInit()) { 5427 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5428 assert(VD->isThisDeclarationADefinition() && 5429 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5430 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD; 5431 VD->dropAttr<AliasAttr>(); 5432 } 5433 } 5434 } 5435 5436 // 'selectany' only applies to externally visible variable declarations. 5437 // It does not apply to functions. 5438 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5439 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5440 S.Diag(Attr->getLocation(), 5441 diag::err_attribute_selectany_non_extern_data); 5442 ND.dropAttr<SelectAnyAttr>(); 5443 } 5444 } 5445 5446 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5447 // dll attributes require external linkage. Static locals may have external 5448 // linkage but still cannot be explicitly imported or exported. 5449 auto *VD = dyn_cast<VarDecl>(&ND); 5450 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5451 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5452 << &ND << Attr; 5453 ND.setInvalidDecl(); 5454 } 5455 } 5456 5457 // Virtual functions cannot be marked as 'notail'. 5458 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5459 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5460 if (MD->isVirtual()) { 5461 S.Diag(ND.getLocation(), 5462 diag::err_invalid_attribute_on_virtual_function) 5463 << Attr; 5464 ND.dropAttr<NotTailCalledAttr>(); 5465 } 5466 } 5467 5468 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5469 NamedDecl *NewDecl, 5470 bool IsSpecialization) { 5471 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5472 OldDecl = OldTD->getTemplatedDecl(); 5473 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5474 NewDecl = NewTD->getTemplatedDecl(); 5475 5476 if (!OldDecl || !NewDecl) 5477 return; 5478 5479 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5480 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5481 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5482 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5483 5484 // dllimport and dllexport are inheritable attributes so we have to exclude 5485 // inherited attribute instances. 5486 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5487 (NewExportAttr && !NewExportAttr->isInherited()); 5488 5489 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5490 // the only exception being explicit specializations. 5491 // Implicitly generated declarations are also excluded for now because there 5492 // is no other way to switch these to use dllimport or dllexport. 5493 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5494 5495 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5496 // Allow with a warning for free functions and global variables. 5497 bool JustWarn = false; 5498 if (!OldDecl->isCXXClassMember()) { 5499 auto *VD = dyn_cast<VarDecl>(OldDecl); 5500 if (VD && !VD->getDescribedVarTemplate()) 5501 JustWarn = true; 5502 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5503 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5504 JustWarn = true; 5505 } 5506 5507 // We cannot change a declaration that's been used because IR has already 5508 // been emitted. Dllimported functions will still work though (modulo 5509 // address equality) as they can use the thunk. 5510 if (OldDecl->isUsed()) 5511 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5512 JustWarn = false; 5513 5514 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5515 : diag::err_attribute_dll_redeclaration; 5516 S.Diag(NewDecl->getLocation(), DiagID) 5517 << NewDecl 5518 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5519 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5520 if (!JustWarn) { 5521 NewDecl->setInvalidDecl(); 5522 return; 5523 } 5524 } 5525 5526 // A redeclaration is not allowed to drop a dllimport attribute, the only 5527 // exceptions being inline function definitions, local extern declarations, 5528 // and qualified friend declarations. 5529 // NB: MSVC converts such a declaration to dllexport. 5530 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5531 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5532 // Ignore static data because out-of-line definitions are diagnosed 5533 // separately. 5534 IsStaticDataMember = VD->isStaticDataMember(); 5535 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5536 IsInline = FD->isInlined(); 5537 IsQualifiedFriend = FD->getQualifier() && 5538 FD->getFriendObjectKind() == Decl::FOK_Declared; 5539 } 5540 5541 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5542 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5543 S.Diag(NewDecl->getLocation(), 5544 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5545 << NewDecl << OldImportAttr; 5546 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5547 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5548 OldDecl->dropAttr<DLLImportAttr>(); 5549 NewDecl->dropAttr<DLLImportAttr>(); 5550 } else if (IsInline && OldImportAttr && 5551 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5552 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5553 OldDecl->dropAttr<DLLImportAttr>(); 5554 NewDecl->dropAttr<DLLImportAttr>(); 5555 S.Diag(NewDecl->getLocation(), 5556 diag::warn_dllimport_dropped_from_inline_function) 5557 << NewDecl << OldImportAttr; 5558 } 5559 } 5560 5561 /// Given that we are within the definition of the given function, 5562 /// will that definition behave like C99's 'inline', where the 5563 /// definition is discarded except for optimization purposes? 5564 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5565 // Try to avoid calling GetGVALinkageForFunction. 5566 5567 // All cases of this require the 'inline' keyword. 5568 if (!FD->isInlined()) return false; 5569 5570 // This is only possible in C++ with the gnu_inline attribute. 5571 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5572 return false; 5573 5574 // Okay, go ahead and call the relatively-more-expensive function. 5575 5576 #ifndef NDEBUG 5577 // AST quite reasonably asserts that it's working on a function 5578 // definition. We don't really have a way to tell it that we're 5579 // currently defining the function, so just lie to it in +Asserts 5580 // builds. This is an awful hack. 5581 FD->setLazyBody(1); 5582 #endif 5583 5584 bool isC99Inline = 5585 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5586 5587 #ifndef NDEBUG 5588 FD->setLazyBody(0); 5589 #endif 5590 5591 return isC99Inline; 5592 } 5593 5594 /// Determine whether a variable is extern "C" prior to attaching 5595 /// an initializer. We can't just call isExternC() here, because that 5596 /// will also compute and cache whether the declaration is externally 5597 /// visible, which might change when we attach the initializer. 5598 /// 5599 /// This can only be used if the declaration is known to not be a 5600 /// redeclaration of an internal linkage declaration. 5601 /// 5602 /// For instance: 5603 /// 5604 /// auto x = []{}; 5605 /// 5606 /// Attaching the initializer here makes this declaration not externally 5607 /// visible, because its type has internal linkage. 5608 /// 5609 /// FIXME: This is a hack. 5610 template<typename T> 5611 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5612 if (S.getLangOpts().CPlusPlus) { 5613 // In C++, the overloadable attribute negates the effects of extern "C". 5614 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5615 return false; 5616 5617 // So do CUDA's host/device attributes if overloading is enabled. 5618 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 5619 (D->template hasAttr<CUDADeviceAttr>() || 5620 D->template hasAttr<CUDAHostAttr>())) 5621 return false; 5622 } 5623 return D->isExternC(); 5624 } 5625 5626 static bool shouldConsiderLinkage(const VarDecl *VD) { 5627 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5628 if (DC->isFunctionOrMethod()) 5629 return VD->hasExternalStorage(); 5630 if (DC->isFileContext()) 5631 return true; 5632 if (DC->isRecord()) 5633 return false; 5634 llvm_unreachable("Unexpected context"); 5635 } 5636 5637 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5638 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5639 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5640 return true; 5641 if (DC->isRecord()) 5642 return false; 5643 llvm_unreachable("Unexpected context"); 5644 } 5645 5646 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5647 AttributeList::Kind Kind) { 5648 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5649 if (L->getKind() == Kind) 5650 return true; 5651 return false; 5652 } 5653 5654 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5655 AttributeList::Kind Kind) { 5656 // Check decl attributes on the DeclSpec. 5657 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5658 return true; 5659 5660 // Walk the declarator structure, checking decl attributes that were in a type 5661 // position to the decl itself. 5662 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5663 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5664 return true; 5665 } 5666 5667 // Finally, check attributes on the decl itself. 5668 return hasParsedAttr(S, PD.getAttributes(), Kind); 5669 } 5670 5671 /// Adjust the \c DeclContext for a function or variable that might be a 5672 /// function-local external declaration. 5673 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5674 if (!DC->isFunctionOrMethod()) 5675 return false; 5676 5677 // If this is a local extern function or variable declared within a function 5678 // template, don't add it into the enclosing namespace scope until it is 5679 // instantiated; it might have a dependent type right now. 5680 if (DC->isDependentContext()) 5681 return true; 5682 5683 // C++11 [basic.link]p7: 5684 // When a block scope declaration of an entity with linkage is not found to 5685 // refer to some other declaration, then that entity is a member of the 5686 // innermost enclosing namespace. 5687 // 5688 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5689 // semantically-enclosing namespace, not a lexically-enclosing one. 5690 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5691 DC = DC->getParent(); 5692 return true; 5693 } 5694 5695 /// \brief Returns true if given declaration has external C language linkage. 5696 static bool isDeclExternC(const Decl *D) { 5697 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5698 return FD->isExternC(); 5699 if (const auto *VD = dyn_cast<VarDecl>(D)) 5700 return VD->isExternC(); 5701 5702 llvm_unreachable("Unknown type of decl!"); 5703 } 5704 5705 NamedDecl * 5706 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5707 TypeSourceInfo *TInfo, LookupResult &Previous, 5708 MultiTemplateParamsArg TemplateParamLists, 5709 bool &AddToScope) { 5710 QualType R = TInfo->getType(); 5711 DeclarationName Name = GetNameForDeclarator(D).getName(); 5712 5713 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5714 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5715 5716 // dllimport globals without explicit storage class are treated as extern. We 5717 // have to change the storage class this early to get the right DeclContext. 5718 if (SC == SC_None && !DC->isRecord() && 5719 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5720 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5721 SC = SC_Extern; 5722 5723 DeclContext *OriginalDC = DC; 5724 bool IsLocalExternDecl = SC == SC_Extern && 5725 adjustContextForLocalExternDecl(DC); 5726 5727 if (getLangOpts().OpenCL) { 5728 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5729 QualType NR = R; 5730 while (NR->isPointerType()) { 5731 if (NR->isFunctionPointerType()) { 5732 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5733 D.setInvalidType(); 5734 break; 5735 } 5736 NR = NR->getPointeeType(); 5737 } 5738 5739 if (!getOpenCLOptions().cl_khr_fp16) { 5740 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5741 // half array type (unless the cl_khr_fp16 extension is enabled). 5742 if (Context.getBaseElementType(R)->isHalfType()) { 5743 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5744 D.setInvalidType(); 5745 } 5746 } 5747 } 5748 5749 if (SCSpec == DeclSpec::SCS_mutable) { 5750 // mutable can only appear on non-static class members, so it's always 5751 // an error here 5752 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5753 D.setInvalidType(); 5754 SC = SC_None; 5755 } 5756 5757 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5758 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5759 D.getDeclSpec().getStorageClassSpecLoc())) { 5760 // In C++11, the 'register' storage class specifier is deprecated. 5761 // Suppress the warning in system macros, it's used in macros in some 5762 // popular C system headers, such as in glibc's htonl() macro. 5763 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5764 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 5765 : diag::warn_deprecated_register) 5766 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5767 } 5768 5769 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5770 if (!II) { 5771 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5772 << Name; 5773 return nullptr; 5774 } 5775 5776 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5777 5778 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5779 // C99 6.9p2: The storage-class specifiers auto and register shall not 5780 // appear in the declaration specifiers in an external declaration. 5781 // Global Register+Asm is a GNU extension we support. 5782 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5783 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5784 D.setInvalidType(); 5785 } 5786 } 5787 5788 if (getLangOpts().OpenCL) { 5789 // OpenCL v1.2 s6.9.b p4: 5790 // The sampler type cannot be used with the __local and __global address 5791 // space qualifiers. 5792 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5793 R.getAddressSpace() == LangAS::opencl_global)) { 5794 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5795 } 5796 5797 // OpenCL 1.2 spec, p6.9 r: 5798 // The event type cannot be used to declare a program scope variable. 5799 // The event type cannot be used with the __local, __constant and __global 5800 // address space qualifiers. 5801 if (R->isEventT()) { 5802 if (S->getParent() == nullptr) { 5803 Diag(D.getLocStart(), diag::err_event_t_global_var); 5804 D.setInvalidType(); 5805 } 5806 5807 if (R.getAddressSpace()) { 5808 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5809 D.setInvalidType(); 5810 } 5811 } 5812 } 5813 5814 bool IsExplicitSpecialization = false; 5815 bool IsVariableTemplateSpecialization = false; 5816 bool IsPartialSpecialization = false; 5817 bool IsVariableTemplate = false; 5818 VarDecl *NewVD = nullptr; 5819 VarTemplateDecl *NewTemplate = nullptr; 5820 TemplateParameterList *TemplateParams = nullptr; 5821 if (!getLangOpts().CPlusPlus) { 5822 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5823 D.getIdentifierLoc(), II, 5824 R, TInfo, SC); 5825 5826 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5827 ParsingInitForAutoVars.insert(NewVD); 5828 5829 if (D.isInvalidType()) 5830 NewVD->setInvalidDecl(); 5831 } else { 5832 bool Invalid = false; 5833 5834 if (DC->isRecord() && !CurContext->isRecord()) { 5835 // This is an out-of-line definition of a static data member. 5836 switch (SC) { 5837 case SC_None: 5838 break; 5839 case SC_Static: 5840 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5841 diag::err_static_out_of_line) 5842 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5843 break; 5844 case SC_Auto: 5845 case SC_Register: 5846 case SC_Extern: 5847 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5848 // to names of variables declared in a block or to function parameters. 5849 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5850 // of class members 5851 5852 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5853 diag::err_storage_class_for_static_member) 5854 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5855 break; 5856 case SC_PrivateExtern: 5857 llvm_unreachable("C storage class in c++!"); 5858 } 5859 } 5860 5861 if (SC == SC_Static && CurContext->isRecord()) { 5862 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5863 if (RD->isLocalClass()) 5864 Diag(D.getIdentifierLoc(), 5865 diag::err_static_data_member_not_allowed_in_local_class) 5866 << Name << RD->getDeclName(); 5867 5868 // C++98 [class.union]p1: If a union contains a static data member, 5869 // the program is ill-formed. C++11 drops this restriction. 5870 if (RD->isUnion()) 5871 Diag(D.getIdentifierLoc(), 5872 getLangOpts().CPlusPlus11 5873 ? diag::warn_cxx98_compat_static_data_member_in_union 5874 : diag::ext_static_data_member_in_union) << Name; 5875 // We conservatively disallow static data members in anonymous structs. 5876 else if (!RD->getDeclName()) 5877 Diag(D.getIdentifierLoc(), 5878 diag::err_static_data_member_not_allowed_in_anon_struct) 5879 << Name << RD->isUnion(); 5880 } 5881 } 5882 5883 // Match up the template parameter lists with the scope specifier, then 5884 // determine whether we have a template or a template specialization. 5885 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5886 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5887 D.getCXXScopeSpec(), 5888 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5889 ? D.getName().TemplateId 5890 : nullptr, 5891 TemplateParamLists, 5892 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5893 5894 if (TemplateParams) { 5895 if (!TemplateParams->size() && 5896 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5897 // There is an extraneous 'template<>' for this variable. Complain 5898 // about it, but allow the declaration of the variable. 5899 Diag(TemplateParams->getTemplateLoc(), 5900 diag::err_template_variable_noparams) 5901 << II 5902 << SourceRange(TemplateParams->getTemplateLoc(), 5903 TemplateParams->getRAngleLoc()); 5904 TemplateParams = nullptr; 5905 } else { 5906 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5907 // This is an explicit specialization or a partial specialization. 5908 // FIXME: Check that we can declare a specialization here. 5909 IsVariableTemplateSpecialization = true; 5910 IsPartialSpecialization = TemplateParams->size() > 0; 5911 } else { // if (TemplateParams->size() > 0) 5912 // This is a template declaration. 5913 IsVariableTemplate = true; 5914 5915 // Check that we can declare a template here. 5916 if (CheckTemplateDeclScope(S, TemplateParams)) 5917 return nullptr; 5918 5919 // Only C++1y supports variable templates (N3651). 5920 Diag(D.getIdentifierLoc(), 5921 getLangOpts().CPlusPlus14 5922 ? diag::warn_cxx11_compat_variable_template 5923 : diag::ext_variable_template); 5924 } 5925 } 5926 } else { 5927 assert( 5928 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 5929 "should have a 'template<>' for this decl"); 5930 } 5931 5932 if (IsVariableTemplateSpecialization) { 5933 SourceLocation TemplateKWLoc = 5934 TemplateParamLists.size() > 0 5935 ? TemplateParamLists[0]->getTemplateLoc() 5936 : SourceLocation(); 5937 DeclResult Res = ActOnVarTemplateSpecialization( 5938 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5939 IsPartialSpecialization); 5940 if (Res.isInvalid()) 5941 return nullptr; 5942 NewVD = cast<VarDecl>(Res.get()); 5943 AddToScope = false; 5944 } else 5945 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5946 D.getIdentifierLoc(), II, R, TInfo, SC); 5947 5948 // If this is supposed to be a variable template, create it as such. 5949 if (IsVariableTemplate) { 5950 NewTemplate = 5951 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5952 TemplateParams, NewVD); 5953 NewVD->setDescribedVarTemplate(NewTemplate); 5954 } 5955 5956 // If this decl has an auto type in need of deduction, make a note of the 5957 // Decl so we can diagnose uses of it in its own initializer. 5958 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5959 ParsingInitForAutoVars.insert(NewVD); 5960 5961 if (D.isInvalidType() || Invalid) { 5962 NewVD->setInvalidDecl(); 5963 if (NewTemplate) 5964 NewTemplate->setInvalidDecl(); 5965 } 5966 5967 SetNestedNameSpecifier(NewVD, D); 5968 5969 // If we have any template parameter lists that don't directly belong to 5970 // the variable (matching the scope specifier), store them. 5971 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5972 if (TemplateParamLists.size() > VDTemplateParamLists) 5973 NewVD->setTemplateParameterListsInfo( 5974 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 5975 5976 if (D.getDeclSpec().isConstexprSpecified()) 5977 NewVD->setConstexpr(true); 5978 5979 if (D.getDeclSpec().isConceptSpecified()) { 5980 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 5981 VTD->setConcept(); 5982 5983 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 5984 // be declared with the thread_local, inline, friend, or constexpr 5985 // specifiers, [...] 5986 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 5987 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5988 diag::err_concept_decl_invalid_specifiers) 5989 << 0 << 0; 5990 NewVD->setInvalidDecl(true); 5991 } 5992 5993 if (D.getDeclSpec().isConstexprSpecified()) { 5994 Diag(D.getDeclSpec().getConstexprSpecLoc(), 5995 diag::err_concept_decl_invalid_specifiers) 5996 << 0 << 3; 5997 NewVD->setInvalidDecl(true); 5998 } 5999 6000 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6001 // applied only to the definition of a function template or variable 6002 // template, declared in namespace scope. 6003 if (IsVariableTemplateSpecialization) { 6004 Diag(D.getDeclSpec().getConceptSpecLoc(), 6005 diag::err_concept_specified_specialization) 6006 << (IsPartialSpecialization ? 2 : 1); 6007 } 6008 6009 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6010 // following restrictions: 6011 // - The declared type shall have the type bool. 6012 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6013 !NewVD->isInvalidDecl()) { 6014 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6015 NewVD->setInvalidDecl(true); 6016 } 6017 } 6018 } 6019 6020 // Set the lexical context. If the declarator has a C++ scope specifier, the 6021 // lexical context will be different from the semantic context. 6022 NewVD->setLexicalDeclContext(CurContext); 6023 if (NewTemplate) 6024 NewTemplate->setLexicalDeclContext(CurContext); 6025 6026 if (IsLocalExternDecl) 6027 NewVD->setLocalExternDecl(); 6028 6029 bool EmitTLSUnsupportedError = false; 6030 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6031 // C++11 [dcl.stc]p4: 6032 // When thread_local is applied to a variable of block scope the 6033 // storage-class-specifier static is implied if it does not appear 6034 // explicitly. 6035 // Core issue: 'static' is not implied if the variable is declared 6036 // 'extern'. 6037 if (NewVD->hasLocalStorage() && 6038 (SCSpec != DeclSpec::SCS_unspecified || 6039 TSCS != DeclSpec::TSCS_thread_local || 6040 !DC->isFunctionOrMethod())) 6041 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6042 diag::err_thread_non_global) 6043 << DeclSpec::getSpecifierName(TSCS); 6044 else if (!Context.getTargetInfo().isTLSSupported()) { 6045 if (getLangOpts().CUDA) { 6046 // Postpone error emission until we've collected attributes required to 6047 // figure out whether it's a host or device variable and whether the 6048 // error should be ignored. 6049 EmitTLSUnsupportedError = true; 6050 // We still need to mark the variable as TLS so it shows up in AST with 6051 // proper storage class for other tools to use even if we're not going 6052 // to emit any code for it. 6053 NewVD->setTSCSpec(TSCS); 6054 } else 6055 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6056 diag::err_thread_unsupported); 6057 } else 6058 NewVD->setTSCSpec(TSCS); 6059 } 6060 6061 // C99 6.7.4p3 6062 // An inline definition of a function with external linkage shall 6063 // not contain a definition of a modifiable object with static or 6064 // thread storage duration... 6065 // We only apply this when the function is required to be defined 6066 // elsewhere, i.e. when the function is not 'extern inline'. Note 6067 // that a local variable with thread storage duration still has to 6068 // be marked 'static'. Also note that it's possible to get these 6069 // semantics in C++ using __attribute__((gnu_inline)). 6070 if (SC == SC_Static && S->getFnParent() != nullptr && 6071 !NewVD->getType().isConstQualified()) { 6072 FunctionDecl *CurFD = getCurFunctionDecl(); 6073 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6074 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6075 diag::warn_static_local_in_extern_inline); 6076 MaybeSuggestAddingStaticToDecl(CurFD); 6077 } 6078 } 6079 6080 if (D.getDeclSpec().isModulePrivateSpecified()) { 6081 if (IsVariableTemplateSpecialization) 6082 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6083 << (IsPartialSpecialization ? 1 : 0) 6084 << FixItHint::CreateRemoval( 6085 D.getDeclSpec().getModulePrivateSpecLoc()); 6086 else if (IsExplicitSpecialization) 6087 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6088 << 2 6089 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6090 else if (NewVD->hasLocalStorage()) 6091 Diag(NewVD->getLocation(), diag::err_module_private_local) 6092 << 0 << NewVD->getDeclName() 6093 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6094 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6095 else { 6096 NewVD->setModulePrivate(); 6097 if (NewTemplate) 6098 NewTemplate->setModulePrivate(); 6099 } 6100 } 6101 6102 // Handle attributes prior to checking for duplicates in MergeVarDecl 6103 ProcessDeclAttributes(S, NewVD, D); 6104 6105 if (getLangOpts().CUDA) { 6106 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6107 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6108 diag::err_thread_unsupported); 6109 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6110 // storage [duration]." 6111 if (SC == SC_None && S->getFnParent() != nullptr && 6112 (NewVD->hasAttr<CUDASharedAttr>() || 6113 NewVD->hasAttr<CUDAConstantAttr>())) { 6114 NewVD->setStorageClass(SC_Static); 6115 } 6116 } 6117 6118 // Ensure that dllimport globals without explicit storage class are treated as 6119 // extern. The storage class is set above using parsed attributes. Now we can 6120 // check the VarDecl itself. 6121 assert(!NewVD->hasAttr<DLLImportAttr>() || 6122 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6123 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6124 6125 // In auto-retain/release, infer strong retension for variables of 6126 // retainable type. 6127 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6128 NewVD->setInvalidDecl(); 6129 6130 // Handle GNU asm-label extension (encoded as an attribute). 6131 if (Expr *E = (Expr*)D.getAsmLabel()) { 6132 // The parser guarantees this is a string. 6133 StringLiteral *SE = cast<StringLiteral>(E); 6134 StringRef Label = SE->getString(); 6135 if (S->getFnParent() != nullptr) { 6136 switch (SC) { 6137 case SC_None: 6138 case SC_Auto: 6139 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6140 break; 6141 case SC_Register: 6142 // Local Named register 6143 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6144 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6145 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6146 break; 6147 case SC_Static: 6148 case SC_Extern: 6149 case SC_PrivateExtern: 6150 break; 6151 } 6152 } else if (SC == SC_Register) { 6153 // Global Named register 6154 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6155 const auto &TI = Context.getTargetInfo(); 6156 bool HasSizeMismatch; 6157 6158 if (!TI.isValidGCCRegisterName(Label)) 6159 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6160 else if (!TI.validateGlobalRegisterVariable(Label, 6161 Context.getTypeSize(R), 6162 HasSizeMismatch)) 6163 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6164 else if (HasSizeMismatch) 6165 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6166 } 6167 6168 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6169 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6170 NewVD->setInvalidDecl(true); 6171 } 6172 } 6173 6174 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6175 Context, Label, 0)); 6176 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6177 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6178 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6179 if (I != ExtnameUndeclaredIdentifiers.end()) { 6180 if (isDeclExternC(NewVD)) { 6181 NewVD->addAttr(I->second); 6182 ExtnameUndeclaredIdentifiers.erase(I); 6183 } else 6184 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6185 << /*Variable*/1 << NewVD; 6186 } 6187 } 6188 6189 // Diagnose shadowed variables before filtering for scope. 6190 if (D.getCXXScopeSpec().isEmpty()) 6191 CheckShadow(S, NewVD, Previous); 6192 6193 // Don't consider existing declarations that are in a different 6194 // scope and are out-of-semantic-context declarations (if the new 6195 // declaration has linkage). 6196 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6197 D.getCXXScopeSpec().isNotEmpty() || 6198 IsExplicitSpecialization || 6199 IsVariableTemplateSpecialization); 6200 6201 // Check whether the previous declaration is in the same block scope. This 6202 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6203 if (getLangOpts().CPlusPlus && 6204 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6205 NewVD->setPreviousDeclInSameBlockScope( 6206 Previous.isSingleResult() && !Previous.isShadowed() && 6207 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6208 6209 if (!getLangOpts().CPlusPlus) { 6210 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6211 } else { 6212 // If this is an explicit specialization of a static data member, check it. 6213 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6214 CheckMemberSpecialization(NewVD, Previous)) 6215 NewVD->setInvalidDecl(); 6216 6217 // Merge the decl with the existing one if appropriate. 6218 if (!Previous.empty()) { 6219 if (Previous.isSingleResult() && 6220 isa<FieldDecl>(Previous.getFoundDecl()) && 6221 D.getCXXScopeSpec().isSet()) { 6222 // The user tried to define a non-static data member 6223 // out-of-line (C++ [dcl.meaning]p1). 6224 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6225 << D.getCXXScopeSpec().getRange(); 6226 Previous.clear(); 6227 NewVD->setInvalidDecl(); 6228 } 6229 } else if (D.getCXXScopeSpec().isSet()) { 6230 // No previous declaration in the qualifying scope. 6231 Diag(D.getIdentifierLoc(), diag::err_no_member) 6232 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6233 << D.getCXXScopeSpec().getRange(); 6234 NewVD->setInvalidDecl(); 6235 } 6236 6237 if (!IsVariableTemplateSpecialization) 6238 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6239 6240 if (NewTemplate) { 6241 VarTemplateDecl *PrevVarTemplate = 6242 NewVD->getPreviousDecl() 6243 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6244 : nullptr; 6245 6246 // Check the template parameter list of this declaration, possibly 6247 // merging in the template parameter list from the previous variable 6248 // template declaration. 6249 if (CheckTemplateParameterList( 6250 TemplateParams, 6251 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6252 : nullptr, 6253 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6254 DC->isDependentContext()) 6255 ? TPC_ClassTemplateMember 6256 : TPC_VarTemplate)) 6257 NewVD->setInvalidDecl(); 6258 6259 // If we are providing an explicit specialization of a static variable 6260 // template, make a note of that. 6261 if (PrevVarTemplate && 6262 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6263 PrevVarTemplate->setMemberSpecialization(); 6264 } 6265 } 6266 6267 ProcessPragmaWeak(S, NewVD); 6268 6269 // If this is the first declaration of an extern C variable, update 6270 // the map of such variables. 6271 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6272 isIncompleteDeclExternC(*this, NewVD)) 6273 RegisterLocallyScopedExternCDecl(NewVD, S); 6274 6275 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6276 Decl *ManglingContextDecl; 6277 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6278 NewVD->getDeclContext(), ManglingContextDecl)) { 6279 Context.setManglingNumber( 6280 NewVD, MCtx->getManglingNumber( 6281 NewVD, getMSManglingNumber(getLangOpts(), S))); 6282 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6283 } 6284 } 6285 6286 // Special handling of variable named 'main'. 6287 if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") && 6288 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6289 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6290 6291 // C++ [basic.start.main]p3 6292 // A program that declares a variable main at global scope is ill-formed. 6293 if (getLangOpts().CPlusPlus) 6294 Diag(D.getLocStart(), diag::err_main_global_variable); 6295 6296 // In C, and external-linkage variable named main results in undefined 6297 // behavior. 6298 else if (NewVD->hasExternalFormalLinkage()) 6299 Diag(D.getLocStart(), diag::warn_main_redefined); 6300 } 6301 6302 if (D.isRedeclaration() && !Previous.empty()) { 6303 checkDLLAttributeRedeclaration( 6304 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6305 IsExplicitSpecialization); 6306 } 6307 6308 if (NewTemplate) { 6309 if (NewVD->isInvalidDecl()) 6310 NewTemplate->setInvalidDecl(); 6311 ActOnDocumentableDecl(NewTemplate); 6312 return NewTemplate; 6313 } 6314 6315 return NewVD; 6316 } 6317 6318 /// \brief Diagnose variable or built-in function shadowing. Implements 6319 /// -Wshadow. 6320 /// 6321 /// This method is called whenever a VarDecl is added to a "useful" 6322 /// scope. 6323 /// 6324 /// \param S the scope in which the shadowing name is being declared 6325 /// \param R the lookup of the name 6326 /// 6327 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6328 // Return if warning is ignored. 6329 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6330 return; 6331 6332 // Don't diagnose declarations at file scope. 6333 if (D->hasGlobalStorage()) 6334 return; 6335 6336 DeclContext *NewDC = D->getDeclContext(); 6337 6338 // Only diagnose if we're shadowing an unambiguous field or variable. 6339 if (R.getResultKind() != LookupResult::Found) 6340 return; 6341 6342 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6343 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6344 return; 6345 6346 // Fields are not shadowed by variables in C++ static methods. 6347 if (isa<FieldDecl>(ShadowedDecl)) 6348 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6349 if (MD->isStatic()) 6350 return; 6351 6352 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6353 if (shadowedVar->isExternC()) { 6354 // For shadowing external vars, make sure that we point to the global 6355 // declaration, not a locally scoped extern declaration. 6356 for (auto I : shadowedVar->redecls()) 6357 if (I->isFileVarDecl()) { 6358 ShadowedDecl = I; 6359 break; 6360 } 6361 } 6362 6363 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6364 6365 // Only warn about certain kinds of shadowing for class members. 6366 if (NewDC && NewDC->isRecord()) { 6367 // In particular, don't warn about shadowing non-class members. 6368 if (!OldDC->isRecord()) 6369 return; 6370 6371 // TODO: should we warn about static data members shadowing 6372 // static data members from base classes? 6373 6374 // TODO: don't diagnose for inaccessible shadowed members. 6375 // This is hard to do perfectly because we might friend the 6376 // shadowing context, but that's just a false negative. 6377 } 6378 6379 // Determine what kind of declaration we're shadowing. 6380 unsigned Kind; 6381 if (isa<RecordDecl>(OldDC)) { 6382 if (isa<FieldDecl>(ShadowedDecl)) 6383 Kind = 3; // field 6384 else 6385 Kind = 2; // static data member 6386 } else if (OldDC->isFileContext()) 6387 Kind = 1; // global 6388 else 6389 Kind = 0; // local 6390 6391 DeclarationName Name = R.getLookupName(); 6392 6393 // Emit warning and note. 6394 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6395 return; 6396 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6397 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6398 } 6399 6400 /// \brief Check -Wshadow without the advantage of a previous lookup. 6401 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6402 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6403 return; 6404 6405 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6406 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6407 LookupName(R, S); 6408 CheckShadow(S, D, R); 6409 } 6410 6411 /// Check for conflict between this global or extern "C" declaration and 6412 /// previous global or extern "C" declarations. This is only used in C++. 6413 template<typename T> 6414 static bool checkGlobalOrExternCConflict( 6415 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6416 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6417 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6418 6419 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6420 // The common case: this global doesn't conflict with any extern "C" 6421 // declaration. 6422 return false; 6423 } 6424 6425 if (Prev) { 6426 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6427 // Both the old and new declarations have C language linkage. This is a 6428 // redeclaration. 6429 Previous.clear(); 6430 Previous.addDecl(Prev); 6431 return true; 6432 } 6433 6434 // This is a global, non-extern "C" declaration, and there is a previous 6435 // non-global extern "C" declaration. Diagnose if this is a variable 6436 // declaration. 6437 if (!isa<VarDecl>(ND)) 6438 return false; 6439 } else { 6440 // The declaration is extern "C". Check for any declaration in the 6441 // translation unit which might conflict. 6442 if (IsGlobal) { 6443 // We have already performed the lookup into the translation unit. 6444 IsGlobal = false; 6445 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6446 I != E; ++I) { 6447 if (isa<VarDecl>(*I)) { 6448 Prev = *I; 6449 break; 6450 } 6451 } 6452 } else { 6453 DeclContext::lookup_result R = 6454 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6455 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6456 I != E; ++I) { 6457 if (isa<VarDecl>(*I)) { 6458 Prev = *I; 6459 break; 6460 } 6461 // FIXME: If we have any other entity with this name in global scope, 6462 // the declaration is ill-formed, but that is a defect: it breaks the 6463 // 'stat' hack, for instance. Only variables can have mangled name 6464 // clashes with extern "C" declarations, so only they deserve a 6465 // diagnostic. 6466 } 6467 } 6468 6469 if (!Prev) 6470 return false; 6471 } 6472 6473 // Use the first declaration's location to ensure we point at something which 6474 // is lexically inside an extern "C" linkage-spec. 6475 assert(Prev && "should have found a previous declaration to diagnose"); 6476 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6477 Prev = FD->getFirstDecl(); 6478 else 6479 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6480 6481 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6482 << IsGlobal << ND; 6483 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6484 << IsGlobal; 6485 return false; 6486 } 6487 6488 /// Apply special rules for handling extern "C" declarations. Returns \c true 6489 /// if we have found that this is a redeclaration of some prior entity. 6490 /// 6491 /// Per C++ [dcl.link]p6: 6492 /// Two declarations [for a function or variable] with C language linkage 6493 /// with the same name that appear in different scopes refer to the same 6494 /// [entity]. An entity with C language linkage shall not be declared with 6495 /// the same name as an entity in global scope. 6496 template<typename T> 6497 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6498 LookupResult &Previous) { 6499 if (!S.getLangOpts().CPlusPlus) { 6500 // In C, when declaring a global variable, look for a corresponding 'extern' 6501 // variable declared in function scope. We don't need this in C++, because 6502 // we find local extern decls in the surrounding file-scope DeclContext. 6503 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6504 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6505 Previous.clear(); 6506 Previous.addDecl(Prev); 6507 return true; 6508 } 6509 } 6510 return false; 6511 } 6512 6513 // A declaration in the translation unit can conflict with an extern "C" 6514 // declaration. 6515 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6516 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6517 6518 // An extern "C" declaration can conflict with a declaration in the 6519 // translation unit or can be a redeclaration of an extern "C" declaration 6520 // in another scope. 6521 if (isIncompleteDeclExternC(S,ND)) 6522 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6523 6524 // Neither global nor extern "C": nothing to do. 6525 return false; 6526 } 6527 6528 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6529 // If the decl is already known invalid, don't check it. 6530 if (NewVD->isInvalidDecl()) 6531 return; 6532 6533 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6534 QualType T = TInfo->getType(); 6535 6536 // Defer checking an 'auto' type until its initializer is attached. 6537 if (T->isUndeducedType()) 6538 return; 6539 6540 if (NewVD->hasAttrs()) 6541 CheckAlignasUnderalignment(NewVD); 6542 6543 if (T->isObjCObjectType()) { 6544 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6545 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6546 T = Context.getObjCObjectPointerType(T); 6547 NewVD->setType(T); 6548 } 6549 6550 // Emit an error if an address space was applied to decl with local storage. 6551 // This includes arrays of objects with address space qualifiers, but not 6552 // automatic variables that point to other address spaces. 6553 // ISO/IEC TR 18037 S5.1.2 6554 if (!getLangOpts().OpenCL 6555 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6556 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6557 NewVD->setInvalidDecl(); 6558 return; 6559 } 6560 6561 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6562 // scope. 6563 if (getLangOpts().OpenCLVersion == 120 && 6564 !getOpenCLOptions().cl_clang_storage_class_specifiers && 6565 NewVD->isStaticLocal()) { 6566 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6567 NewVD->setInvalidDecl(); 6568 return; 6569 } 6570 6571 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6572 // __constant address space. 6573 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6574 // variables inside a function can also be declared in the global 6575 // address space. 6576 if (getLangOpts().OpenCL) { 6577 if (NewVD->isFileVarDecl()) { 6578 if (!T->isSamplerT() && 6579 !(T.getAddressSpace() == LangAS::opencl_constant || 6580 (T.getAddressSpace() == LangAS::opencl_global && 6581 getLangOpts().OpenCLVersion == 200))) { 6582 if (getLangOpts().OpenCLVersion == 200) 6583 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6584 << "global or constant"; 6585 else 6586 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6587 << "constant"; 6588 NewVD->setInvalidDecl(); 6589 return; 6590 } 6591 } else { 6592 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6593 // variables inside a function can also be declared in the global 6594 // address space. 6595 if (NewVD->isStaticLocal() && 6596 !(T.getAddressSpace() == LangAS::opencl_constant || 6597 (T.getAddressSpace() == LangAS::opencl_global && 6598 getLangOpts().OpenCLVersion == 200))) { 6599 if (getLangOpts().OpenCLVersion == 200) 6600 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6601 << "global or constant"; 6602 else 6603 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6604 << "constant"; 6605 NewVD->setInvalidDecl(); 6606 return; 6607 } 6608 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 6609 // in functions. 6610 if (T.getAddressSpace() == LangAS::opencl_constant || 6611 T.getAddressSpace() == LangAS::opencl_local) { 6612 FunctionDecl *FD = getCurFunctionDecl(); 6613 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 6614 if (T.getAddressSpace() == LangAS::opencl_constant) 6615 Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable) 6616 << "constant"; 6617 else 6618 Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable) 6619 << "local"; 6620 NewVD->setInvalidDecl(); 6621 return; 6622 } 6623 } 6624 } 6625 } 6626 6627 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6628 && !NewVD->hasAttr<BlocksAttr>()) { 6629 if (getLangOpts().getGC() != LangOptions::NonGC) 6630 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6631 else { 6632 assert(!getLangOpts().ObjCAutoRefCount); 6633 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6634 } 6635 } 6636 6637 bool isVM = T->isVariablyModifiedType(); 6638 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6639 NewVD->hasAttr<BlocksAttr>()) 6640 getCurFunction()->setHasBranchProtectedScope(); 6641 6642 if ((isVM && NewVD->hasLinkage()) || 6643 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6644 bool SizeIsNegative; 6645 llvm::APSInt Oversized; 6646 TypeSourceInfo *FixedTInfo = 6647 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6648 SizeIsNegative, Oversized); 6649 if (!FixedTInfo && T->isVariableArrayType()) { 6650 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6651 // FIXME: This won't give the correct result for 6652 // int a[10][n]; 6653 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6654 6655 if (NewVD->isFileVarDecl()) 6656 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6657 << SizeRange; 6658 else if (NewVD->isStaticLocal()) 6659 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6660 << SizeRange; 6661 else 6662 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6663 << SizeRange; 6664 NewVD->setInvalidDecl(); 6665 return; 6666 } 6667 6668 if (!FixedTInfo) { 6669 if (NewVD->isFileVarDecl()) 6670 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6671 else 6672 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6673 NewVD->setInvalidDecl(); 6674 return; 6675 } 6676 6677 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6678 NewVD->setType(FixedTInfo->getType()); 6679 NewVD->setTypeSourceInfo(FixedTInfo); 6680 } 6681 6682 if (T->isVoidType()) { 6683 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6684 // of objects and functions. 6685 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6686 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6687 << T; 6688 NewVD->setInvalidDecl(); 6689 return; 6690 } 6691 } 6692 6693 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6694 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6695 NewVD->setInvalidDecl(); 6696 return; 6697 } 6698 6699 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6700 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6701 NewVD->setInvalidDecl(); 6702 return; 6703 } 6704 6705 if (NewVD->isConstexpr() && !T->isDependentType() && 6706 RequireLiteralType(NewVD->getLocation(), T, 6707 diag::err_constexpr_var_non_literal)) { 6708 NewVD->setInvalidDecl(); 6709 return; 6710 } 6711 } 6712 6713 /// \brief Perform semantic checking on a newly-created variable 6714 /// declaration. 6715 /// 6716 /// This routine performs all of the type-checking required for a 6717 /// variable declaration once it has been built. It is used both to 6718 /// check variables after they have been parsed and their declarators 6719 /// have been translated into a declaration, and to check variables 6720 /// that have been instantiated from a template. 6721 /// 6722 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6723 /// 6724 /// Returns true if the variable declaration is a redeclaration. 6725 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6726 CheckVariableDeclarationType(NewVD); 6727 6728 // If the decl is already known invalid, don't check it. 6729 if (NewVD->isInvalidDecl()) 6730 return false; 6731 6732 // If we did not find anything by this name, look for a non-visible 6733 // extern "C" declaration with the same name. 6734 if (Previous.empty() && 6735 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6736 Previous.setShadowed(); 6737 6738 if (!Previous.empty()) { 6739 MergeVarDecl(NewVD, Previous); 6740 return true; 6741 } 6742 return false; 6743 } 6744 6745 namespace { 6746 struct FindOverriddenMethod { 6747 Sema *S; 6748 CXXMethodDecl *Method; 6749 6750 /// Member lookup function that determines whether a given C++ 6751 /// method overrides a method in a base class, to be used with 6752 /// CXXRecordDecl::lookupInBases(). 6753 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 6754 RecordDecl *BaseRecord = 6755 Specifier->getType()->getAs<RecordType>()->getDecl(); 6756 6757 DeclarationName Name = Method->getDeclName(); 6758 6759 // FIXME: Do we care about other names here too? 6760 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6761 // We really want to find the base class destructor here. 6762 QualType T = S->Context.getTypeDeclType(BaseRecord); 6763 CanQualType CT = S->Context.getCanonicalType(T); 6764 6765 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 6766 } 6767 6768 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 6769 Path.Decls = Path.Decls.slice(1)) { 6770 NamedDecl *D = Path.Decls.front(); 6771 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6772 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 6773 return true; 6774 } 6775 } 6776 6777 return false; 6778 } 6779 }; 6780 6781 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6782 } // end anonymous namespace 6783 6784 /// \brief Report an error regarding overriding, along with any relevant 6785 /// overriden methods. 6786 /// 6787 /// \param DiagID the primary error to report. 6788 /// \param MD the overriding method. 6789 /// \param OEK which overrides to include as notes. 6790 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6791 OverrideErrorKind OEK = OEK_All) { 6792 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6793 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6794 E = MD->end_overridden_methods(); 6795 I != E; ++I) { 6796 // This check (& the OEK parameter) could be replaced by a predicate, but 6797 // without lambdas that would be overkill. This is still nicer than writing 6798 // out the diag loop 3 times. 6799 if ((OEK == OEK_All) || 6800 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6801 (OEK == OEK_Deleted && (*I)->isDeleted())) 6802 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6803 } 6804 } 6805 6806 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6807 /// and if so, check that it's a valid override and remember it. 6808 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6809 // Look for methods in base classes that this method might override. 6810 CXXBasePaths Paths; 6811 FindOverriddenMethod FOM; 6812 FOM.Method = MD; 6813 FOM.S = this; 6814 bool hasDeletedOverridenMethods = false; 6815 bool hasNonDeletedOverridenMethods = false; 6816 bool AddedAny = false; 6817 if (DC->lookupInBases(FOM, Paths)) { 6818 for (auto *I : Paths.found_decls()) { 6819 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6820 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6821 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6822 !CheckOverridingFunctionAttributes(MD, OldMD) && 6823 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6824 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6825 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6826 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6827 AddedAny = true; 6828 } 6829 } 6830 } 6831 } 6832 6833 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6834 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6835 } 6836 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6837 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6838 } 6839 6840 return AddedAny; 6841 } 6842 6843 namespace { 6844 // Struct for holding all of the extra arguments needed by 6845 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6846 struct ActOnFDArgs { 6847 Scope *S; 6848 Declarator &D; 6849 MultiTemplateParamsArg TemplateParamLists; 6850 bool AddToScope; 6851 }; 6852 } // end anonymous namespace 6853 6854 namespace { 6855 6856 // Callback to only accept typo corrections that have a non-zero edit distance. 6857 // Also only accept corrections that have the same parent decl. 6858 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6859 public: 6860 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6861 CXXRecordDecl *Parent) 6862 : Context(Context), OriginalFD(TypoFD), 6863 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6864 6865 bool ValidateCandidate(const TypoCorrection &candidate) override { 6866 if (candidate.getEditDistance() == 0) 6867 return false; 6868 6869 SmallVector<unsigned, 1> MismatchedParams; 6870 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6871 CDeclEnd = candidate.end(); 6872 CDecl != CDeclEnd; ++CDecl) { 6873 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6874 6875 if (FD && !FD->hasBody() && 6876 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6877 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6878 CXXRecordDecl *Parent = MD->getParent(); 6879 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6880 return true; 6881 } else if (!ExpectedParent) { 6882 return true; 6883 } 6884 } 6885 } 6886 6887 return false; 6888 } 6889 6890 private: 6891 ASTContext &Context; 6892 FunctionDecl *OriginalFD; 6893 CXXRecordDecl *ExpectedParent; 6894 }; 6895 6896 } // end anonymous namespace 6897 6898 /// \brief Generate diagnostics for an invalid function redeclaration. 6899 /// 6900 /// This routine handles generating the diagnostic messages for an invalid 6901 /// function redeclaration, including finding possible similar declarations 6902 /// or performing typo correction if there are no previous declarations with 6903 /// the same name. 6904 /// 6905 /// Returns a NamedDecl iff typo correction was performed and substituting in 6906 /// the new declaration name does not cause new errors. 6907 static NamedDecl *DiagnoseInvalidRedeclaration( 6908 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6909 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6910 DeclarationName Name = NewFD->getDeclName(); 6911 DeclContext *NewDC = NewFD->getDeclContext(); 6912 SmallVector<unsigned, 1> MismatchedParams; 6913 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6914 TypoCorrection Correction; 6915 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6916 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6917 : diag::err_member_decl_does_not_match; 6918 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6919 IsLocalFriend ? Sema::LookupLocalFriendName 6920 : Sema::LookupOrdinaryName, 6921 Sema::ForRedeclaration); 6922 6923 NewFD->setInvalidDecl(); 6924 if (IsLocalFriend) 6925 SemaRef.LookupName(Prev, S); 6926 else 6927 SemaRef.LookupQualifiedName(Prev, NewDC); 6928 assert(!Prev.isAmbiguous() && 6929 "Cannot have an ambiguity in previous-declaration lookup"); 6930 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6931 if (!Prev.empty()) { 6932 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6933 Func != FuncEnd; ++Func) { 6934 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6935 if (FD && 6936 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6937 // Add 1 to the index so that 0 can mean the mismatch didn't 6938 // involve a parameter 6939 unsigned ParamNum = 6940 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6941 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6942 } 6943 } 6944 // If the qualified name lookup yielded nothing, try typo correction 6945 } else if ((Correction = SemaRef.CorrectTypo( 6946 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6947 &ExtraArgs.D.getCXXScopeSpec(), 6948 llvm::make_unique<DifferentNameValidatorCCC>( 6949 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 6950 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6951 // Set up everything for the call to ActOnFunctionDeclarator 6952 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6953 ExtraArgs.D.getIdentifierLoc()); 6954 Previous.clear(); 6955 Previous.setLookupName(Correction.getCorrection()); 6956 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6957 CDeclEnd = Correction.end(); 6958 CDecl != CDeclEnd; ++CDecl) { 6959 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6960 if (FD && !FD->hasBody() && 6961 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6962 Previous.addDecl(FD); 6963 } 6964 } 6965 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6966 6967 NamedDecl *Result; 6968 // Retry building the function declaration with the new previous 6969 // declarations, and with errors suppressed. 6970 { 6971 // Trap errors. 6972 Sema::SFINAETrap Trap(SemaRef); 6973 6974 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6975 // pieces need to verify the typo-corrected C++ declaration and hopefully 6976 // eliminate the need for the parameter pack ExtraArgs. 6977 Result = SemaRef.ActOnFunctionDeclarator( 6978 ExtraArgs.S, ExtraArgs.D, 6979 Correction.getCorrectionDecl()->getDeclContext(), 6980 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6981 ExtraArgs.AddToScope); 6982 6983 if (Trap.hasErrorOccurred()) 6984 Result = nullptr; 6985 } 6986 6987 if (Result) { 6988 // Determine which correction we picked. 6989 Decl *Canonical = Result->getCanonicalDecl(); 6990 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6991 I != E; ++I) 6992 if ((*I)->getCanonicalDecl() == Canonical) 6993 Correction.setCorrectionDecl(*I); 6994 6995 SemaRef.diagnoseTypo( 6996 Correction, 6997 SemaRef.PDiag(IsLocalFriend 6998 ? diag::err_no_matching_local_friend_suggest 6999 : diag::err_member_decl_does_not_match_suggest) 7000 << Name << NewDC << IsDefinition); 7001 return Result; 7002 } 7003 7004 // Pretend the typo correction never occurred 7005 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7006 ExtraArgs.D.getIdentifierLoc()); 7007 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7008 Previous.clear(); 7009 Previous.setLookupName(Name); 7010 } 7011 7012 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7013 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7014 7015 bool NewFDisConst = false; 7016 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7017 NewFDisConst = NewMD->isConst(); 7018 7019 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7020 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7021 NearMatch != NearMatchEnd; ++NearMatch) { 7022 FunctionDecl *FD = NearMatch->first; 7023 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7024 bool FDisConst = MD && MD->isConst(); 7025 bool IsMember = MD || !IsLocalFriend; 7026 7027 // FIXME: These notes are poorly worded for the local friend case. 7028 if (unsigned Idx = NearMatch->second) { 7029 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7030 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7031 if (Loc.isInvalid()) Loc = FD->getLocation(); 7032 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7033 : diag::note_local_decl_close_param_match) 7034 << Idx << FDParam->getType() 7035 << NewFD->getParamDecl(Idx - 1)->getType(); 7036 } else if (FDisConst != NewFDisConst) { 7037 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7038 << NewFDisConst << FD->getSourceRange().getEnd(); 7039 } else 7040 SemaRef.Diag(FD->getLocation(), 7041 IsMember ? diag::note_member_def_close_match 7042 : diag::note_local_decl_close_match); 7043 } 7044 return nullptr; 7045 } 7046 7047 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7048 switch (D.getDeclSpec().getStorageClassSpec()) { 7049 default: llvm_unreachable("Unknown storage class!"); 7050 case DeclSpec::SCS_auto: 7051 case DeclSpec::SCS_register: 7052 case DeclSpec::SCS_mutable: 7053 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7054 diag::err_typecheck_sclass_func); 7055 D.setInvalidType(); 7056 break; 7057 case DeclSpec::SCS_unspecified: break; 7058 case DeclSpec::SCS_extern: 7059 if (D.getDeclSpec().isExternInLinkageSpec()) 7060 return SC_None; 7061 return SC_Extern; 7062 case DeclSpec::SCS_static: { 7063 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7064 // C99 6.7.1p5: 7065 // The declaration of an identifier for a function that has 7066 // block scope shall have no explicit storage-class specifier 7067 // other than extern 7068 // See also (C++ [dcl.stc]p4). 7069 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7070 diag::err_static_block_func); 7071 break; 7072 } else 7073 return SC_Static; 7074 } 7075 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7076 } 7077 7078 // No explicit storage class has already been returned 7079 return SC_None; 7080 } 7081 7082 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7083 DeclContext *DC, QualType &R, 7084 TypeSourceInfo *TInfo, 7085 StorageClass SC, 7086 bool &IsVirtualOkay) { 7087 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7088 DeclarationName Name = NameInfo.getName(); 7089 7090 FunctionDecl *NewFD = nullptr; 7091 bool isInline = D.getDeclSpec().isInlineSpecified(); 7092 7093 if (!SemaRef.getLangOpts().CPlusPlus) { 7094 // Determine whether the function was written with a 7095 // prototype. This true when: 7096 // - there is a prototype in the declarator, or 7097 // - the type R of the function is some kind of typedef or other reference 7098 // to a type name (which eventually refers to a function type). 7099 bool HasPrototype = 7100 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7101 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7102 7103 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7104 D.getLocStart(), NameInfo, R, 7105 TInfo, SC, isInline, 7106 HasPrototype, false); 7107 if (D.isInvalidType()) 7108 NewFD->setInvalidDecl(); 7109 7110 return NewFD; 7111 } 7112 7113 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7114 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7115 7116 // Check that the return type is not an abstract class type. 7117 // For record types, this is done by the AbstractClassUsageDiagnoser once 7118 // the class has been completely parsed. 7119 if (!DC->isRecord() && 7120 SemaRef.RequireNonAbstractType( 7121 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7122 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7123 D.setInvalidType(); 7124 7125 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7126 // This is a C++ constructor declaration. 7127 assert(DC->isRecord() && 7128 "Constructors can only be declared in a member context"); 7129 7130 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7131 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7132 D.getLocStart(), NameInfo, 7133 R, TInfo, isExplicit, isInline, 7134 /*isImplicitlyDeclared=*/false, 7135 isConstexpr); 7136 7137 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7138 // This is a C++ destructor declaration. 7139 if (DC->isRecord()) { 7140 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7141 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7142 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7143 SemaRef.Context, Record, 7144 D.getLocStart(), 7145 NameInfo, R, TInfo, isInline, 7146 /*isImplicitlyDeclared=*/false); 7147 7148 // If the class is complete, then we now create the implicit exception 7149 // specification. If the class is incomplete or dependent, we can't do 7150 // it yet. 7151 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7152 Record->getDefinition() && !Record->isBeingDefined() && 7153 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7154 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7155 } 7156 7157 IsVirtualOkay = true; 7158 return NewDD; 7159 7160 } else { 7161 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7162 D.setInvalidType(); 7163 7164 // Create a FunctionDecl to satisfy the function definition parsing 7165 // code path. 7166 return FunctionDecl::Create(SemaRef.Context, DC, 7167 D.getLocStart(), 7168 D.getIdentifierLoc(), Name, R, TInfo, 7169 SC, isInline, 7170 /*hasPrototype=*/true, isConstexpr); 7171 } 7172 7173 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7174 if (!DC->isRecord()) { 7175 SemaRef.Diag(D.getIdentifierLoc(), 7176 diag::err_conv_function_not_member); 7177 return nullptr; 7178 } 7179 7180 SemaRef.CheckConversionDeclarator(D, R, SC); 7181 IsVirtualOkay = true; 7182 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7183 D.getLocStart(), NameInfo, 7184 R, TInfo, isInline, isExplicit, 7185 isConstexpr, SourceLocation()); 7186 7187 } else if (DC->isRecord()) { 7188 // If the name of the function is the same as the name of the record, 7189 // then this must be an invalid constructor that has a return type. 7190 // (The parser checks for a return type and makes the declarator a 7191 // constructor if it has no return type). 7192 if (Name.getAsIdentifierInfo() && 7193 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7194 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7195 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7196 << SourceRange(D.getIdentifierLoc()); 7197 return nullptr; 7198 } 7199 7200 // This is a C++ method declaration. 7201 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7202 cast<CXXRecordDecl>(DC), 7203 D.getLocStart(), NameInfo, R, 7204 TInfo, SC, isInline, 7205 isConstexpr, SourceLocation()); 7206 IsVirtualOkay = !Ret->isStatic(); 7207 return Ret; 7208 } else { 7209 bool isFriend = 7210 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7211 if (!isFriend && SemaRef.CurContext->isRecord()) 7212 return nullptr; 7213 7214 // Determine whether the function was written with a 7215 // prototype. This true when: 7216 // - we're in C++ (where every function has a prototype), 7217 return FunctionDecl::Create(SemaRef.Context, DC, 7218 D.getLocStart(), 7219 NameInfo, R, TInfo, SC, isInline, 7220 true/*HasPrototype*/, isConstexpr); 7221 } 7222 } 7223 7224 enum OpenCLParamType { 7225 ValidKernelParam, 7226 PtrPtrKernelParam, 7227 PtrKernelParam, 7228 PrivatePtrKernelParam, 7229 InvalidKernelParam, 7230 RecordKernelParam 7231 }; 7232 7233 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 7234 if (PT->isPointerType()) { 7235 QualType PointeeType = PT->getPointeeType(); 7236 if (PointeeType->isPointerType()) 7237 return PtrPtrKernelParam; 7238 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 7239 : PtrKernelParam; 7240 } 7241 7242 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7243 // be used as builtin types. 7244 7245 if (PT->isImageType()) 7246 return PtrKernelParam; 7247 7248 if (PT->isBooleanType()) 7249 return InvalidKernelParam; 7250 7251 if (PT->isEventT()) 7252 return InvalidKernelParam; 7253 7254 if (PT->isHalfType()) 7255 return InvalidKernelParam; 7256 7257 if (PT->isRecordType()) 7258 return RecordKernelParam; 7259 7260 return ValidKernelParam; 7261 } 7262 7263 static void checkIsValidOpenCLKernelParameter( 7264 Sema &S, 7265 Declarator &D, 7266 ParmVarDecl *Param, 7267 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7268 QualType PT = Param->getType(); 7269 7270 // Cache the valid types we encounter to avoid rechecking structs that are 7271 // used again 7272 if (ValidTypes.count(PT.getTypePtr())) 7273 return; 7274 7275 switch (getOpenCLKernelParameterType(PT)) { 7276 case PtrPtrKernelParam: 7277 // OpenCL v1.2 s6.9.a: 7278 // A kernel function argument cannot be declared as a 7279 // pointer to a pointer type. 7280 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7281 D.setInvalidType(); 7282 return; 7283 7284 case PrivatePtrKernelParam: 7285 // OpenCL v1.2 s6.9.a: 7286 // A kernel function argument cannot be declared as a 7287 // pointer to the private address space. 7288 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 7289 D.setInvalidType(); 7290 return; 7291 7292 // OpenCL v1.2 s6.9.k: 7293 // Arguments to kernel functions in a program cannot be declared with the 7294 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7295 // uintptr_t or a struct and/or union that contain fields declared to be 7296 // one of these built-in scalar types. 7297 7298 case InvalidKernelParam: 7299 // OpenCL v1.2 s6.8 n: 7300 // A kernel function argument cannot be declared 7301 // of event_t type. 7302 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7303 D.setInvalidType(); 7304 return; 7305 7306 case PtrKernelParam: 7307 case ValidKernelParam: 7308 ValidTypes.insert(PT.getTypePtr()); 7309 return; 7310 7311 case RecordKernelParam: 7312 break; 7313 } 7314 7315 // Track nested structs we will inspect 7316 SmallVector<const Decl *, 4> VisitStack; 7317 7318 // Track where we are in the nested structs. Items will migrate from 7319 // VisitStack to HistoryStack as we do the DFS for bad field. 7320 SmallVector<const FieldDecl *, 4> HistoryStack; 7321 HistoryStack.push_back(nullptr); 7322 7323 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7324 VisitStack.push_back(PD); 7325 7326 assert(VisitStack.back() && "First decl null?"); 7327 7328 do { 7329 const Decl *Next = VisitStack.pop_back_val(); 7330 if (!Next) { 7331 assert(!HistoryStack.empty()); 7332 // Found a marker, we have gone up a level 7333 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7334 ValidTypes.insert(Hist->getType().getTypePtr()); 7335 7336 continue; 7337 } 7338 7339 // Adds everything except the original parameter declaration (which is not a 7340 // field itself) to the history stack. 7341 const RecordDecl *RD; 7342 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7343 HistoryStack.push_back(Field); 7344 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7345 } else { 7346 RD = cast<RecordDecl>(Next); 7347 } 7348 7349 // Add a null marker so we know when we've gone back up a level 7350 VisitStack.push_back(nullptr); 7351 7352 for (const auto *FD : RD->fields()) { 7353 QualType QT = FD->getType(); 7354 7355 if (ValidTypes.count(QT.getTypePtr())) 7356 continue; 7357 7358 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 7359 if (ParamType == ValidKernelParam) 7360 continue; 7361 7362 if (ParamType == RecordKernelParam) { 7363 VisitStack.push_back(FD); 7364 continue; 7365 } 7366 7367 // OpenCL v1.2 s6.9.p: 7368 // Arguments to kernel functions that are declared to be a struct or union 7369 // do not allow OpenCL objects to be passed as elements of the struct or 7370 // union. 7371 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7372 ParamType == PrivatePtrKernelParam) { 7373 S.Diag(Param->getLocation(), 7374 diag::err_record_with_pointers_kernel_param) 7375 << PT->isUnionType() 7376 << PT; 7377 } else { 7378 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7379 } 7380 7381 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7382 << PD->getDeclName(); 7383 7384 // We have an error, now let's go back up through history and show where 7385 // the offending field came from 7386 for (ArrayRef<const FieldDecl *>::const_iterator 7387 I = HistoryStack.begin() + 1, 7388 E = HistoryStack.end(); 7389 I != E; ++I) { 7390 const FieldDecl *OuterField = *I; 7391 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7392 << OuterField->getType(); 7393 } 7394 7395 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7396 << QT->isPointerType() 7397 << QT; 7398 D.setInvalidType(); 7399 return; 7400 } 7401 } while (!VisitStack.empty()); 7402 } 7403 7404 NamedDecl* 7405 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7406 TypeSourceInfo *TInfo, LookupResult &Previous, 7407 MultiTemplateParamsArg TemplateParamLists, 7408 bool &AddToScope) { 7409 QualType R = TInfo->getType(); 7410 7411 assert(R.getTypePtr()->isFunctionType()); 7412 7413 // TODO: consider using NameInfo for diagnostic. 7414 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7415 DeclarationName Name = NameInfo.getName(); 7416 StorageClass SC = getFunctionStorageClass(*this, D); 7417 7418 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7419 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7420 diag::err_invalid_thread) 7421 << DeclSpec::getSpecifierName(TSCS); 7422 7423 if (D.isFirstDeclarationOfMember()) 7424 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7425 D.getIdentifierLoc()); 7426 7427 bool isFriend = false; 7428 FunctionTemplateDecl *FunctionTemplate = nullptr; 7429 bool isExplicitSpecialization = false; 7430 bool isFunctionTemplateSpecialization = false; 7431 7432 bool isDependentClassScopeExplicitSpecialization = false; 7433 bool HasExplicitTemplateArgs = false; 7434 TemplateArgumentListInfo TemplateArgs; 7435 7436 bool isVirtualOkay = false; 7437 7438 DeclContext *OriginalDC = DC; 7439 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7440 7441 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7442 isVirtualOkay); 7443 if (!NewFD) return nullptr; 7444 7445 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7446 NewFD->setTopLevelDeclInObjCContainer(); 7447 7448 // Set the lexical context. If this is a function-scope declaration, or has a 7449 // C++ scope specifier, or is the object of a friend declaration, the lexical 7450 // context will be different from the semantic context. 7451 NewFD->setLexicalDeclContext(CurContext); 7452 7453 if (IsLocalExternDecl) 7454 NewFD->setLocalExternDecl(); 7455 7456 if (getLangOpts().CPlusPlus) { 7457 bool isInline = D.getDeclSpec().isInlineSpecified(); 7458 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7459 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7460 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7461 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7462 isFriend = D.getDeclSpec().isFriendSpecified(); 7463 if (isFriend && !isInline && D.isFunctionDefinition()) { 7464 // C++ [class.friend]p5 7465 // A function can be defined in a friend declaration of a 7466 // class . . . . Such a function is implicitly inline. 7467 NewFD->setImplicitlyInline(); 7468 } 7469 7470 // If this is a method defined in an __interface, and is not a constructor 7471 // or an overloaded operator, then set the pure flag (isVirtual will already 7472 // return true). 7473 if (const CXXRecordDecl *Parent = 7474 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7475 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7476 NewFD->setPure(true); 7477 7478 // C++ [class.union]p2 7479 // A union can have member functions, but not virtual functions. 7480 if (isVirtual && Parent->isUnion()) 7481 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7482 } 7483 7484 SetNestedNameSpecifier(NewFD, D); 7485 isExplicitSpecialization = false; 7486 isFunctionTemplateSpecialization = false; 7487 if (D.isInvalidType()) 7488 NewFD->setInvalidDecl(); 7489 7490 // Match up the template parameter lists with the scope specifier, then 7491 // determine whether we have a template or a template specialization. 7492 bool Invalid = false; 7493 if (TemplateParameterList *TemplateParams = 7494 MatchTemplateParametersToScopeSpecifier( 7495 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7496 D.getCXXScopeSpec(), 7497 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7498 ? D.getName().TemplateId 7499 : nullptr, 7500 TemplateParamLists, isFriend, isExplicitSpecialization, 7501 Invalid)) { 7502 if (TemplateParams->size() > 0) { 7503 // This is a function template 7504 7505 // Check that we can declare a template here. 7506 if (CheckTemplateDeclScope(S, TemplateParams)) 7507 NewFD->setInvalidDecl(); 7508 7509 // A destructor cannot be a template. 7510 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7511 Diag(NewFD->getLocation(), diag::err_destructor_template); 7512 NewFD->setInvalidDecl(); 7513 } 7514 7515 // If we're adding a template to a dependent context, we may need to 7516 // rebuilding some of the types used within the template parameter list, 7517 // now that we know what the current instantiation is. 7518 if (DC->isDependentContext()) { 7519 ContextRAII SavedContext(*this, DC); 7520 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7521 Invalid = true; 7522 } 7523 7524 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7525 NewFD->getLocation(), 7526 Name, TemplateParams, 7527 NewFD); 7528 FunctionTemplate->setLexicalDeclContext(CurContext); 7529 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7530 7531 // For source fidelity, store the other template param lists. 7532 if (TemplateParamLists.size() > 1) { 7533 NewFD->setTemplateParameterListsInfo(Context, 7534 TemplateParamLists.drop_back(1)); 7535 } 7536 } else { 7537 // This is a function template specialization. 7538 isFunctionTemplateSpecialization = true; 7539 // For source fidelity, store all the template param lists. 7540 if (TemplateParamLists.size() > 0) 7541 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7542 7543 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7544 if (isFriend) { 7545 // We want to remove the "template<>", found here. 7546 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7547 7548 // If we remove the template<> and the name is not a 7549 // template-id, we're actually silently creating a problem: 7550 // the friend declaration will refer to an untemplated decl, 7551 // and clearly the user wants a template specialization. So 7552 // we need to insert '<>' after the name. 7553 SourceLocation InsertLoc; 7554 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7555 InsertLoc = D.getName().getSourceRange().getEnd(); 7556 InsertLoc = getLocForEndOfToken(InsertLoc); 7557 } 7558 7559 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7560 << Name << RemoveRange 7561 << FixItHint::CreateRemoval(RemoveRange) 7562 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7563 } 7564 } 7565 } 7566 else { 7567 // All template param lists were matched against the scope specifier: 7568 // this is NOT (an explicit specialization of) a template. 7569 if (TemplateParamLists.size() > 0) 7570 // For source fidelity, store all the template param lists. 7571 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7572 } 7573 7574 if (Invalid) { 7575 NewFD->setInvalidDecl(); 7576 if (FunctionTemplate) 7577 FunctionTemplate->setInvalidDecl(); 7578 } 7579 7580 // C++ [dcl.fct.spec]p5: 7581 // The virtual specifier shall only be used in declarations of 7582 // nonstatic class member functions that appear within a 7583 // member-specification of a class declaration; see 10.3. 7584 // 7585 if (isVirtual && !NewFD->isInvalidDecl()) { 7586 if (!isVirtualOkay) { 7587 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7588 diag::err_virtual_non_function); 7589 } else if (!CurContext->isRecord()) { 7590 // 'virtual' was specified outside of the class. 7591 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7592 diag::err_virtual_out_of_class) 7593 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7594 } else if (NewFD->getDescribedFunctionTemplate()) { 7595 // C++ [temp.mem]p3: 7596 // A member function template shall not be virtual. 7597 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7598 diag::err_virtual_member_function_template) 7599 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7600 } else { 7601 // Okay: Add virtual to the method. 7602 NewFD->setVirtualAsWritten(true); 7603 } 7604 7605 if (getLangOpts().CPlusPlus14 && 7606 NewFD->getReturnType()->isUndeducedType()) 7607 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7608 } 7609 7610 if (getLangOpts().CPlusPlus14 && 7611 (NewFD->isDependentContext() || 7612 (isFriend && CurContext->isDependentContext())) && 7613 NewFD->getReturnType()->isUndeducedType()) { 7614 // If the function template is referenced directly (for instance, as a 7615 // member of the current instantiation), pretend it has a dependent type. 7616 // This is not really justified by the standard, but is the only sane 7617 // thing to do. 7618 // FIXME: For a friend function, we have not marked the function as being 7619 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7620 const FunctionProtoType *FPT = 7621 NewFD->getType()->castAs<FunctionProtoType>(); 7622 QualType Result = 7623 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7624 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7625 FPT->getExtProtoInfo())); 7626 } 7627 7628 // C++ [dcl.fct.spec]p3: 7629 // The inline specifier shall not appear on a block scope function 7630 // declaration. 7631 if (isInline && !NewFD->isInvalidDecl()) { 7632 if (CurContext->isFunctionOrMethod()) { 7633 // 'inline' is not allowed on block scope function declaration. 7634 Diag(D.getDeclSpec().getInlineSpecLoc(), 7635 diag::err_inline_declaration_block_scope) << Name 7636 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7637 } 7638 } 7639 7640 // C++ [dcl.fct.spec]p6: 7641 // The explicit specifier shall be used only in the declaration of a 7642 // constructor or conversion function within its class definition; 7643 // see 12.3.1 and 12.3.2. 7644 if (isExplicit && !NewFD->isInvalidDecl()) { 7645 if (!CurContext->isRecord()) { 7646 // 'explicit' was specified outside of the class. 7647 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7648 diag::err_explicit_out_of_class) 7649 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7650 } else if (!isa<CXXConstructorDecl>(NewFD) && 7651 !isa<CXXConversionDecl>(NewFD)) { 7652 // 'explicit' was specified on a function that wasn't a constructor 7653 // or conversion function. 7654 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7655 diag::err_explicit_non_ctor_or_conv_function) 7656 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7657 } 7658 } 7659 7660 if (isConstexpr) { 7661 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7662 // are implicitly inline. 7663 NewFD->setImplicitlyInline(); 7664 7665 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7666 // be either constructors or to return a literal type. Therefore, 7667 // destructors cannot be declared constexpr. 7668 if (isa<CXXDestructorDecl>(NewFD)) 7669 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7670 } 7671 7672 if (isConcept) { 7673 // This is a function concept. 7674 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 7675 FTD->setConcept(); 7676 7677 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7678 // applied only to the definition of a function template [...] 7679 if (!D.isFunctionDefinition()) { 7680 Diag(D.getDeclSpec().getConceptSpecLoc(), 7681 diag::err_function_concept_not_defined); 7682 NewFD->setInvalidDecl(); 7683 } 7684 7685 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 7686 // have no exception-specification and is treated as if it were specified 7687 // with noexcept(true) (15.4). [...] 7688 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 7689 if (FPT->hasExceptionSpec()) { 7690 SourceRange Range; 7691 if (D.isFunctionDeclarator()) 7692 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 7693 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 7694 << FixItHint::CreateRemoval(Range); 7695 NewFD->setInvalidDecl(); 7696 } else { 7697 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 7698 } 7699 7700 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 7701 // following restrictions: 7702 // - The declared return type shall have the type bool. 7703 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 7704 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 7705 NewFD->setInvalidDecl(); 7706 } 7707 7708 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 7709 // following restrictions: 7710 // - The declaration's parameter list shall be equivalent to an empty 7711 // parameter list. 7712 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 7713 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 7714 } 7715 7716 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 7717 // implicity defined to be a constexpr declaration (implicitly inline) 7718 NewFD->setImplicitlyInline(); 7719 7720 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 7721 // be declared with the thread_local, inline, friend, or constexpr 7722 // specifiers, [...] 7723 if (isInline) { 7724 Diag(D.getDeclSpec().getInlineSpecLoc(), 7725 diag::err_concept_decl_invalid_specifiers) 7726 << 1 << 1; 7727 NewFD->setInvalidDecl(true); 7728 } 7729 7730 if (isFriend) { 7731 Diag(D.getDeclSpec().getFriendSpecLoc(), 7732 diag::err_concept_decl_invalid_specifiers) 7733 << 1 << 2; 7734 NewFD->setInvalidDecl(true); 7735 } 7736 7737 if (isConstexpr) { 7738 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7739 diag::err_concept_decl_invalid_specifiers) 7740 << 1 << 3; 7741 NewFD->setInvalidDecl(true); 7742 } 7743 7744 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7745 // applied only to the definition of a function template or variable 7746 // template, declared in namespace scope. 7747 if (isFunctionTemplateSpecialization) { 7748 Diag(D.getDeclSpec().getConceptSpecLoc(), 7749 diag::err_concept_specified_specialization) << 1; 7750 } 7751 } 7752 7753 // If __module_private__ was specified, mark the function accordingly. 7754 if (D.getDeclSpec().isModulePrivateSpecified()) { 7755 if (isFunctionTemplateSpecialization) { 7756 SourceLocation ModulePrivateLoc 7757 = D.getDeclSpec().getModulePrivateSpecLoc(); 7758 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7759 << 0 7760 << FixItHint::CreateRemoval(ModulePrivateLoc); 7761 } else { 7762 NewFD->setModulePrivate(); 7763 if (FunctionTemplate) 7764 FunctionTemplate->setModulePrivate(); 7765 } 7766 } 7767 7768 if (isFriend) { 7769 if (FunctionTemplate) { 7770 FunctionTemplate->setObjectOfFriendDecl(); 7771 FunctionTemplate->setAccess(AS_public); 7772 } 7773 NewFD->setObjectOfFriendDecl(); 7774 NewFD->setAccess(AS_public); 7775 } 7776 7777 // If a function is defined as defaulted or deleted, mark it as such now. 7778 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7779 // definition kind to FDK_Definition. 7780 switch (D.getFunctionDefinitionKind()) { 7781 case FDK_Declaration: 7782 case FDK_Definition: 7783 break; 7784 7785 case FDK_Defaulted: 7786 NewFD->setDefaulted(); 7787 break; 7788 7789 case FDK_Deleted: 7790 NewFD->setDeletedAsWritten(); 7791 break; 7792 } 7793 7794 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7795 D.isFunctionDefinition()) { 7796 // C++ [class.mfct]p2: 7797 // A member function may be defined (8.4) in its class definition, in 7798 // which case it is an inline member function (7.1.2) 7799 NewFD->setImplicitlyInline(); 7800 } 7801 7802 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7803 !CurContext->isRecord()) { 7804 // C++ [class.static]p1: 7805 // A data or function member of a class may be declared static 7806 // in a class definition, in which case it is a static member of 7807 // the class. 7808 7809 // Complain about the 'static' specifier if it's on an out-of-line 7810 // member function definition. 7811 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7812 diag::err_static_out_of_line) 7813 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7814 } 7815 7816 // C++11 [except.spec]p15: 7817 // A deallocation function with no exception-specification is treated 7818 // as if it were specified with noexcept(true). 7819 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7820 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7821 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7822 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7823 NewFD->setType(Context.getFunctionType( 7824 FPT->getReturnType(), FPT->getParamTypes(), 7825 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7826 } 7827 7828 // Filter out previous declarations that don't match the scope. 7829 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7830 D.getCXXScopeSpec().isNotEmpty() || 7831 isExplicitSpecialization || 7832 isFunctionTemplateSpecialization); 7833 7834 // Handle GNU asm-label extension (encoded as an attribute). 7835 if (Expr *E = (Expr*) D.getAsmLabel()) { 7836 // The parser guarantees this is a string. 7837 StringLiteral *SE = cast<StringLiteral>(E); 7838 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7839 SE->getString(), 0)); 7840 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7841 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7842 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7843 if (I != ExtnameUndeclaredIdentifiers.end()) { 7844 if (isDeclExternC(NewFD)) { 7845 NewFD->addAttr(I->second); 7846 ExtnameUndeclaredIdentifiers.erase(I); 7847 } else 7848 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 7849 << /*Variable*/0 << NewFD; 7850 } 7851 } 7852 7853 // Copy the parameter declarations from the declarator D to the function 7854 // declaration NewFD, if they are available. First scavenge them into Params. 7855 SmallVector<ParmVarDecl*, 16> Params; 7856 if (D.isFunctionDeclarator()) { 7857 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7858 7859 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7860 // function that takes no arguments, not a function that takes a 7861 // single void argument. 7862 // We let through "const void" here because Sema::GetTypeForDeclarator 7863 // already checks for that case. 7864 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7865 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7866 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7867 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7868 Param->setDeclContext(NewFD); 7869 Params.push_back(Param); 7870 7871 if (Param->isInvalidDecl()) 7872 NewFD->setInvalidDecl(); 7873 } 7874 } 7875 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7876 // When we're declaring a function with a typedef, typeof, etc as in the 7877 // following example, we'll need to synthesize (unnamed) 7878 // parameters for use in the declaration. 7879 // 7880 // @code 7881 // typedef void fn(int); 7882 // fn f; 7883 // @endcode 7884 7885 // Synthesize a parameter for each argument type. 7886 for (const auto &AI : FT->param_types()) { 7887 ParmVarDecl *Param = 7888 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7889 Param->setScopeInfo(0, Params.size()); 7890 Params.push_back(Param); 7891 } 7892 } else { 7893 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7894 "Should not need args for typedef of non-prototype fn"); 7895 } 7896 7897 // Finally, we know we have the right number of parameters, install them. 7898 NewFD->setParams(Params); 7899 7900 // Find all anonymous symbols defined during the declaration of this function 7901 // and add to NewFD. This lets us track decls such 'enum Y' in: 7902 // 7903 // void f(enum Y {AA} x) {} 7904 // 7905 // which would otherwise incorrectly end up in the translation unit scope. 7906 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7907 DeclsInPrototypeScope.clear(); 7908 7909 if (D.getDeclSpec().isNoreturnSpecified()) 7910 NewFD->addAttr( 7911 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7912 Context, 0)); 7913 7914 // Functions returning a variably modified type violate C99 6.7.5.2p2 7915 // because all functions have linkage. 7916 if (!NewFD->isInvalidDecl() && 7917 NewFD->getReturnType()->isVariablyModifiedType()) { 7918 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7919 NewFD->setInvalidDecl(); 7920 } 7921 7922 // Apply an implicit SectionAttr if #pragma code_seg is active. 7923 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 7924 !NewFD->hasAttr<SectionAttr>()) { 7925 NewFD->addAttr( 7926 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7927 CodeSegStack.CurrentValue->getString(), 7928 CodeSegStack.CurrentPragmaLocation)); 7929 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7930 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 7931 ASTContext::PSF_Read, 7932 NewFD)) 7933 NewFD->dropAttr<SectionAttr>(); 7934 } 7935 7936 // Handle attributes. 7937 ProcessDeclAttributes(S, NewFD, D); 7938 7939 if (getLangOpts().OpenCL) { 7940 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7941 // type declaration will generate a compilation error. 7942 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 7943 if (AddressSpace == LangAS::opencl_local || 7944 AddressSpace == LangAS::opencl_global || 7945 AddressSpace == LangAS::opencl_constant) { 7946 Diag(NewFD->getLocation(), 7947 diag::err_opencl_return_value_with_address_space); 7948 NewFD->setInvalidDecl(); 7949 } 7950 } 7951 7952 if (!getLangOpts().CPlusPlus) { 7953 // Perform semantic checking on the function declaration. 7954 bool isExplicitSpecialization=false; 7955 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7956 CheckMain(NewFD, D.getDeclSpec()); 7957 7958 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7959 CheckMSVCRTEntryPoint(NewFD); 7960 7961 if (!NewFD->isInvalidDecl()) 7962 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7963 isExplicitSpecialization)); 7964 else if (!Previous.empty()) 7965 // Recover gracefully from an invalid redeclaration. 7966 D.setRedeclaration(true); 7967 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7968 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7969 "previous declaration set still overloaded"); 7970 7971 // Diagnose no-prototype function declarations with calling conventions that 7972 // don't support variadic calls. Only do this in C and do it after merging 7973 // possibly prototyped redeclarations. 7974 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 7975 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 7976 CallingConv CC = FT->getExtInfo().getCC(); 7977 if (!supportsVariadicCall(CC)) { 7978 // Windows system headers sometimes accidentally use stdcall without 7979 // (void) parameters, so we relax this to a warning. 7980 int DiagID = 7981 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 7982 Diag(NewFD->getLocation(), DiagID) 7983 << FunctionType::getNameForCallConv(CC); 7984 } 7985 } 7986 } else { 7987 // C++11 [replacement.functions]p3: 7988 // The program's definitions shall not be specified as inline. 7989 // 7990 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7991 // 7992 // Suppress the diagnostic if the function is __attribute__((used)), since 7993 // that forces an external definition to be emitted. 7994 if (D.getDeclSpec().isInlineSpecified() && 7995 NewFD->isReplaceableGlobalAllocationFunction() && 7996 !NewFD->hasAttr<UsedAttr>()) 7997 Diag(D.getDeclSpec().getInlineSpecLoc(), 7998 diag::ext_operator_new_delete_declared_inline) 7999 << NewFD->getDeclName(); 8000 8001 // If the declarator is a template-id, translate the parser's template 8002 // argument list into our AST format. 8003 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8004 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8005 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8006 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8007 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8008 TemplateId->NumArgs); 8009 translateTemplateArguments(TemplateArgsPtr, 8010 TemplateArgs); 8011 8012 HasExplicitTemplateArgs = true; 8013 8014 if (NewFD->isInvalidDecl()) { 8015 HasExplicitTemplateArgs = false; 8016 } else if (FunctionTemplate) { 8017 // Function template with explicit template arguments. 8018 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8019 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8020 8021 HasExplicitTemplateArgs = false; 8022 } else { 8023 assert((isFunctionTemplateSpecialization || 8024 D.getDeclSpec().isFriendSpecified()) && 8025 "should have a 'template<>' for this decl"); 8026 // "friend void foo<>(int);" is an implicit specialization decl. 8027 isFunctionTemplateSpecialization = true; 8028 } 8029 } else if (isFriend && isFunctionTemplateSpecialization) { 8030 // This combination is only possible in a recovery case; the user 8031 // wrote something like: 8032 // template <> friend void foo(int); 8033 // which we're recovering from as if the user had written: 8034 // friend void foo<>(int); 8035 // Go ahead and fake up a template id. 8036 HasExplicitTemplateArgs = true; 8037 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8038 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8039 } 8040 8041 // If it's a friend (and only if it's a friend), it's possible 8042 // that either the specialized function type or the specialized 8043 // template is dependent, and therefore matching will fail. In 8044 // this case, don't check the specialization yet. 8045 bool InstantiationDependent = false; 8046 if (isFunctionTemplateSpecialization && isFriend && 8047 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8048 TemplateSpecializationType::anyDependentTemplateArguments( 8049 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 8050 InstantiationDependent))) { 8051 assert(HasExplicitTemplateArgs && 8052 "friend function specialization without template args"); 8053 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8054 Previous)) 8055 NewFD->setInvalidDecl(); 8056 } else if (isFunctionTemplateSpecialization) { 8057 if (CurContext->isDependentContext() && CurContext->isRecord() 8058 && !isFriend) { 8059 isDependentClassScopeExplicitSpecialization = true; 8060 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8061 diag::ext_function_specialization_in_class : 8062 diag::err_function_specialization_in_class) 8063 << NewFD->getDeclName(); 8064 } else if (CheckFunctionTemplateSpecialization(NewFD, 8065 (HasExplicitTemplateArgs ? &TemplateArgs 8066 : nullptr), 8067 Previous)) 8068 NewFD->setInvalidDecl(); 8069 8070 // C++ [dcl.stc]p1: 8071 // A storage-class-specifier shall not be specified in an explicit 8072 // specialization (14.7.3) 8073 FunctionTemplateSpecializationInfo *Info = 8074 NewFD->getTemplateSpecializationInfo(); 8075 if (Info && SC != SC_None) { 8076 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8077 Diag(NewFD->getLocation(), 8078 diag::err_explicit_specialization_inconsistent_storage_class) 8079 << SC 8080 << FixItHint::CreateRemoval( 8081 D.getDeclSpec().getStorageClassSpecLoc()); 8082 8083 else 8084 Diag(NewFD->getLocation(), 8085 diag::ext_explicit_specialization_storage_class) 8086 << FixItHint::CreateRemoval( 8087 D.getDeclSpec().getStorageClassSpecLoc()); 8088 } 8089 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 8090 if (CheckMemberSpecialization(NewFD, Previous)) 8091 NewFD->setInvalidDecl(); 8092 } 8093 8094 // Perform semantic checking on the function declaration. 8095 if (!isDependentClassScopeExplicitSpecialization) { 8096 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8097 CheckMain(NewFD, D.getDeclSpec()); 8098 8099 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8100 CheckMSVCRTEntryPoint(NewFD); 8101 8102 if (!NewFD->isInvalidDecl()) 8103 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8104 isExplicitSpecialization)); 8105 else if (!Previous.empty()) 8106 // Recover gracefully from an invalid redeclaration. 8107 D.setRedeclaration(true); 8108 } 8109 8110 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8111 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8112 "previous declaration set still overloaded"); 8113 8114 NamedDecl *PrincipalDecl = (FunctionTemplate 8115 ? cast<NamedDecl>(FunctionTemplate) 8116 : NewFD); 8117 8118 if (isFriend && D.isRedeclaration()) { 8119 AccessSpecifier Access = AS_public; 8120 if (!NewFD->isInvalidDecl()) 8121 Access = NewFD->getPreviousDecl()->getAccess(); 8122 8123 NewFD->setAccess(Access); 8124 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8125 } 8126 8127 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8128 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8129 PrincipalDecl->setNonMemberOperator(); 8130 8131 // If we have a function template, check the template parameter 8132 // list. This will check and merge default template arguments. 8133 if (FunctionTemplate) { 8134 FunctionTemplateDecl *PrevTemplate = 8135 FunctionTemplate->getPreviousDecl(); 8136 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8137 PrevTemplate ? PrevTemplate->getTemplateParameters() 8138 : nullptr, 8139 D.getDeclSpec().isFriendSpecified() 8140 ? (D.isFunctionDefinition() 8141 ? TPC_FriendFunctionTemplateDefinition 8142 : TPC_FriendFunctionTemplate) 8143 : (D.getCXXScopeSpec().isSet() && 8144 DC && DC->isRecord() && 8145 DC->isDependentContext()) 8146 ? TPC_ClassTemplateMember 8147 : TPC_FunctionTemplate); 8148 } 8149 8150 if (NewFD->isInvalidDecl()) { 8151 // Ignore all the rest of this. 8152 } else if (!D.isRedeclaration()) { 8153 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8154 AddToScope }; 8155 // Fake up an access specifier if it's supposed to be a class member. 8156 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8157 NewFD->setAccess(AS_public); 8158 8159 // Qualified decls generally require a previous declaration. 8160 if (D.getCXXScopeSpec().isSet()) { 8161 // ...with the major exception of templated-scope or 8162 // dependent-scope friend declarations. 8163 8164 // TODO: we currently also suppress this check in dependent 8165 // contexts because (1) the parameter depth will be off when 8166 // matching friend templates and (2) we might actually be 8167 // selecting a friend based on a dependent factor. But there 8168 // are situations where these conditions don't apply and we 8169 // can actually do this check immediately. 8170 if (isFriend && 8171 (TemplateParamLists.size() || 8172 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8173 CurContext->isDependentContext())) { 8174 // ignore these 8175 } else { 8176 // The user tried to provide an out-of-line definition for a 8177 // function that is a member of a class or namespace, but there 8178 // was no such member function declared (C++ [class.mfct]p2, 8179 // C++ [namespace.memdef]p2). For example: 8180 // 8181 // class X { 8182 // void f() const; 8183 // }; 8184 // 8185 // void X::f() { } // ill-formed 8186 // 8187 // Complain about this problem, and attempt to suggest close 8188 // matches (e.g., those that differ only in cv-qualifiers and 8189 // whether the parameter types are references). 8190 8191 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8192 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8193 AddToScope = ExtraArgs.AddToScope; 8194 return Result; 8195 } 8196 } 8197 8198 // Unqualified local friend declarations are required to resolve 8199 // to something. 8200 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8201 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8202 *this, Previous, NewFD, ExtraArgs, true, S)) { 8203 AddToScope = ExtraArgs.AddToScope; 8204 return Result; 8205 } 8206 } 8207 } else if (!D.isFunctionDefinition() && 8208 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8209 !isFriend && !isFunctionTemplateSpecialization && 8210 !isExplicitSpecialization) { 8211 // An out-of-line member function declaration must also be a 8212 // definition (C++ [class.mfct]p2). 8213 // Note that this is not the case for explicit specializations of 8214 // function templates or member functions of class templates, per 8215 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8216 // extension for compatibility with old SWIG code which likes to 8217 // generate them. 8218 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8219 << D.getCXXScopeSpec().getRange(); 8220 } 8221 } 8222 8223 ProcessPragmaWeak(S, NewFD); 8224 checkAttributesAfterMerging(*this, *NewFD); 8225 8226 AddKnownFunctionAttributes(NewFD); 8227 8228 if (NewFD->hasAttr<OverloadableAttr>() && 8229 !NewFD->getType()->getAs<FunctionProtoType>()) { 8230 Diag(NewFD->getLocation(), 8231 diag::err_attribute_overloadable_no_prototype) 8232 << NewFD; 8233 8234 // Turn this into a variadic function with no parameters. 8235 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8236 FunctionProtoType::ExtProtoInfo EPI( 8237 Context.getDefaultCallingConvention(true, false)); 8238 EPI.Variadic = true; 8239 EPI.ExtInfo = FT->getExtInfo(); 8240 8241 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8242 NewFD->setType(R); 8243 } 8244 8245 // If there's a #pragma GCC visibility in scope, and this isn't a class 8246 // member, set the visibility of this function. 8247 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8248 AddPushedVisibilityAttribute(NewFD); 8249 8250 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8251 // marking the function. 8252 AddCFAuditedAttribute(NewFD); 8253 8254 // If this is a function definition, check if we have to apply optnone due to 8255 // a pragma. 8256 if(D.isFunctionDefinition()) 8257 AddRangeBasedOptnone(NewFD); 8258 8259 // If this is the first declaration of an extern C variable, update 8260 // the map of such variables. 8261 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8262 isIncompleteDeclExternC(*this, NewFD)) 8263 RegisterLocallyScopedExternCDecl(NewFD, S); 8264 8265 // Set this FunctionDecl's range up to the right paren. 8266 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8267 8268 if (D.isRedeclaration() && !Previous.empty()) { 8269 checkDLLAttributeRedeclaration( 8270 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8271 isExplicitSpecialization || isFunctionTemplateSpecialization); 8272 } 8273 8274 if (getLangOpts().CPlusPlus) { 8275 if (FunctionTemplate) { 8276 if (NewFD->isInvalidDecl()) 8277 FunctionTemplate->setInvalidDecl(); 8278 return FunctionTemplate; 8279 } 8280 } 8281 8282 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8283 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8284 if ((getLangOpts().OpenCLVersion >= 120) 8285 && (SC == SC_Static)) { 8286 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8287 D.setInvalidType(); 8288 } 8289 8290 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8291 if (!NewFD->getReturnType()->isVoidType()) { 8292 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8293 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8294 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8295 : FixItHint()); 8296 D.setInvalidType(); 8297 } 8298 8299 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8300 for (auto Param : NewFD->params()) 8301 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8302 } 8303 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 8304 PE = NewFD->param_end(); PI != PE; ++PI) { 8305 ParmVarDecl *Param = *PI; 8306 QualType PT = Param->getType(); 8307 8308 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8309 // types. 8310 if (getLangOpts().OpenCLVersion >= 200) { 8311 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8312 QualType ElemTy = PipeTy->getElementType(); 8313 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8314 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8315 D.setInvalidType(); 8316 } 8317 } 8318 } 8319 } 8320 8321 MarkUnusedFileScopedDecl(NewFD); 8322 8323 if (getLangOpts().CUDA) { 8324 IdentifierInfo *II = NewFD->getIdentifier(); 8325 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8326 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8327 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8328 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8329 8330 Context.setcudaConfigureCallDecl(NewFD); 8331 } 8332 8333 // Variadic functions, other than a *declaration* of printf, are not allowed 8334 // in device-side CUDA code, unless someone passed 8335 // -fcuda-allow-variadic-functions. 8336 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8337 (NewFD->hasAttr<CUDADeviceAttr>() || 8338 NewFD->hasAttr<CUDAGlobalAttr>()) && 8339 !(II && II->isStr("printf") && NewFD->isExternC() && 8340 !D.isFunctionDefinition())) { 8341 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8342 } 8343 } 8344 8345 // Here we have an function template explicit specialization at class scope. 8346 // The actually specialization will be postponed to template instatiation 8347 // time via the ClassScopeFunctionSpecializationDecl node. 8348 if (isDependentClassScopeExplicitSpecialization) { 8349 ClassScopeFunctionSpecializationDecl *NewSpec = 8350 ClassScopeFunctionSpecializationDecl::Create( 8351 Context, CurContext, SourceLocation(), 8352 cast<CXXMethodDecl>(NewFD), 8353 HasExplicitTemplateArgs, TemplateArgs); 8354 CurContext->addDecl(NewSpec); 8355 AddToScope = false; 8356 } 8357 8358 return NewFD; 8359 } 8360 8361 /// \brief Perform semantic checking of a new function declaration. 8362 /// 8363 /// Performs semantic analysis of the new function declaration 8364 /// NewFD. This routine performs all semantic checking that does not 8365 /// require the actual declarator involved in the declaration, and is 8366 /// used both for the declaration of functions as they are parsed 8367 /// (called via ActOnDeclarator) and for the declaration of functions 8368 /// that have been instantiated via C++ template instantiation (called 8369 /// via InstantiateDecl). 8370 /// 8371 /// \param IsExplicitSpecialization whether this new function declaration is 8372 /// an explicit specialization of the previous declaration. 8373 /// 8374 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8375 /// 8376 /// \returns true if the function declaration is a redeclaration. 8377 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8378 LookupResult &Previous, 8379 bool IsExplicitSpecialization) { 8380 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8381 "Variably modified return types are not handled here"); 8382 8383 // Determine whether the type of this function should be merged with 8384 // a previous visible declaration. This never happens for functions in C++, 8385 // and always happens in C if the previous declaration was visible. 8386 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8387 !Previous.isShadowed(); 8388 8389 bool Redeclaration = false; 8390 NamedDecl *OldDecl = nullptr; 8391 8392 // Merge or overload the declaration with an existing declaration of 8393 // the same name, if appropriate. 8394 if (!Previous.empty()) { 8395 // Determine whether NewFD is an overload of PrevDecl or 8396 // a declaration that requires merging. If it's an overload, 8397 // there's no more work to do here; we'll just add the new 8398 // function to the scope. 8399 if (!AllowOverloadingOfFunction(Previous, Context)) { 8400 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8401 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8402 Redeclaration = true; 8403 OldDecl = Candidate; 8404 } 8405 } else { 8406 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8407 /*NewIsUsingDecl*/ false)) { 8408 case Ovl_Match: 8409 Redeclaration = true; 8410 break; 8411 8412 case Ovl_NonFunction: 8413 Redeclaration = true; 8414 break; 8415 8416 case Ovl_Overload: 8417 Redeclaration = false; 8418 break; 8419 } 8420 8421 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8422 // If a function name is overloadable in C, then every function 8423 // with that name must be marked "overloadable". 8424 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8425 << Redeclaration << NewFD; 8426 NamedDecl *OverloadedDecl = nullptr; 8427 if (Redeclaration) 8428 OverloadedDecl = OldDecl; 8429 else if (!Previous.empty()) 8430 OverloadedDecl = Previous.getRepresentativeDecl(); 8431 if (OverloadedDecl) 8432 Diag(OverloadedDecl->getLocation(), 8433 diag::note_attribute_overloadable_prev_overload); 8434 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8435 } 8436 } 8437 } 8438 8439 // Check for a previous extern "C" declaration with this name. 8440 if (!Redeclaration && 8441 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8442 if (!Previous.empty()) { 8443 // This is an extern "C" declaration with the same name as a previous 8444 // declaration, and thus redeclares that entity... 8445 Redeclaration = true; 8446 OldDecl = Previous.getFoundDecl(); 8447 MergeTypeWithPrevious = false; 8448 8449 // ... except in the presence of __attribute__((overloadable)). 8450 if (OldDecl->hasAttr<OverloadableAttr>()) { 8451 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8452 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8453 << Redeclaration << NewFD; 8454 Diag(Previous.getFoundDecl()->getLocation(), 8455 diag::note_attribute_overloadable_prev_overload); 8456 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8457 } 8458 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8459 Redeclaration = false; 8460 OldDecl = nullptr; 8461 } 8462 } 8463 } 8464 } 8465 8466 // C++11 [dcl.constexpr]p8: 8467 // A constexpr specifier for a non-static member function that is not 8468 // a constructor declares that member function to be const. 8469 // 8470 // This needs to be delayed until we know whether this is an out-of-line 8471 // definition of a static member function. 8472 // 8473 // This rule is not present in C++1y, so we produce a backwards 8474 // compatibility warning whenever it happens in C++11. 8475 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8476 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8477 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8478 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8479 CXXMethodDecl *OldMD = nullptr; 8480 if (OldDecl) 8481 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8482 if (!OldMD || !OldMD->isStatic()) { 8483 const FunctionProtoType *FPT = 8484 MD->getType()->castAs<FunctionProtoType>(); 8485 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8486 EPI.TypeQuals |= Qualifiers::Const; 8487 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8488 FPT->getParamTypes(), EPI)); 8489 8490 // Warn that we did this, if we're not performing template instantiation. 8491 // In that case, we'll have warned already when the template was defined. 8492 if (ActiveTemplateInstantiations.empty()) { 8493 SourceLocation AddConstLoc; 8494 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8495 .IgnoreParens().getAs<FunctionTypeLoc>()) 8496 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8497 8498 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8499 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8500 } 8501 } 8502 } 8503 8504 if (Redeclaration) { 8505 // NewFD and OldDecl represent declarations that need to be 8506 // merged. 8507 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8508 NewFD->setInvalidDecl(); 8509 return Redeclaration; 8510 } 8511 8512 Previous.clear(); 8513 Previous.addDecl(OldDecl); 8514 8515 if (FunctionTemplateDecl *OldTemplateDecl 8516 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8517 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8518 FunctionTemplateDecl *NewTemplateDecl 8519 = NewFD->getDescribedFunctionTemplate(); 8520 assert(NewTemplateDecl && "Template/non-template mismatch"); 8521 if (CXXMethodDecl *Method 8522 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8523 Method->setAccess(OldTemplateDecl->getAccess()); 8524 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8525 } 8526 8527 // If this is an explicit specialization of a member that is a function 8528 // template, mark it as a member specialization. 8529 if (IsExplicitSpecialization && 8530 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8531 NewTemplateDecl->setMemberSpecialization(); 8532 assert(OldTemplateDecl->isMemberSpecialization()); 8533 } 8534 8535 } else { 8536 // This needs to happen first so that 'inline' propagates. 8537 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8538 8539 if (isa<CXXMethodDecl>(NewFD)) 8540 NewFD->setAccess(OldDecl->getAccess()); 8541 } 8542 } 8543 8544 // Semantic checking for this function declaration (in isolation). 8545 8546 if (getLangOpts().CPlusPlus) { 8547 // C++-specific checks. 8548 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8549 CheckConstructor(Constructor); 8550 } else if (CXXDestructorDecl *Destructor = 8551 dyn_cast<CXXDestructorDecl>(NewFD)) { 8552 CXXRecordDecl *Record = Destructor->getParent(); 8553 QualType ClassType = Context.getTypeDeclType(Record); 8554 8555 // FIXME: Shouldn't we be able to perform this check even when the class 8556 // type is dependent? Both gcc and edg can handle that. 8557 if (!ClassType->isDependentType()) { 8558 DeclarationName Name 8559 = Context.DeclarationNames.getCXXDestructorName( 8560 Context.getCanonicalType(ClassType)); 8561 if (NewFD->getDeclName() != Name) { 8562 Diag(NewFD->getLocation(), diag::err_destructor_name); 8563 NewFD->setInvalidDecl(); 8564 return Redeclaration; 8565 } 8566 } 8567 } else if (CXXConversionDecl *Conversion 8568 = dyn_cast<CXXConversionDecl>(NewFD)) { 8569 ActOnConversionDeclarator(Conversion); 8570 } 8571 8572 // Find any virtual functions that this function overrides. 8573 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8574 if (!Method->isFunctionTemplateSpecialization() && 8575 !Method->getDescribedFunctionTemplate() && 8576 Method->isCanonicalDecl()) { 8577 if (AddOverriddenMethods(Method->getParent(), Method)) { 8578 // If the function was marked as "static", we have a problem. 8579 if (NewFD->getStorageClass() == SC_Static) { 8580 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8581 } 8582 } 8583 } 8584 8585 if (Method->isStatic()) 8586 checkThisInStaticMemberFunctionType(Method); 8587 } 8588 8589 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8590 if (NewFD->isOverloadedOperator() && 8591 CheckOverloadedOperatorDeclaration(NewFD)) { 8592 NewFD->setInvalidDecl(); 8593 return Redeclaration; 8594 } 8595 8596 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8597 if (NewFD->getLiteralIdentifier() && 8598 CheckLiteralOperatorDeclaration(NewFD)) { 8599 NewFD->setInvalidDecl(); 8600 return Redeclaration; 8601 } 8602 8603 // In C++, check default arguments now that we have merged decls. Unless 8604 // the lexical context is the class, because in this case this is done 8605 // during delayed parsing anyway. 8606 if (!CurContext->isRecord()) 8607 CheckCXXDefaultArguments(NewFD); 8608 8609 // If this function declares a builtin function, check the type of this 8610 // declaration against the expected type for the builtin. 8611 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8612 ASTContext::GetBuiltinTypeError Error; 8613 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8614 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8615 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8616 // The type of this function differs from the type of the builtin, 8617 // so forget about the builtin entirely. 8618 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 8619 } 8620 } 8621 8622 // If this function is declared as being extern "C", then check to see if 8623 // the function returns a UDT (class, struct, or union type) that is not C 8624 // compatible, and if it does, warn the user. 8625 // But, issue any diagnostic on the first declaration only. 8626 if (Previous.empty() && NewFD->isExternC()) { 8627 QualType R = NewFD->getReturnType(); 8628 if (R->isIncompleteType() && !R->isVoidType()) 8629 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8630 << NewFD << R; 8631 else if (!R.isPODType(Context) && !R->isVoidType() && 8632 !R->isObjCObjectPointerType()) 8633 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8634 } 8635 } 8636 return Redeclaration; 8637 } 8638 8639 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8640 // C++11 [basic.start.main]p3: 8641 // A program that [...] declares main to be inline, static or 8642 // constexpr is ill-formed. 8643 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8644 // appear in a declaration of main. 8645 // static main is not an error under C99, but we should warn about it. 8646 // We accept _Noreturn main as an extension. 8647 if (FD->getStorageClass() == SC_Static) 8648 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8649 ? diag::err_static_main : diag::warn_static_main) 8650 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8651 if (FD->isInlineSpecified()) 8652 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8653 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8654 if (DS.isNoreturnSpecified()) { 8655 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8656 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8657 Diag(NoreturnLoc, diag::ext_noreturn_main); 8658 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8659 << FixItHint::CreateRemoval(NoreturnRange); 8660 } 8661 if (FD->isConstexpr()) { 8662 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8663 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8664 FD->setConstexpr(false); 8665 } 8666 8667 if (getLangOpts().OpenCL) { 8668 Diag(FD->getLocation(), diag::err_opencl_no_main) 8669 << FD->hasAttr<OpenCLKernelAttr>(); 8670 FD->setInvalidDecl(); 8671 return; 8672 } 8673 8674 QualType T = FD->getType(); 8675 assert(T->isFunctionType() && "function decl is not of function type"); 8676 const FunctionType* FT = T->castAs<FunctionType>(); 8677 8678 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8679 // In C with GNU extensions we allow main() to have non-integer return 8680 // type, but we should warn about the extension, and we disable the 8681 // implicit-return-zero rule. 8682 8683 // GCC in C mode accepts qualified 'int'. 8684 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8685 FD->setHasImplicitReturnZero(true); 8686 else { 8687 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8688 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8689 if (RTRange.isValid()) 8690 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8691 << FixItHint::CreateReplacement(RTRange, "int"); 8692 } 8693 } else { 8694 // In C and C++, main magically returns 0 if you fall off the end; 8695 // set the flag which tells us that. 8696 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8697 8698 // All the standards say that main() should return 'int'. 8699 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8700 FD->setHasImplicitReturnZero(true); 8701 else { 8702 // Otherwise, this is just a flat-out error. 8703 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8704 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8705 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8706 : FixItHint()); 8707 FD->setInvalidDecl(true); 8708 } 8709 } 8710 8711 // Treat protoless main() as nullary. 8712 if (isa<FunctionNoProtoType>(FT)) return; 8713 8714 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8715 unsigned nparams = FTP->getNumParams(); 8716 assert(FD->getNumParams() == nparams); 8717 8718 bool HasExtraParameters = (nparams > 3); 8719 8720 if (FTP->isVariadic()) { 8721 Diag(FD->getLocation(), diag::ext_variadic_main); 8722 // FIXME: if we had information about the location of the ellipsis, we 8723 // could add a FixIt hint to remove it as a parameter. 8724 } 8725 8726 // Darwin passes an undocumented fourth argument of type char**. If 8727 // other platforms start sprouting these, the logic below will start 8728 // getting shifty. 8729 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8730 HasExtraParameters = false; 8731 8732 if (HasExtraParameters) { 8733 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8734 FD->setInvalidDecl(true); 8735 nparams = 3; 8736 } 8737 8738 // FIXME: a lot of the following diagnostics would be improved 8739 // if we had some location information about types. 8740 8741 QualType CharPP = 8742 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8743 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8744 8745 for (unsigned i = 0; i < nparams; ++i) { 8746 QualType AT = FTP->getParamType(i); 8747 8748 bool mismatch = true; 8749 8750 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8751 mismatch = false; 8752 else if (Expected[i] == CharPP) { 8753 // As an extension, the following forms are okay: 8754 // char const ** 8755 // char const * const * 8756 // char * const * 8757 8758 QualifierCollector qs; 8759 const PointerType* PT; 8760 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8761 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8762 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8763 Context.CharTy)) { 8764 qs.removeConst(); 8765 mismatch = !qs.empty(); 8766 } 8767 } 8768 8769 if (mismatch) { 8770 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8771 // TODO: suggest replacing given type with expected type 8772 FD->setInvalidDecl(true); 8773 } 8774 } 8775 8776 if (nparams == 1 && !FD->isInvalidDecl()) { 8777 Diag(FD->getLocation(), diag::warn_main_one_arg); 8778 } 8779 8780 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8781 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8782 FD->setInvalidDecl(); 8783 } 8784 } 8785 8786 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8787 QualType T = FD->getType(); 8788 assert(T->isFunctionType() && "function decl is not of function type"); 8789 const FunctionType *FT = T->castAs<FunctionType>(); 8790 8791 // Set an implicit return of 'zero' if the function can return some integral, 8792 // enumeration, pointer or nullptr type. 8793 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8794 FT->getReturnType()->isAnyPointerType() || 8795 FT->getReturnType()->isNullPtrType()) 8796 // DllMain is exempt because a return value of zero means it failed. 8797 if (FD->getName() != "DllMain") 8798 FD->setHasImplicitReturnZero(true); 8799 8800 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8801 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8802 FD->setInvalidDecl(); 8803 } 8804 } 8805 8806 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8807 // FIXME: Need strict checking. In C89, we need to check for 8808 // any assignment, increment, decrement, function-calls, or 8809 // commas outside of a sizeof. In C99, it's the same list, 8810 // except that the aforementioned are allowed in unevaluated 8811 // expressions. Everything else falls under the 8812 // "may accept other forms of constant expressions" exception. 8813 // (We never end up here for C++, so the constant expression 8814 // rules there don't matter.) 8815 const Expr *Culprit; 8816 if (Init->isConstantInitializer(Context, false, &Culprit)) 8817 return false; 8818 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8819 << Culprit->getSourceRange(); 8820 return true; 8821 } 8822 8823 namespace { 8824 // Visits an initialization expression to see if OrigDecl is evaluated in 8825 // its own initialization and throws a warning if it does. 8826 class SelfReferenceChecker 8827 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8828 Sema &S; 8829 Decl *OrigDecl; 8830 bool isRecordType; 8831 bool isPODType; 8832 bool isReferenceType; 8833 8834 bool isInitList; 8835 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8836 8837 public: 8838 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8839 8840 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8841 S(S), OrigDecl(OrigDecl) { 8842 isPODType = false; 8843 isRecordType = false; 8844 isReferenceType = false; 8845 isInitList = false; 8846 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8847 isPODType = VD->getType().isPODType(S.Context); 8848 isRecordType = VD->getType()->isRecordType(); 8849 isReferenceType = VD->getType()->isReferenceType(); 8850 } 8851 } 8852 8853 // For most expressions, just call the visitor. For initializer lists, 8854 // track the index of the field being initialized since fields are 8855 // initialized in order allowing use of previously initialized fields. 8856 void CheckExpr(Expr *E) { 8857 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8858 if (!InitList) { 8859 Visit(E); 8860 return; 8861 } 8862 8863 // Track and increment the index here. 8864 isInitList = true; 8865 InitFieldIndex.push_back(0); 8866 for (auto Child : InitList->children()) { 8867 CheckExpr(cast<Expr>(Child)); 8868 ++InitFieldIndex.back(); 8869 } 8870 InitFieldIndex.pop_back(); 8871 } 8872 8873 // Returns true if MemberExpr is checked and no futher checking is needed. 8874 // Returns false if additional checking is required. 8875 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8876 llvm::SmallVector<FieldDecl*, 4> Fields; 8877 Expr *Base = E; 8878 bool ReferenceField = false; 8879 8880 // Get the field memebers used. 8881 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8882 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8883 if (!FD) 8884 return false; 8885 Fields.push_back(FD); 8886 if (FD->getType()->isReferenceType()) 8887 ReferenceField = true; 8888 Base = ME->getBase()->IgnoreParenImpCasts(); 8889 } 8890 8891 // Keep checking only if the base Decl is the same. 8892 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8893 if (!DRE || DRE->getDecl() != OrigDecl) 8894 return false; 8895 8896 // A reference field can be bound to an unininitialized field. 8897 if (CheckReference && !ReferenceField) 8898 return true; 8899 8900 // Convert FieldDecls to their index number. 8901 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8902 for (const FieldDecl *I : llvm::reverse(Fields)) 8903 UsedFieldIndex.push_back(I->getFieldIndex()); 8904 8905 // See if a warning is needed by checking the first difference in index 8906 // numbers. If field being used has index less than the field being 8907 // initialized, then the use is safe. 8908 for (auto UsedIter = UsedFieldIndex.begin(), 8909 UsedEnd = UsedFieldIndex.end(), 8910 OrigIter = InitFieldIndex.begin(), 8911 OrigEnd = InitFieldIndex.end(); 8912 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8913 if (*UsedIter < *OrigIter) 8914 return true; 8915 if (*UsedIter > *OrigIter) 8916 break; 8917 } 8918 8919 // TODO: Add a different warning which will print the field names. 8920 HandleDeclRefExpr(DRE); 8921 return true; 8922 } 8923 8924 // For most expressions, the cast is directly above the DeclRefExpr. 8925 // For conditional operators, the cast can be outside the conditional 8926 // operator if both expressions are DeclRefExpr's. 8927 void HandleValue(Expr *E) { 8928 E = E->IgnoreParens(); 8929 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8930 HandleDeclRefExpr(DRE); 8931 return; 8932 } 8933 8934 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8935 Visit(CO->getCond()); 8936 HandleValue(CO->getTrueExpr()); 8937 HandleValue(CO->getFalseExpr()); 8938 return; 8939 } 8940 8941 if (BinaryConditionalOperator *BCO = 8942 dyn_cast<BinaryConditionalOperator>(E)) { 8943 Visit(BCO->getCond()); 8944 HandleValue(BCO->getFalseExpr()); 8945 return; 8946 } 8947 8948 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8949 HandleValue(OVE->getSourceExpr()); 8950 return; 8951 } 8952 8953 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8954 if (BO->getOpcode() == BO_Comma) { 8955 Visit(BO->getLHS()); 8956 HandleValue(BO->getRHS()); 8957 return; 8958 } 8959 } 8960 8961 if (isa<MemberExpr>(E)) { 8962 if (isInitList) { 8963 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8964 false /*CheckReference*/)) 8965 return; 8966 } 8967 8968 Expr *Base = E->IgnoreParenImpCasts(); 8969 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8970 // Check for static member variables and don't warn on them. 8971 if (!isa<FieldDecl>(ME->getMemberDecl())) 8972 return; 8973 Base = ME->getBase()->IgnoreParenImpCasts(); 8974 } 8975 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8976 HandleDeclRefExpr(DRE); 8977 return; 8978 } 8979 8980 Visit(E); 8981 } 8982 8983 // Reference types not handled in HandleValue are handled here since all 8984 // uses of references are bad, not just r-value uses. 8985 void VisitDeclRefExpr(DeclRefExpr *E) { 8986 if (isReferenceType) 8987 HandleDeclRefExpr(E); 8988 } 8989 8990 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8991 if (E->getCastKind() == CK_LValueToRValue) { 8992 HandleValue(E->getSubExpr()); 8993 return; 8994 } 8995 8996 Inherited::VisitImplicitCastExpr(E); 8997 } 8998 8999 void VisitMemberExpr(MemberExpr *E) { 9000 if (isInitList) { 9001 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9002 return; 9003 } 9004 9005 // Don't warn on arrays since they can be treated as pointers. 9006 if (E->getType()->canDecayToPointerType()) return; 9007 9008 // Warn when a non-static method call is followed by non-static member 9009 // field accesses, which is followed by a DeclRefExpr. 9010 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9011 bool Warn = (MD && !MD->isStatic()); 9012 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9013 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9014 if (!isa<FieldDecl>(ME->getMemberDecl())) 9015 Warn = false; 9016 Base = ME->getBase()->IgnoreParenImpCasts(); 9017 } 9018 9019 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9020 if (Warn) 9021 HandleDeclRefExpr(DRE); 9022 return; 9023 } 9024 9025 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9026 // Visit that expression. 9027 Visit(Base); 9028 } 9029 9030 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9031 Expr *Callee = E->getCallee(); 9032 9033 if (isa<UnresolvedLookupExpr>(Callee)) 9034 return Inherited::VisitCXXOperatorCallExpr(E); 9035 9036 Visit(Callee); 9037 for (auto Arg: E->arguments()) 9038 HandleValue(Arg->IgnoreParenImpCasts()); 9039 } 9040 9041 void VisitUnaryOperator(UnaryOperator *E) { 9042 // For POD record types, addresses of its own members are well-defined. 9043 if (E->getOpcode() == UO_AddrOf && isRecordType && 9044 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9045 if (!isPODType) 9046 HandleValue(E->getSubExpr()); 9047 return; 9048 } 9049 9050 if (E->isIncrementDecrementOp()) { 9051 HandleValue(E->getSubExpr()); 9052 return; 9053 } 9054 9055 Inherited::VisitUnaryOperator(E); 9056 } 9057 9058 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9059 9060 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9061 if (E->getConstructor()->isCopyConstructor()) { 9062 Expr *ArgExpr = E->getArg(0); 9063 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9064 if (ILE->getNumInits() == 1) 9065 ArgExpr = ILE->getInit(0); 9066 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9067 if (ICE->getCastKind() == CK_NoOp) 9068 ArgExpr = ICE->getSubExpr(); 9069 HandleValue(ArgExpr); 9070 return; 9071 } 9072 Inherited::VisitCXXConstructExpr(E); 9073 } 9074 9075 void VisitCallExpr(CallExpr *E) { 9076 // Treat std::move as a use. 9077 if (E->getNumArgs() == 1) { 9078 if (FunctionDecl *FD = E->getDirectCallee()) { 9079 if (FD->isInStdNamespace() && FD->getIdentifier() && 9080 FD->getIdentifier()->isStr("move")) { 9081 HandleValue(E->getArg(0)); 9082 return; 9083 } 9084 } 9085 } 9086 9087 Inherited::VisitCallExpr(E); 9088 } 9089 9090 void VisitBinaryOperator(BinaryOperator *E) { 9091 if (E->isCompoundAssignmentOp()) { 9092 HandleValue(E->getLHS()); 9093 Visit(E->getRHS()); 9094 return; 9095 } 9096 9097 Inherited::VisitBinaryOperator(E); 9098 } 9099 9100 // A custom visitor for BinaryConditionalOperator is needed because the 9101 // regular visitor would check the condition and true expression separately 9102 // but both point to the same place giving duplicate diagnostics. 9103 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9104 Visit(E->getCond()); 9105 Visit(E->getFalseExpr()); 9106 } 9107 9108 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9109 Decl* ReferenceDecl = DRE->getDecl(); 9110 if (OrigDecl != ReferenceDecl) return; 9111 unsigned diag; 9112 if (isReferenceType) { 9113 diag = diag::warn_uninit_self_reference_in_reference_init; 9114 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9115 diag = diag::warn_static_self_reference_in_init; 9116 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9117 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9118 DRE->getDecl()->getType()->isRecordType()) { 9119 diag = diag::warn_uninit_self_reference_in_init; 9120 } else { 9121 // Local variables will be handled by the CFG analysis. 9122 return; 9123 } 9124 9125 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9126 S.PDiag(diag) 9127 << DRE->getNameInfo().getName() 9128 << OrigDecl->getLocation() 9129 << DRE->getSourceRange()); 9130 } 9131 }; 9132 9133 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9134 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9135 bool DirectInit) { 9136 // Parameters arguments are occassionially constructed with itself, 9137 // for instance, in recursive functions. Skip them. 9138 if (isa<ParmVarDecl>(OrigDecl)) 9139 return; 9140 9141 E = E->IgnoreParens(); 9142 9143 // Skip checking T a = a where T is not a record or reference type. 9144 // Doing so is a way to silence uninitialized warnings. 9145 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9146 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9147 if (ICE->getCastKind() == CK_LValueToRValue) 9148 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9149 if (DRE->getDecl() == OrigDecl) 9150 return; 9151 9152 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9153 } 9154 } // end anonymous namespace 9155 9156 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9157 DeclarationName Name, QualType Type, 9158 TypeSourceInfo *TSI, 9159 SourceRange Range, bool DirectInit, 9160 Expr *Init) { 9161 bool IsInitCapture = !VDecl; 9162 assert((!VDecl || !VDecl->isInitCapture()) && 9163 "init captures are expected to be deduced prior to initialization"); 9164 9165 ArrayRef<Expr *> DeduceInits = Init; 9166 if (DirectInit) { 9167 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9168 DeduceInits = PL->exprs(); 9169 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9170 DeduceInits = IL->inits(); 9171 } 9172 9173 // Deduction only works if we have exactly one source expression. 9174 if (DeduceInits.empty()) { 9175 // It isn't possible to write this directly, but it is possible to 9176 // end up in this situation with "auto x(some_pack...);" 9177 Diag(Init->getLocStart(), IsInitCapture 9178 ? diag::err_init_capture_no_expression 9179 : diag::err_auto_var_init_no_expression) 9180 << Name << Type << Range; 9181 return QualType(); 9182 } 9183 9184 if (DeduceInits.size() > 1) { 9185 Diag(DeduceInits[1]->getLocStart(), 9186 IsInitCapture ? diag::err_init_capture_multiple_expressions 9187 : diag::err_auto_var_init_multiple_expressions) 9188 << Name << Type << Range; 9189 return QualType(); 9190 } 9191 9192 Expr *DeduceInit = DeduceInits[0]; 9193 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9194 Diag(Init->getLocStart(), IsInitCapture 9195 ? diag::err_init_capture_paren_braces 9196 : diag::err_auto_var_init_paren_braces) 9197 << isa<InitListExpr>(Init) << Name << Type << Range; 9198 return QualType(); 9199 } 9200 9201 // Expressions default to 'id' when we're in a debugger. 9202 bool DefaultedAnyToId = false; 9203 if (getLangOpts().DebuggerCastResultToId && 9204 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9205 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9206 if (Result.isInvalid()) { 9207 return QualType(); 9208 } 9209 Init = Result.get(); 9210 DefaultedAnyToId = true; 9211 } 9212 9213 QualType DeducedType; 9214 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9215 if (!IsInitCapture) 9216 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9217 else if (isa<InitListExpr>(Init)) 9218 Diag(Range.getBegin(), 9219 diag::err_init_capture_deduction_failure_from_init_list) 9220 << Name 9221 << (DeduceInit->getType().isNull() ? TSI->getType() 9222 : DeduceInit->getType()) 9223 << DeduceInit->getSourceRange(); 9224 else 9225 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9226 << Name << TSI->getType() 9227 << (DeduceInit->getType().isNull() ? TSI->getType() 9228 : DeduceInit->getType()) 9229 << DeduceInit->getSourceRange(); 9230 } 9231 9232 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9233 // 'id' instead of a specific object type prevents most of our usual 9234 // checks. 9235 // We only want to warn outside of template instantiations, though: 9236 // inside a template, the 'id' could have come from a parameter. 9237 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9238 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9239 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9240 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range; 9241 } 9242 9243 return DeducedType; 9244 } 9245 9246 /// AddInitializerToDecl - Adds the initializer Init to the 9247 /// declaration dcl. If DirectInit is true, this is C++ direct 9248 /// initialization rather than copy initialization. 9249 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 9250 bool DirectInit, bool TypeMayContainAuto) { 9251 // If there is no declaration, there was an error parsing it. Just ignore 9252 // the initializer. 9253 if (!RealDecl || RealDecl->isInvalidDecl()) { 9254 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9255 return; 9256 } 9257 9258 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9259 // Pure-specifiers are handled in ActOnPureSpecifier. 9260 Diag(Method->getLocation(), diag::err_member_function_initialization) 9261 << Method->getDeclName() << Init->getSourceRange(); 9262 Method->setInvalidDecl(); 9263 return; 9264 } 9265 9266 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9267 if (!VDecl) { 9268 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9269 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9270 RealDecl->setInvalidDecl(); 9271 return; 9272 } 9273 9274 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9275 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 9276 // Attempt typo correction early so that the type of the init expression can 9277 // be deduced based on the chosen correction if the original init contains a 9278 // TypoExpr. 9279 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9280 if (!Res.isUsable()) { 9281 RealDecl->setInvalidDecl(); 9282 return; 9283 } 9284 Init = Res.get(); 9285 9286 QualType DeducedType = deduceVarTypeFromInitializer( 9287 VDecl, VDecl->getDeclName(), VDecl->getType(), 9288 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9289 if (DeducedType.isNull()) { 9290 RealDecl->setInvalidDecl(); 9291 return; 9292 } 9293 9294 VDecl->setType(DeducedType); 9295 assert(VDecl->isLinkageValid()); 9296 9297 // In ARC, infer lifetime. 9298 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9299 VDecl->setInvalidDecl(); 9300 9301 // If this is a redeclaration, check that the type we just deduced matches 9302 // the previously declared type. 9303 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9304 // We never need to merge the type, because we cannot form an incomplete 9305 // array of auto, nor deduce such a type. 9306 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9307 } 9308 9309 // Check the deduced type is valid for a variable declaration. 9310 CheckVariableDeclarationType(VDecl); 9311 if (VDecl->isInvalidDecl()) 9312 return; 9313 } 9314 9315 // dllimport cannot be used on variable definitions. 9316 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9317 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9318 VDecl->setInvalidDecl(); 9319 return; 9320 } 9321 9322 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9323 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9324 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9325 VDecl->setInvalidDecl(); 9326 return; 9327 } 9328 9329 if (!VDecl->getType()->isDependentType()) { 9330 // A definition must end up with a complete type, which means it must be 9331 // complete with the restriction that an array type might be completed by 9332 // the initializer; note that later code assumes this restriction. 9333 QualType BaseDeclType = VDecl->getType(); 9334 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9335 BaseDeclType = Array->getElementType(); 9336 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9337 diag::err_typecheck_decl_incomplete_type)) { 9338 RealDecl->setInvalidDecl(); 9339 return; 9340 } 9341 9342 // The variable can not have an abstract class type. 9343 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9344 diag::err_abstract_type_in_decl, 9345 AbstractVariableType)) 9346 VDecl->setInvalidDecl(); 9347 } 9348 9349 VarDecl *Def; 9350 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 9351 NamedDecl *Hidden = nullptr; 9352 if (!hasVisibleDefinition(Def, &Hidden) && 9353 (VDecl->getFormalLinkage() == InternalLinkage || 9354 VDecl->getDescribedVarTemplate() || 9355 VDecl->getNumTemplateParameterLists() || 9356 VDecl->getDeclContext()->isDependentContext())) { 9357 // The previous definition is hidden, and multiple definitions are 9358 // permitted (in separate TUs). Form another definition of it. 9359 } else { 9360 Diag(VDecl->getLocation(), diag::err_redefinition) 9361 << VDecl->getDeclName(); 9362 Diag(Def->getLocation(), diag::note_previous_definition); 9363 VDecl->setInvalidDecl(); 9364 return; 9365 } 9366 } 9367 9368 if (getLangOpts().CPlusPlus) { 9369 // C++ [class.static.data]p4 9370 // If a static data member is of const integral or const 9371 // enumeration type, its declaration in the class definition can 9372 // specify a constant-initializer which shall be an integral 9373 // constant expression (5.19). In that case, the member can appear 9374 // in integral constant expressions. The member shall still be 9375 // defined in a namespace scope if it is used in the program and the 9376 // namespace scope definition shall not contain an initializer. 9377 // 9378 // We already performed a redefinition check above, but for static 9379 // data members we also need to check whether there was an in-class 9380 // declaration with an initializer. 9381 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9382 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9383 << VDecl->getDeclName(); 9384 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9385 diag::note_previous_initializer) 9386 << 0; 9387 return; 9388 } 9389 9390 if (VDecl->hasLocalStorage()) 9391 getCurFunction()->setHasBranchProtectedScope(); 9392 9393 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 9394 VDecl->setInvalidDecl(); 9395 return; 9396 } 9397 } 9398 9399 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 9400 // a kernel function cannot be initialized." 9401 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 9402 Diag(VDecl->getLocation(), diag::err_local_cant_init); 9403 VDecl->setInvalidDecl(); 9404 return; 9405 } 9406 9407 // Get the decls type and save a reference for later, since 9408 // CheckInitializerTypes may change it. 9409 QualType DclT = VDecl->getType(), SavT = DclT; 9410 9411 // Expressions default to 'id' when we're in a debugger 9412 // and we are assigning it to a variable of Objective-C pointer type. 9413 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 9414 Init->getType() == Context.UnknownAnyTy) { 9415 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9416 if (Result.isInvalid()) { 9417 VDecl->setInvalidDecl(); 9418 return; 9419 } 9420 Init = Result.get(); 9421 } 9422 9423 // Perform the initialization. 9424 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 9425 if (!VDecl->isInvalidDecl()) { 9426 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9427 InitializationKind Kind = 9428 DirectInit 9429 ? CXXDirectInit 9430 ? InitializationKind::CreateDirect(VDecl->getLocation(), 9431 Init->getLocStart(), 9432 Init->getLocEnd()) 9433 : InitializationKind::CreateDirectList(VDecl->getLocation()) 9434 : InitializationKind::CreateCopy(VDecl->getLocation(), 9435 Init->getLocStart()); 9436 9437 MultiExprArg Args = Init; 9438 if (CXXDirectInit) 9439 Args = MultiExprArg(CXXDirectInit->getExprs(), 9440 CXXDirectInit->getNumExprs()); 9441 9442 // Try to correct any TypoExprs in the initialization arguments. 9443 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9444 ExprResult Res = CorrectDelayedTyposInExpr( 9445 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9446 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9447 return Init.Failed() ? ExprError() : E; 9448 }); 9449 if (Res.isInvalid()) { 9450 VDecl->setInvalidDecl(); 9451 } else if (Res.get() != Args[Idx]) { 9452 Args[Idx] = Res.get(); 9453 } 9454 } 9455 if (VDecl->isInvalidDecl()) 9456 return; 9457 9458 InitializationSequence InitSeq(*this, Entity, Kind, Args); 9459 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9460 if (Result.isInvalid()) { 9461 VDecl->setInvalidDecl(); 9462 return; 9463 } 9464 9465 Init = Result.getAs<Expr>(); 9466 } 9467 9468 // Check for self-references within variable initializers. 9469 // Variables declared within a function/method body (except for references) 9470 // are handled by a dataflow analysis. 9471 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9472 VDecl->getType()->isReferenceType()) { 9473 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9474 } 9475 9476 // If the type changed, it means we had an incomplete type that was 9477 // completed by the initializer. For example: 9478 // int ary[] = { 1, 3, 5 }; 9479 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9480 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9481 VDecl->setType(DclT); 9482 9483 if (!VDecl->isInvalidDecl()) { 9484 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9485 9486 if (VDecl->hasAttr<BlocksAttr>()) 9487 checkRetainCycles(VDecl, Init); 9488 9489 // It is safe to assign a weak reference into a strong variable. 9490 // Although this code can still have problems: 9491 // id x = self.weakProp; 9492 // id y = self.weakProp; 9493 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9494 // paths through the function. This should be revisited if 9495 // -Wrepeated-use-of-weak is made flow-sensitive. 9496 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9497 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9498 Init->getLocStart())) 9499 getCurFunction()->markSafeWeakUse(Init); 9500 } 9501 9502 // The initialization is usually a full-expression. 9503 // 9504 // FIXME: If this is a braced initialization of an aggregate, it is not 9505 // an expression, and each individual field initializer is a separate 9506 // full-expression. For instance, in: 9507 // 9508 // struct Temp { ~Temp(); }; 9509 // struct S { S(Temp); }; 9510 // struct T { S a, b; } t = { Temp(), Temp() } 9511 // 9512 // we should destroy the first Temp before constructing the second. 9513 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9514 false, 9515 VDecl->isConstexpr()); 9516 if (Result.isInvalid()) { 9517 VDecl->setInvalidDecl(); 9518 return; 9519 } 9520 Init = Result.get(); 9521 9522 // Attach the initializer to the decl. 9523 VDecl->setInit(Init); 9524 9525 if (VDecl->isLocalVarDecl()) { 9526 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9527 // static storage duration shall be constant expressions or string literals. 9528 // C++ does not have this restriction. 9529 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9530 const Expr *Culprit; 9531 if (VDecl->getStorageClass() == SC_Static) 9532 CheckForConstantInitializer(Init, DclT); 9533 // C89 is stricter than C99 for non-static aggregate types. 9534 // C89 6.5.7p3: All the expressions [...] in an initializer list 9535 // for an object that has aggregate or union type shall be 9536 // constant expressions. 9537 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9538 isa<InitListExpr>(Init) && 9539 !Init->isConstantInitializer(Context, false, &Culprit)) 9540 Diag(Culprit->getExprLoc(), 9541 diag::ext_aggregate_init_not_constant) 9542 << Culprit->getSourceRange(); 9543 } 9544 } else if (VDecl->isStaticDataMember() && 9545 VDecl->getLexicalDeclContext()->isRecord()) { 9546 // This is an in-class initialization for a static data member, e.g., 9547 // 9548 // struct S { 9549 // static const int value = 17; 9550 // }; 9551 9552 // C++ [class.mem]p4: 9553 // A member-declarator can contain a constant-initializer only 9554 // if it declares a static member (9.4) of const integral or 9555 // const enumeration type, see 9.4.2. 9556 // 9557 // C++11 [class.static.data]p3: 9558 // If a non-volatile const static data member is of integral or 9559 // enumeration type, its declaration in the class definition can 9560 // specify a brace-or-equal-initializer in which every initalizer-clause 9561 // that is an assignment-expression is a constant expression. A static 9562 // data member of literal type can be declared in the class definition 9563 // with the constexpr specifier; if so, its declaration shall specify a 9564 // brace-or-equal-initializer in which every initializer-clause that is 9565 // an assignment-expression is a constant expression. 9566 9567 // Do nothing on dependent types. 9568 if (DclT->isDependentType()) { 9569 9570 // Allow any 'static constexpr' members, whether or not they are of literal 9571 // type. We separately check that every constexpr variable is of literal 9572 // type. 9573 } else if (VDecl->isConstexpr()) { 9574 9575 // Require constness. 9576 } else if (!DclT.isConstQualified()) { 9577 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9578 << Init->getSourceRange(); 9579 VDecl->setInvalidDecl(); 9580 9581 // We allow integer constant expressions in all cases. 9582 } else if (DclT->isIntegralOrEnumerationType()) { 9583 // Check whether the expression is a constant expression. 9584 SourceLocation Loc; 9585 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9586 // In C++11, a non-constexpr const static data member with an 9587 // in-class initializer cannot be volatile. 9588 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9589 else if (Init->isValueDependent()) 9590 ; // Nothing to check. 9591 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9592 ; // Ok, it's an ICE! 9593 else if (Init->isEvaluatable(Context)) { 9594 // If we can constant fold the initializer through heroics, accept it, 9595 // but report this as a use of an extension for -pedantic. 9596 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9597 << Init->getSourceRange(); 9598 } else { 9599 // Otherwise, this is some crazy unknown case. Report the issue at the 9600 // location provided by the isIntegerConstantExpr failed check. 9601 Diag(Loc, diag::err_in_class_initializer_non_constant) 9602 << Init->getSourceRange(); 9603 VDecl->setInvalidDecl(); 9604 } 9605 9606 // We allow foldable floating-point constants as an extension. 9607 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9608 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9609 // it anyway and provide a fixit to add the 'constexpr'. 9610 if (getLangOpts().CPlusPlus11) { 9611 Diag(VDecl->getLocation(), 9612 diag::ext_in_class_initializer_float_type_cxx11) 9613 << DclT << Init->getSourceRange(); 9614 Diag(VDecl->getLocStart(), 9615 diag::note_in_class_initializer_float_type_cxx11) 9616 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9617 } else { 9618 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9619 << DclT << Init->getSourceRange(); 9620 9621 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9622 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9623 << Init->getSourceRange(); 9624 VDecl->setInvalidDecl(); 9625 } 9626 } 9627 9628 // Suggest adding 'constexpr' in C++11 for literal types. 9629 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9630 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9631 << DclT << Init->getSourceRange() 9632 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9633 VDecl->setConstexpr(true); 9634 9635 } else { 9636 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9637 << DclT << Init->getSourceRange(); 9638 VDecl->setInvalidDecl(); 9639 } 9640 } else if (VDecl->isFileVarDecl()) { 9641 if (VDecl->getStorageClass() == SC_Extern && 9642 (!getLangOpts().CPlusPlus || 9643 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 9644 VDecl->isExternC())) && 9645 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9646 Diag(VDecl->getLocation(), diag::warn_extern_init); 9647 9648 // C99 6.7.8p4. All file scoped initializers need to be constant. 9649 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9650 CheckForConstantInitializer(Init, DclT); 9651 } 9652 9653 // We will represent direct-initialization similarly to copy-initialization: 9654 // int x(1); -as-> int x = 1; 9655 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9656 // 9657 // Clients that want to distinguish between the two forms, can check for 9658 // direct initializer using VarDecl::getInitStyle(). 9659 // A major benefit is that clients that don't particularly care about which 9660 // exactly form was it (like the CodeGen) can handle both cases without 9661 // special case code. 9662 9663 // C++ 8.5p11: 9664 // The form of initialization (using parentheses or '=') is generally 9665 // insignificant, but does matter when the entity being initialized has a 9666 // class type. 9667 if (CXXDirectInit) { 9668 assert(DirectInit && "Call-style initializer must be direct init."); 9669 VDecl->setInitStyle(VarDecl::CallInit); 9670 } else if (DirectInit) { 9671 // This must be list-initialization. No other way is direct-initialization. 9672 VDecl->setInitStyle(VarDecl::ListInit); 9673 } 9674 9675 CheckCompleteVariableDeclaration(VDecl); 9676 } 9677 9678 /// ActOnInitializerError - Given that there was an error parsing an 9679 /// initializer for the given declaration, try to return to some form 9680 /// of sanity. 9681 void Sema::ActOnInitializerError(Decl *D) { 9682 // Our main concern here is re-establishing invariants like "a 9683 // variable's type is either dependent or complete". 9684 if (!D || D->isInvalidDecl()) return; 9685 9686 VarDecl *VD = dyn_cast<VarDecl>(D); 9687 if (!VD) return; 9688 9689 // Auto types are meaningless if we can't make sense of the initializer. 9690 if (ParsingInitForAutoVars.count(D)) { 9691 D->setInvalidDecl(); 9692 return; 9693 } 9694 9695 QualType Ty = VD->getType(); 9696 if (Ty->isDependentType()) return; 9697 9698 // Require a complete type. 9699 if (RequireCompleteType(VD->getLocation(), 9700 Context.getBaseElementType(Ty), 9701 diag::err_typecheck_decl_incomplete_type)) { 9702 VD->setInvalidDecl(); 9703 return; 9704 } 9705 9706 // Require a non-abstract type. 9707 if (RequireNonAbstractType(VD->getLocation(), Ty, 9708 diag::err_abstract_type_in_decl, 9709 AbstractVariableType)) { 9710 VD->setInvalidDecl(); 9711 return; 9712 } 9713 9714 // Don't bother complaining about constructors or destructors, 9715 // though. 9716 } 9717 9718 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9719 bool TypeMayContainAuto) { 9720 // If there is no declaration, there was an error parsing it. Just ignore it. 9721 if (!RealDecl) 9722 return; 9723 9724 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9725 QualType Type = Var->getType(); 9726 9727 // C++11 [dcl.spec.auto]p3 9728 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9729 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9730 << Var->getDeclName() << Type; 9731 Var->setInvalidDecl(); 9732 return; 9733 } 9734 9735 // C++11 [class.static.data]p3: A static data member can be declared with 9736 // the constexpr specifier; if so, its declaration shall specify 9737 // a brace-or-equal-initializer. 9738 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9739 // the definition of a variable [...] or the declaration of a static data 9740 // member. 9741 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9742 if (Var->isStaticDataMember()) 9743 Diag(Var->getLocation(), 9744 diag::err_constexpr_static_mem_var_requires_init) 9745 << Var->getDeclName(); 9746 else 9747 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9748 Var->setInvalidDecl(); 9749 return; 9750 } 9751 9752 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 9753 // definition having the concept specifier is called a variable concept. A 9754 // concept definition refers to [...] a variable concept and its initializer. 9755 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 9756 if (VTD->isConcept()) { 9757 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 9758 Var->setInvalidDecl(); 9759 return; 9760 } 9761 } 9762 9763 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9764 // be initialized. 9765 if (!Var->isInvalidDecl() && 9766 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9767 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9768 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9769 Var->setInvalidDecl(); 9770 return; 9771 } 9772 9773 switch (Var->isThisDeclarationADefinition()) { 9774 case VarDecl::Definition: 9775 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9776 break; 9777 9778 // We have an out-of-line definition of a static data member 9779 // that has an in-class initializer, so we type-check this like 9780 // a declaration. 9781 // 9782 // Fall through 9783 9784 case VarDecl::DeclarationOnly: 9785 // It's only a declaration. 9786 9787 // Block scope. C99 6.7p7: If an identifier for an object is 9788 // declared with no linkage (C99 6.2.2p6), the type for the 9789 // object shall be complete. 9790 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9791 !Var->hasLinkage() && !Var->isInvalidDecl() && 9792 RequireCompleteType(Var->getLocation(), Type, 9793 diag::err_typecheck_decl_incomplete_type)) 9794 Var->setInvalidDecl(); 9795 9796 // Make sure that the type is not abstract. 9797 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9798 RequireNonAbstractType(Var->getLocation(), Type, 9799 diag::err_abstract_type_in_decl, 9800 AbstractVariableType)) 9801 Var->setInvalidDecl(); 9802 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9803 Var->getStorageClass() == SC_PrivateExtern) { 9804 Diag(Var->getLocation(), diag::warn_private_extern); 9805 Diag(Var->getLocation(), diag::note_private_extern); 9806 } 9807 9808 return; 9809 9810 case VarDecl::TentativeDefinition: 9811 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9812 // object that has file scope without an initializer, and without a 9813 // storage-class specifier or with the storage-class specifier "static", 9814 // constitutes a tentative definition. Note: A tentative definition with 9815 // external linkage is valid (C99 6.2.2p5). 9816 if (!Var->isInvalidDecl()) { 9817 if (const IncompleteArrayType *ArrayT 9818 = Context.getAsIncompleteArrayType(Type)) { 9819 if (RequireCompleteType(Var->getLocation(), 9820 ArrayT->getElementType(), 9821 diag::err_illegal_decl_array_incomplete_type)) 9822 Var->setInvalidDecl(); 9823 } else if (Var->getStorageClass() == SC_Static) { 9824 // C99 6.9.2p3: If the declaration of an identifier for an object is 9825 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9826 // declared type shall not be an incomplete type. 9827 // NOTE: code such as the following 9828 // static struct s; 9829 // struct s { int a; }; 9830 // is accepted by gcc. Hence here we issue a warning instead of 9831 // an error and we do not invalidate the static declaration. 9832 // NOTE: to avoid multiple warnings, only check the first declaration. 9833 if (Var->isFirstDecl()) 9834 RequireCompleteType(Var->getLocation(), Type, 9835 diag::ext_typecheck_decl_incomplete_type); 9836 } 9837 } 9838 9839 // Record the tentative definition; we're done. 9840 if (!Var->isInvalidDecl()) 9841 TentativeDefinitions.push_back(Var); 9842 return; 9843 } 9844 9845 // Provide a specific diagnostic for uninitialized variable 9846 // definitions with incomplete array type. 9847 if (Type->isIncompleteArrayType()) { 9848 Diag(Var->getLocation(), 9849 diag::err_typecheck_incomplete_array_needs_initializer); 9850 Var->setInvalidDecl(); 9851 return; 9852 } 9853 9854 // Provide a specific diagnostic for uninitialized variable 9855 // definitions with reference type. 9856 if (Type->isReferenceType()) { 9857 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9858 << Var->getDeclName() 9859 << SourceRange(Var->getLocation(), Var->getLocation()); 9860 Var->setInvalidDecl(); 9861 return; 9862 } 9863 9864 // Do not attempt to type-check the default initializer for a 9865 // variable with dependent type. 9866 if (Type->isDependentType()) 9867 return; 9868 9869 if (Var->isInvalidDecl()) 9870 return; 9871 9872 if (!Var->hasAttr<AliasAttr>()) { 9873 if (RequireCompleteType(Var->getLocation(), 9874 Context.getBaseElementType(Type), 9875 diag::err_typecheck_decl_incomplete_type)) { 9876 Var->setInvalidDecl(); 9877 return; 9878 } 9879 } else { 9880 return; 9881 } 9882 9883 // The variable can not have an abstract class type. 9884 if (RequireNonAbstractType(Var->getLocation(), Type, 9885 diag::err_abstract_type_in_decl, 9886 AbstractVariableType)) { 9887 Var->setInvalidDecl(); 9888 return; 9889 } 9890 9891 // Check for jumps past the implicit initializer. C++0x 9892 // clarifies that this applies to a "variable with automatic 9893 // storage duration", not a "local variable". 9894 // C++11 [stmt.dcl]p3 9895 // A program that jumps from a point where a variable with automatic 9896 // storage duration is not in scope to a point where it is in scope is 9897 // ill-formed unless the variable has scalar type, class type with a 9898 // trivial default constructor and a trivial destructor, a cv-qualified 9899 // version of one of these types, or an array of one of the preceding 9900 // types and is declared without an initializer. 9901 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9902 if (const RecordType *Record 9903 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9904 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9905 // Mark the function for further checking even if the looser rules of 9906 // C++11 do not require such checks, so that we can diagnose 9907 // incompatibilities with C++98. 9908 if (!CXXRecord->isPOD()) 9909 getCurFunction()->setHasBranchProtectedScope(); 9910 } 9911 } 9912 9913 // C++03 [dcl.init]p9: 9914 // If no initializer is specified for an object, and the 9915 // object is of (possibly cv-qualified) non-POD class type (or 9916 // array thereof), the object shall be default-initialized; if 9917 // the object is of const-qualified type, the underlying class 9918 // type shall have a user-declared default 9919 // constructor. Otherwise, if no initializer is specified for 9920 // a non- static object, the object and its subobjects, if 9921 // any, have an indeterminate initial value); if the object 9922 // or any of its subobjects are of const-qualified type, the 9923 // program is ill-formed. 9924 // C++0x [dcl.init]p11: 9925 // If no initializer is specified for an object, the object is 9926 // default-initialized; [...]. 9927 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9928 InitializationKind Kind 9929 = InitializationKind::CreateDefault(Var->getLocation()); 9930 9931 InitializationSequence InitSeq(*this, Entity, Kind, None); 9932 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9933 if (Init.isInvalid()) 9934 Var->setInvalidDecl(); 9935 else if (Init.get()) { 9936 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9937 // This is important for template substitution. 9938 Var->setInitStyle(VarDecl::CallInit); 9939 } 9940 9941 CheckCompleteVariableDeclaration(Var); 9942 } 9943 } 9944 9945 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9946 // If there is no declaration, there was an error parsing it. Ignore it. 9947 if (!D) 9948 return; 9949 9950 VarDecl *VD = dyn_cast<VarDecl>(D); 9951 if (!VD) { 9952 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9953 D->setInvalidDecl(); 9954 return; 9955 } 9956 9957 VD->setCXXForRangeDecl(true); 9958 9959 // for-range-declaration cannot be given a storage class specifier. 9960 int Error = -1; 9961 switch (VD->getStorageClass()) { 9962 case SC_None: 9963 break; 9964 case SC_Extern: 9965 Error = 0; 9966 break; 9967 case SC_Static: 9968 Error = 1; 9969 break; 9970 case SC_PrivateExtern: 9971 Error = 2; 9972 break; 9973 case SC_Auto: 9974 Error = 3; 9975 break; 9976 case SC_Register: 9977 Error = 4; 9978 break; 9979 } 9980 if (Error != -1) { 9981 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9982 << VD->getDeclName() << Error; 9983 D->setInvalidDecl(); 9984 } 9985 } 9986 9987 StmtResult 9988 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9989 IdentifierInfo *Ident, 9990 ParsedAttributes &Attrs, 9991 SourceLocation AttrEnd) { 9992 // C++1y [stmt.iter]p1: 9993 // A range-based for statement of the form 9994 // for ( for-range-identifier : for-range-initializer ) statement 9995 // is equivalent to 9996 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9997 DeclSpec DS(Attrs.getPool().getFactory()); 9998 9999 const char *PrevSpec; 10000 unsigned DiagID; 10001 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10002 getPrintingPolicy()); 10003 10004 Declarator D(DS, Declarator::ForContext); 10005 D.SetIdentifier(Ident, IdentLoc); 10006 D.takeAttributes(Attrs, AttrEnd); 10007 10008 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10009 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10010 EmptyAttrs, IdentLoc); 10011 Decl *Var = ActOnDeclarator(S, D); 10012 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10013 FinalizeDeclaration(Var); 10014 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10015 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10016 } 10017 10018 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10019 if (var->isInvalidDecl()) return; 10020 10021 // In Objective-C, don't allow jumps past the implicit initialization of a 10022 // local retaining variable. 10023 if (getLangOpts().ObjC1 && 10024 var->hasLocalStorage()) { 10025 switch (var->getType().getObjCLifetime()) { 10026 case Qualifiers::OCL_None: 10027 case Qualifiers::OCL_ExplicitNone: 10028 case Qualifiers::OCL_Autoreleasing: 10029 break; 10030 10031 case Qualifiers::OCL_Weak: 10032 case Qualifiers::OCL_Strong: 10033 getCurFunction()->setHasBranchProtectedScope(); 10034 break; 10035 } 10036 } 10037 10038 // Warn about externally-visible variables being defined without a 10039 // prior declaration. We only want to do this for global 10040 // declarations, but we also specifically need to avoid doing it for 10041 // class members because the linkage of an anonymous class can 10042 // change if it's later given a typedef name. 10043 if (var->isThisDeclarationADefinition() && 10044 var->getDeclContext()->getRedeclContext()->isFileContext() && 10045 var->isExternallyVisible() && var->hasLinkage() && 10046 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10047 var->getLocation())) { 10048 // Find a previous declaration that's not a definition. 10049 VarDecl *prev = var->getPreviousDecl(); 10050 while (prev && prev->isThisDeclarationADefinition()) 10051 prev = prev->getPreviousDecl(); 10052 10053 if (!prev) 10054 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10055 } 10056 10057 if (var->getTLSKind() == VarDecl::TLS_Static) { 10058 const Expr *Culprit; 10059 if (var->getType().isDestructedType()) { 10060 // GNU C++98 edits for __thread, [basic.start.term]p3: 10061 // The type of an object with thread storage duration shall not 10062 // have a non-trivial destructor. 10063 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10064 if (getLangOpts().CPlusPlus11) 10065 Diag(var->getLocation(), diag::note_use_thread_local); 10066 } else if (getLangOpts().CPlusPlus && var->hasInit() && 10067 !var->getInit()->isConstantInitializer( 10068 Context, var->getType()->isReferenceType(), &Culprit)) { 10069 // GNU C++98 edits for __thread, [basic.start.init]p4: 10070 // An object of thread storage duration shall not require dynamic 10071 // initialization. 10072 // FIXME: Need strict checking here. 10073 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 10074 << Culprit->getSourceRange(); 10075 if (getLangOpts().CPlusPlus11) 10076 Diag(var->getLocation(), diag::note_use_thread_local); 10077 } 10078 } 10079 10080 // Apply section attributes and pragmas to global variables. 10081 bool GlobalStorage = var->hasGlobalStorage(); 10082 if (GlobalStorage && var->isThisDeclarationADefinition() && 10083 ActiveTemplateInstantiations.empty()) { 10084 PragmaStack<StringLiteral *> *Stack = nullptr; 10085 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10086 if (var->getType().isConstQualified()) 10087 Stack = &ConstSegStack; 10088 else if (!var->getInit()) { 10089 Stack = &BSSSegStack; 10090 SectionFlags |= ASTContext::PSF_Write; 10091 } else { 10092 Stack = &DataSegStack; 10093 SectionFlags |= ASTContext::PSF_Write; 10094 } 10095 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10096 var->addAttr(SectionAttr::CreateImplicit( 10097 Context, SectionAttr::Declspec_allocate, 10098 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10099 } 10100 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10101 if (UnifySection(SA->getName(), SectionFlags, var)) 10102 var->dropAttr<SectionAttr>(); 10103 10104 // Apply the init_seg attribute if this has an initializer. If the 10105 // initializer turns out to not be dynamic, we'll end up ignoring this 10106 // attribute. 10107 if (CurInitSeg && var->getInit()) 10108 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10109 CurInitSegLoc)); 10110 } 10111 10112 // All the following checks are C++ only. 10113 if (!getLangOpts().CPlusPlus) return; 10114 10115 QualType type = var->getType(); 10116 if (type->isDependentType()) return; 10117 10118 // __block variables might require us to capture a copy-initializer. 10119 if (var->hasAttr<BlocksAttr>()) { 10120 // It's currently invalid to ever have a __block variable with an 10121 // array type; should we diagnose that here? 10122 10123 // Regardless, we don't want to ignore array nesting when 10124 // constructing this copy. 10125 if (type->isStructureOrClassType()) { 10126 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10127 SourceLocation poi = var->getLocation(); 10128 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10129 ExprResult result 10130 = PerformMoveOrCopyInitialization( 10131 InitializedEntity::InitializeBlock(poi, type, false), 10132 var, var->getType(), varRef, /*AllowNRVO=*/true); 10133 if (!result.isInvalid()) { 10134 result = MaybeCreateExprWithCleanups(result); 10135 Expr *init = result.getAs<Expr>(); 10136 Context.setBlockVarCopyInits(var, init); 10137 } 10138 } 10139 } 10140 10141 Expr *Init = var->getInit(); 10142 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10143 QualType baseType = Context.getBaseElementType(type); 10144 10145 if (!var->getDeclContext()->isDependentContext() && 10146 Init && !Init->isValueDependent()) { 10147 if (IsGlobal && !var->isConstexpr() && 10148 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10149 var->getLocation())) { 10150 // Warn about globals which don't have a constant initializer. Don't 10151 // warn about globals with a non-trivial destructor because we already 10152 // warned about them. 10153 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10154 if (!(RD && !RD->hasTrivialDestructor()) && 10155 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 10156 Diag(var->getLocation(), diag::warn_global_constructor) 10157 << Init->getSourceRange(); 10158 } 10159 10160 if (var->isConstexpr()) { 10161 SmallVector<PartialDiagnosticAt, 8> Notes; 10162 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10163 SourceLocation DiagLoc = var->getLocation(); 10164 // If the note doesn't add any useful information other than a source 10165 // location, fold it into the primary diagnostic. 10166 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10167 diag::note_invalid_subexpr_in_const_expr) { 10168 DiagLoc = Notes[0].first; 10169 Notes.clear(); 10170 } 10171 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10172 << var << Init->getSourceRange(); 10173 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10174 Diag(Notes[I].first, Notes[I].second); 10175 } 10176 } else if (var->isUsableInConstantExpressions(Context)) { 10177 // Check whether the initializer of a const variable of integral or 10178 // enumeration type is an ICE now, since we can't tell whether it was 10179 // initialized by a constant expression if we check later. 10180 var->checkInitIsICE(); 10181 } 10182 } 10183 10184 // Require the destructor. 10185 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10186 FinalizeVarWithDestructor(var, recordType); 10187 } 10188 10189 /// \brief Determines if a variable's alignment is dependent. 10190 static bool hasDependentAlignment(VarDecl *VD) { 10191 if (VD->getType()->isDependentType()) 10192 return true; 10193 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10194 if (I->isAlignmentDependent()) 10195 return true; 10196 return false; 10197 } 10198 10199 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10200 /// any semantic actions necessary after any initializer has been attached. 10201 void 10202 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10203 // Note that we are no longer parsing the initializer for this declaration. 10204 ParsingInitForAutoVars.erase(ThisDecl); 10205 10206 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10207 if (!VD) 10208 return; 10209 10210 checkAttributesAfterMerging(*this, *VD); 10211 10212 // Perform TLS alignment check here after attributes attached to the variable 10213 // which may affect the alignment have been processed. Only perform the check 10214 // if the target has a maximum TLS alignment (zero means no constraints). 10215 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10216 // Protect the check so that it's not performed on dependent types and 10217 // dependent alignments (we can't determine the alignment in that case). 10218 if (VD->getTLSKind() && !hasDependentAlignment(VD)) { 10219 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10220 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10221 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10222 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10223 << (unsigned)MaxAlignChars.getQuantity(); 10224 } 10225 } 10226 } 10227 10228 // Static locals inherit dll attributes from their function. 10229 if (VD->isStaticLocal()) { 10230 if (FunctionDecl *FD = 10231 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10232 if (Attr *A = getDLLAttr(FD)) { 10233 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10234 NewAttr->setInherited(true); 10235 VD->addAttr(NewAttr); 10236 } 10237 } 10238 } 10239 10240 // Perform check for initializers of device-side global variables. 10241 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 10242 // 7.5). CUDA also allows constant initializers for __constant__ and 10243 // __device__ variables. 10244 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 10245 const Expr *Init = VD->getInit(); 10246 const bool IsGlobal = VD->hasGlobalStorage() && !VD->isStaticLocal(); 10247 if (Init && IsGlobal && 10248 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 10249 VD->hasAttr<CUDASharedAttr>())) { 10250 bool AllowedInit = false; 10251 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 10252 AllowedInit = 10253 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 10254 // We'll allow constant initializers even if it's a non-empty 10255 // constructor according to CUDA rules. This deviates from NVCC, 10256 // but allows us to handle things like constexpr constructors. 10257 if (!AllowedInit && 10258 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 10259 AllowedInit = VD->getInit()->isConstantInitializer( 10260 Context, VD->getType()->isReferenceType()); 10261 10262 if (!AllowedInit) { 10263 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 10264 ? diag::err_shared_var_init 10265 : diag::err_dynamic_var_init) 10266 << Init->getSourceRange(); 10267 VD->setInvalidDecl(); 10268 } 10269 } 10270 } 10271 10272 // Grab the dllimport or dllexport attribute off of the VarDecl. 10273 const InheritableAttr *DLLAttr = getDLLAttr(VD); 10274 10275 // Imported static data members cannot be defined out-of-line. 10276 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 10277 if (VD->isStaticDataMember() && VD->isOutOfLine() && 10278 VD->isThisDeclarationADefinition()) { 10279 // We allow definitions of dllimport class template static data members 10280 // with a warning. 10281 CXXRecordDecl *Context = 10282 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 10283 bool IsClassTemplateMember = 10284 isa<ClassTemplatePartialSpecializationDecl>(Context) || 10285 Context->getDescribedClassTemplate(); 10286 10287 Diag(VD->getLocation(), 10288 IsClassTemplateMember 10289 ? diag::warn_attribute_dllimport_static_field_definition 10290 : diag::err_attribute_dllimport_static_field_definition); 10291 Diag(IA->getLocation(), diag::note_attribute); 10292 if (!IsClassTemplateMember) 10293 VD->setInvalidDecl(); 10294 } 10295 } 10296 10297 // dllimport/dllexport variables cannot be thread local, their TLS index 10298 // isn't exported with the variable. 10299 if (DLLAttr && VD->getTLSKind()) { 10300 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 10301 if (F && getDLLAttr(F)) { 10302 assert(VD->isStaticLocal()); 10303 // But if this is a static local in a dlimport/dllexport function, the 10304 // function will never be inlined, which means the var would never be 10305 // imported, so having it marked import/export is safe. 10306 } else { 10307 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 10308 << DLLAttr; 10309 VD->setInvalidDecl(); 10310 } 10311 } 10312 10313 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 10314 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 10315 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 10316 VD->dropAttr<UsedAttr>(); 10317 } 10318 } 10319 10320 const DeclContext *DC = VD->getDeclContext(); 10321 // If there's a #pragma GCC visibility in scope, and this isn't a class 10322 // member, set the visibility of this variable. 10323 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 10324 AddPushedVisibilityAttribute(VD); 10325 10326 // FIXME: Warn on unused templates. 10327 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 10328 !isa<VarTemplatePartialSpecializationDecl>(VD)) 10329 MarkUnusedFileScopedDecl(VD); 10330 10331 // Now we have parsed the initializer and can update the table of magic 10332 // tag values. 10333 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 10334 !VD->getType()->isIntegralOrEnumerationType()) 10335 return; 10336 10337 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 10338 const Expr *MagicValueExpr = VD->getInit(); 10339 if (!MagicValueExpr) { 10340 continue; 10341 } 10342 llvm::APSInt MagicValueInt; 10343 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 10344 Diag(I->getRange().getBegin(), 10345 diag::err_type_tag_for_datatype_not_ice) 10346 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10347 continue; 10348 } 10349 if (MagicValueInt.getActiveBits() > 64) { 10350 Diag(I->getRange().getBegin(), 10351 diag::err_type_tag_for_datatype_too_large) 10352 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10353 continue; 10354 } 10355 uint64_t MagicValue = MagicValueInt.getZExtValue(); 10356 RegisterTypeTagForDatatype(I->getArgumentKind(), 10357 MagicValue, 10358 I->getMatchingCType(), 10359 I->getLayoutCompatible(), 10360 I->getMustBeNull()); 10361 } 10362 } 10363 10364 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 10365 ArrayRef<Decl *> Group) { 10366 SmallVector<Decl*, 8> Decls; 10367 10368 if (DS.isTypeSpecOwned()) 10369 Decls.push_back(DS.getRepAsDecl()); 10370 10371 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 10372 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10373 if (Decl *D = Group[i]) { 10374 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 10375 if (!FirstDeclaratorInGroup) 10376 FirstDeclaratorInGroup = DD; 10377 Decls.push_back(D); 10378 } 10379 10380 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 10381 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 10382 handleTagNumbering(Tag, S); 10383 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 10384 getLangOpts().CPlusPlus) 10385 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 10386 } 10387 } 10388 10389 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 10390 } 10391 10392 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 10393 /// group, performing any necessary semantic checking. 10394 Sema::DeclGroupPtrTy 10395 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 10396 bool TypeMayContainAuto) { 10397 // C++0x [dcl.spec.auto]p7: 10398 // If the type deduced for the template parameter U is not the same in each 10399 // deduction, the program is ill-formed. 10400 // FIXME: When initializer-list support is added, a distinction is needed 10401 // between the deduced type U and the deduced type which 'auto' stands for. 10402 // auto a = 0, b = { 1, 2, 3 }; 10403 // is legal because the deduced type U is 'int' in both cases. 10404 if (TypeMayContainAuto && Group.size() > 1) { 10405 QualType Deduced; 10406 CanQualType DeducedCanon; 10407 VarDecl *DeducedDecl = nullptr; 10408 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10409 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 10410 AutoType *AT = D->getType()->getContainedAutoType(); 10411 // Don't reissue diagnostics when instantiating a template. 10412 if (AT && D->isInvalidDecl()) 10413 break; 10414 QualType U = AT ? AT->getDeducedType() : QualType(); 10415 if (!U.isNull()) { 10416 CanQualType UCanon = Context.getCanonicalType(U); 10417 if (Deduced.isNull()) { 10418 Deduced = U; 10419 DeducedCanon = UCanon; 10420 DeducedDecl = D; 10421 } else if (DeducedCanon != UCanon) { 10422 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 10423 diag::err_auto_different_deductions) 10424 << (unsigned)AT->getKeyword() 10425 << Deduced << DeducedDecl->getDeclName() 10426 << U << D->getDeclName() 10427 << DeducedDecl->getInit()->getSourceRange() 10428 << D->getInit()->getSourceRange(); 10429 D->setInvalidDecl(); 10430 break; 10431 } 10432 } 10433 } 10434 } 10435 } 10436 10437 ActOnDocumentableDecls(Group); 10438 10439 return DeclGroupPtrTy::make( 10440 DeclGroupRef::Create(Context, Group.data(), Group.size())); 10441 } 10442 10443 void Sema::ActOnDocumentableDecl(Decl *D) { 10444 ActOnDocumentableDecls(D); 10445 } 10446 10447 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 10448 // Don't parse the comment if Doxygen diagnostics are ignored. 10449 if (Group.empty() || !Group[0]) 10450 return; 10451 10452 if (Diags.isIgnored(diag::warn_doc_param_not_found, 10453 Group[0]->getLocation()) && 10454 Diags.isIgnored(diag::warn_unknown_comment_command_name, 10455 Group[0]->getLocation())) 10456 return; 10457 10458 if (Group.size() >= 2) { 10459 // This is a decl group. Normally it will contain only declarations 10460 // produced from declarator list. But in case we have any definitions or 10461 // additional declaration references: 10462 // 'typedef struct S {} S;' 10463 // 'typedef struct S *S;' 10464 // 'struct S *pS;' 10465 // FinalizeDeclaratorGroup adds these as separate declarations. 10466 Decl *MaybeTagDecl = Group[0]; 10467 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 10468 Group = Group.slice(1); 10469 } 10470 } 10471 10472 // See if there are any new comments that are not attached to a decl. 10473 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 10474 if (!Comments.empty() && 10475 !Comments.back()->isAttached()) { 10476 // There is at least one comment that not attached to a decl. 10477 // Maybe it should be attached to one of these decls? 10478 // 10479 // Note that this way we pick up not only comments that precede the 10480 // declaration, but also comments that *follow* the declaration -- thanks to 10481 // the lookahead in the lexer: we've consumed the semicolon and looked 10482 // ahead through comments. 10483 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10484 Context.getCommentForDecl(Group[i], &PP); 10485 } 10486 } 10487 10488 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 10489 /// to introduce parameters into function prototype scope. 10490 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 10491 const DeclSpec &DS = D.getDeclSpec(); 10492 10493 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 10494 10495 // C++03 [dcl.stc]p2 also permits 'auto'. 10496 StorageClass SC = SC_None; 10497 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 10498 SC = SC_Register; 10499 } else if (getLangOpts().CPlusPlus && 10500 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 10501 SC = SC_Auto; 10502 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 10503 Diag(DS.getStorageClassSpecLoc(), 10504 diag::err_invalid_storage_class_in_func_decl); 10505 D.getMutableDeclSpec().ClearStorageClassSpecs(); 10506 } 10507 10508 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 10509 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 10510 << DeclSpec::getSpecifierName(TSCS); 10511 if (DS.isConstexprSpecified()) 10512 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 10513 << 0; 10514 if (DS.isConceptSpecified()) 10515 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 10516 10517 DiagnoseFunctionSpecifiers(DS); 10518 10519 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10520 QualType parmDeclType = TInfo->getType(); 10521 10522 if (getLangOpts().CPlusPlus) { 10523 // Check that there are no default arguments inside the type of this 10524 // parameter. 10525 CheckExtraCXXDefaultArguments(D); 10526 10527 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 10528 if (D.getCXXScopeSpec().isSet()) { 10529 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 10530 << D.getCXXScopeSpec().getRange(); 10531 D.getCXXScopeSpec().clear(); 10532 } 10533 } 10534 10535 // Ensure we have a valid name 10536 IdentifierInfo *II = nullptr; 10537 if (D.hasName()) { 10538 II = D.getIdentifier(); 10539 if (!II) { 10540 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 10541 << GetNameForDeclarator(D).getName(); 10542 D.setInvalidType(true); 10543 } 10544 } 10545 10546 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 10547 if (II) { 10548 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 10549 ForRedeclaration); 10550 LookupName(R, S); 10551 if (R.isSingleResult()) { 10552 NamedDecl *PrevDecl = R.getFoundDecl(); 10553 if (PrevDecl->isTemplateParameter()) { 10554 // Maybe we will complain about the shadowed template parameter. 10555 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10556 // Just pretend that we didn't see the previous declaration. 10557 PrevDecl = nullptr; 10558 } else if (S->isDeclScope(PrevDecl)) { 10559 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 10560 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10561 10562 // Recover by removing the name 10563 II = nullptr; 10564 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 10565 D.setInvalidType(true); 10566 } 10567 } 10568 } 10569 10570 // Temporarily put parameter variables in the translation unit, not 10571 // the enclosing context. This prevents them from accidentally 10572 // looking like class members in C++. 10573 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 10574 D.getLocStart(), 10575 D.getIdentifierLoc(), II, 10576 parmDeclType, TInfo, 10577 SC); 10578 10579 if (D.isInvalidType()) 10580 New->setInvalidDecl(); 10581 10582 assert(S->isFunctionPrototypeScope()); 10583 assert(S->getFunctionPrototypeDepth() >= 1); 10584 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 10585 S->getNextFunctionPrototypeIndex()); 10586 10587 // Add the parameter declaration into this scope. 10588 S->AddDecl(New); 10589 if (II) 10590 IdResolver.AddDecl(New); 10591 10592 ProcessDeclAttributes(S, New, D); 10593 10594 if (D.getDeclSpec().isModulePrivateSpecified()) 10595 Diag(New->getLocation(), diag::err_module_private_local) 10596 << 1 << New->getDeclName() 10597 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10598 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10599 10600 if (New->hasAttr<BlocksAttr>()) { 10601 Diag(New->getLocation(), diag::err_block_on_nonlocal); 10602 } 10603 return New; 10604 } 10605 10606 /// \brief Synthesizes a variable for a parameter arising from a 10607 /// typedef. 10608 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 10609 SourceLocation Loc, 10610 QualType T) { 10611 /* FIXME: setting StartLoc == Loc. 10612 Would it be worth to modify callers so as to provide proper source 10613 location for the unnamed parameters, embedding the parameter's type? */ 10614 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 10615 T, Context.getTrivialTypeSourceInfo(T, Loc), 10616 SC_None, nullptr); 10617 Param->setImplicit(); 10618 return Param; 10619 } 10620 10621 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 10622 ParmVarDecl * const *ParamEnd) { 10623 // Don't diagnose unused-parameter errors in template instantiations; we 10624 // will already have done so in the template itself. 10625 if (!ActiveTemplateInstantiations.empty()) 10626 return; 10627 10628 for (; Param != ParamEnd; ++Param) { 10629 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 10630 !(*Param)->hasAttr<UnusedAttr>()) { 10631 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 10632 << (*Param)->getDeclName(); 10633 } 10634 } 10635 } 10636 10637 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 10638 ParmVarDecl * const *ParamEnd, 10639 QualType ReturnTy, 10640 NamedDecl *D) { 10641 if (LangOpts.NumLargeByValueCopy == 0) // No check. 10642 return; 10643 10644 // Warn if the return value is pass-by-value and larger than the specified 10645 // threshold. 10646 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 10647 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 10648 if (Size > LangOpts.NumLargeByValueCopy) 10649 Diag(D->getLocation(), diag::warn_return_value_size) 10650 << D->getDeclName() << Size; 10651 } 10652 10653 // Warn if any parameter is pass-by-value and larger than the specified 10654 // threshold. 10655 for (; Param != ParamEnd; ++Param) { 10656 QualType T = (*Param)->getType(); 10657 if (T->isDependentType() || !T.isPODType(Context)) 10658 continue; 10659 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 10660 if (Size > LangOpts.NumLargeByValueCopy) 10661 Diag((*Param)->getLocation(), diag::warn_parameter_size) 10662 << (*Param)->getDeclName() << Size; 10663 } 10664 } 10665 10666 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 10667 SourceLocation NameLoc, IdentifierInfo *Name, 10668 QualType T, TypeSourceInfo *TSInfo, 10669 StorageClass SC) { 10670 // In ARC, infer a lifetime qualifier for appropriate parameter types. 10671 if (getLangOpts().ObjCAutoRefCount && 10672 T.getObjCLifetime() == Qualifiers::OCL_None && 10673 T->isObjCLifetimeType()) { 10674 10675 Qualifiers::ObjCLifetime lifetime; 10676 10677 // Special cases for arrays: 10678 // - if it's const, use __unsafe_unretained 10679 // - otherwise, it's an error 10680 if (T->isArrayType()) { 10681 if (!T.isConstQualified()) { 10682 DelayedDiagnostics.add( 10683 sema::DelayedDiagnostic::makeForbiddenType( 10684 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 10685 } 10686 lifetime = Qualifiers::OCL_ExplicitNone; 10687 } else { 10688 lifetime = T->getObjCARCImplicitLifetime(); 10689 } 10690 T = Context.getLifetimeQualifiedType(T, lifetime); 10691 } 10692 10693 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 10694 Context.getAdjustedParameterType(T), 10695 TSInfo, SC, nullptr); 10696 10697 // Parameters can not be abstract class types. 10698 // For record types, this is done by the AbstractClassUsageDiagnoser once 10699 // the class has been completely parsed. 10700 if (!CurContext->isRecord() && 10701 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 10702 AbstractParamType)) 10703 New->setInvalidDecl(); 10704 10705 // Parameter declarators cannot be interface types. All ObjC objects are 10706 // passed by reference. 10707 if (T->isObjCObjectType()) { 10708 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 10709 Diag(NameLoc, 10710 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 10711 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 10712 T = Context.getObjCObjectPointerType(T); 10713 New->setType(T); 10714 } 10715 10716 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 10717 // duration shall not be qualified by an address-space qualifier." 10718 // Since all parameters have automatic store duration, they can not have 10719 // an address space. 10720 if (T.getAddressSpace() != 0) { 10721 // OpenCL allows function arguments declared to be an array of a type 10722 // to be qualified with an address space. 10723 if (!(getLangOpts().OpenCL && T->isArrayType())) { 10724 Diag(NameLoc, diag::err_arg_with_address_space); 10725 New->setInvalidDecl(); 10726 } 10727 } 10728 10729 return New; 10730 } 10731 10732 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 10733 SourceLocation LocAfterDecls) { 10734 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10735 10736 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 10737 // for a K&R function. 10738 if (!FTI.hasPrototype) { 10739 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10740 --i; 10741 if (FTI.Params[i].Param == nullptr) { 10742 SmallString<256> Code; 10743 llvm::raw_svector_ostream(Code) 10744 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10745 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10746 << FTI.Params[i].Ident 10747 << FixItHint::CreateInsertion(LocAfterDecls, Code); 10748 10749 // Implicitly declare the argument as type 'int' for lack of a better 10750 // type. 10751 AttributeFactory attrs; 10752 DeclSpec DS(attrs); 10753 const char* PrevSpec; // unused 10754 unsigned DiagID; // unused 10755 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10756 DiagID, Context.getPrintingPolicy()); 10757 // Use the identifier location for the type source range. 10758 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10759 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10760 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10761 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10762 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10763 } 10764 } 10765 } 10766 } 10767 10768 Decl * 10769 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 10770 MultiTemplateParamsArg TemplateParameterLists, 10771 SkipBodyInfo *SkipBody) { 10772 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10773 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10774 Scope *ParentScope = FnBodyScope->getParent(); 10775 10776 D.setFunctionDefinitionKind(FDK_Definition); 10777 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 10778 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 10779 } 10780 10781 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10782 Consumer.HandleInlineMethodDefinition(D); 10783 } 10784 10785 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10786 const FunctionDecl*& PossibleZeroParamPrototype) { 10787 // Don't warn about invalid declarations. 10788 if (FD->isInvalidDecl()) 10789 return false; 10790 10791 // Or declarations that aren't global. 10792 if (!FD->isGlobal()) 10793 return false; 10794 10795 // Don't warn about C++ member functions. 10796 if (isa<CXXMethodDecl>(FD)) 10797 return false; 10798 10799 // Don't warn about 'main'. 10800 if (FD->isMain()) 10801 return false; 10802 10803 // Don't warn about inline functions. 10804 if (FD->isInlined()) 10805 return false; 10806 10807 // Don't warn about function templates. 10808 if (FD->getDescribedFunctionTemplate()) 10809 return false; 10810 10811 // Don't warn about function template specializations. 10812 if (FD->isFunctionTemplateSpecialization()) 10813 return false; 10814 10815 // Don't warn for OpenCL kernels. 10816 if (FD->hasAttr<OpenCLKernelAttr>()) 10817 return false; 10818 10819 // Don't warn on explicitly deleted functions. 10820 if (FD->isDeleted()) 10821 return false; 10822 10823 bool MissingPrototype = true; 10824 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10825 Prev; Prev = Prev->getPreviousDecl()) { 10826 // Ignore any declarations that occur in function or method 10827 // scope, because they aren't visible from the header. 10828 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10829 continue; 10830 10831 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10832 if (FD->getNumParams() == 0) 10833 PossibleZeroParamPrototype = Prev; 10834 break; 10835 } 10836 10837 return MissingPrototype; 10838 } 10839 10840 void 10841 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10842 const FunctionDecl *EffectiveDefinition, 10843 SkipBodyInfo *SkipBody) { 10844 // Don't complain if we're in GNU89 mode and the previous definition 10845 // was an extern inline function. 10846 const FunctionDecl *Definition = EffectiveDefinition; 10847 if (!Definition) 10848 if (!FD->isDefined(Definition)) 10849 return; 10850 10851 if (canRedefineFunction(Definition, getLangOpts())) 10852 return; 10853 10854 // If we don't have a visible definition of the function, and it's inline or 10855 // a template, skip the new definition. 10856 if (SkipBody && !hasVisibleDefinition(Definition) && 10857 (Definition->getFormalLinkage() == InternalLinkage || 10858 Definition->isInlined() || 10859 Definition->getDescribedFunctionTemplate() || 10860 Definition->getNumTemplateParameterLists())) { 10861 SkipBody->ShouldSkip = true; 10862 if (auto *TD = Definition->getDescribedFunctionTemplate()) 10863 makeMergedDefinitionVisible(TD, FD->getLocation()); 10864 else 10865 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 10866 FD->getLocation()); 10867 return; 10868 } 10869 10870 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10871 Definition->getStorageClass() == SC_Extern) 10872 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10873 << FD->getDeclName() << getLangOpts().CPlusPlus; 10874 else 10875 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10876 10877 Diag(Definition->getLocation(), diag::note_previous_definition); 10878 FD->setInvalidDecl(); 10879 } 10880 10881 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10882 Sema &S) { 10883 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10884 10885 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10886 LSI->CallOperator = CallOperator; 10887 LSI->Lambda = LambdaClass; 10888 LSI->ReturnType = CallOperator->getReturnType(); 10889 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10890 10891 if (LCD == LCD_None) 10892 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10893 else if (LCD == LCD_ByCopy) 10894 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10895 else if (LCD == LCD_ByRef) 10896 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10897 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10898 10899 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10900 LSI->Mutable = !CallOperator->isConst(); 10901 10902 // Add the captures to the LSI so they can be noted as already 10903 // captured within tryCaptureVar. 10904 auto I = LambdaClass->field_begin(); 10905 for (const auto &C : LambdaClass->captures()) { 10906 if (C.capturesVariable()) { 10907 VarDecl *VD = C.getCapturedVar(); 10908 if (VD->isInitCapture()) 10909 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10910 QualType CaptureType = VD->getType(); 10911 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10912 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10913 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 10914 /*EllipsisLoc*/C.isPackExpansion() 10915 ? C.getEllipsisLoc() : SourceLocation(), 10916 CaptureType, /*Expr*/ nullptr); 10917 10918 } else if (C.capturesThis()) { 10919 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10920 S.getCurrentThisType(), /*Expr*/ nullptr); 10921 } else { 10922 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10923 } 10924 ++I; 10925 } 10926 } 10927 10928 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 10929 SkipBodyInfo *SkipBody) { 10930 // Clear the last template instantiation error context. 10931 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10932 10933 if (!D) 10934 return D; 10935 FunctionDecl *FD = nullptr; 10936 10937 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10938 FD = FunTmpl->getTemplatedDecl(); 10939 else 10940 FD = cast<FunctionDecl>(D); 10941 10942 // See if this is a redefinition. 10943 if (!FD->isLateTemplateParsed()) { 10944 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 10945 10946 // If we're skipping the body, we're done. Don't enter the scope. 10947 if (SkipBody && SkipBody->ShouldSkip) 10948 return D; 10949 } 10950 10951 // If we are instantiating a generic lambda call operator, push 10952 // a LambdaScopeInfo onto the function stack. But use the information 10953 // that's already been calculated (ActOnLambdaExpr) to prime the current 10954 // LambdaScopeInfo. 10955 // When the template operator is being specialized, the LambdaScopeInfo, 10956 // has to be properly restored so that tryCaptureVariable doesn't try 10957 // and capture any new variables. In addition when calculating potential 10958 // captures during transformation of nested lambdas, it is necessary to 10959 // have the LSI properly restored. 10960 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10961 assert(ActiveTemplateInstantiations.size() && 10962 "There should be an active template instantiation on the stack " 10963 "when instantiating a generic lambda!"); 10964 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10965 } 10966 else 10967 // Enter a new function scope 10968 PushFunctionScope(); 10969 10970 // Builtin functions cannot be defined. 10971 if (unsigned BuiltinID = FD->getBuiltinID()) { 10972 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10973 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10974 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10975 FD->setInvalidDecl(); 10976 } 10977 } 10978 10979 // The return type of a function definition must be complete 10980 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10981 QualType ResultType = FD->getReturnType(); 10982 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10983 !FD->isInvalidDecl() && 10984 RequireCompleteType(FD->getLocation(), ResultType, 10985 diag::err_func_def_incomplete_result)) 10986 FD->setInvalidDecl(); 10987 10988 if (FnBodyScope) 10989 PushDeclContext(FnBodyScope, FD); 10990 10991 // Check the validity of our function parameters 10992 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10993 /*CheckParameterNames=*/true); 10994 10995 // Introduce our parameters into the function scope 10996 for (auto Param : FD->params()) { 10997 Param->setOwningFunction(FD); 10998 10999 // If this has an identifier, add it to the scope stack. 11000 if (Param->getIdentifier() && FnBodyScope) { 11001 CheckShadow(FnBodyScope, Param); 11002 11003 PushOnScopeChains(Param, FnBodyScope); 11004 } 11005 } 11006 11007 // If we had any tags defined in the function prototype, 11008 // introduce them into the function scope. 11009 if (FnBodyScope) { 11010 for (ArrayRef<NamedDecl *>::iterator 11011 I = FD->getDeclsInPrototypeScope().begin(), 11012 E = FD->getDeclsInPrototypeScope().end(); 11013 I != E; ++I) { 11014 NamedDecl *D = *I; 11015 11016 // Some of these decls (like enums) may have been pinned to the 11017 // translation unit for lack of a real context earlier. If so, remove 11018 // from the translation unit and reattach to the current context. 11019 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 11020 // Is the decl actually in the context? 11021 if (Context.getTranslationUnitDecl()->containsDecl(D)) 11022 Context.getTranslationUnitDecl()->removeDecl(D); 11023 // Either way, reassign the lexical decl context to our FunctionDecl. 11024 D->setLexicalDeclContext(CurContext); 11025 } 11026 11027 // If the decl has a non-null name, make accessible in the current scope. 11028 if (!D->getName().empty()) 11029 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 11030 11031 // Similarly, dive into enums and fish their constants out, making them 11032 // accessible in this scope. 11033 if (auto *ED = dyn_cast<EnumDecl>(D)) { 11034 for (auto *EI : ED->enumerators()) 11035 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11036 } 11037 } 11038 } 11039 11040 // Ensure that the function's exception specification is instantiated. 11041 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11042 ResolveExceptionSpec(D->getLocation(), FPT); 11043 11044 // dllimport cannot be applied to non-inline function definitions. 11045 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11046 !FD->isTemplateInstantiation()) { 11047 assert(!FD->hasAttr<DLLExportAttr>()); 11048 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11049 FD->setInvalidDecl(); 11050 return D; 11051 } 11052 // We want to attach documentation to original Decl (which might be 11053 // a function template). 11054 ActOnDocumentableDecl(D); 11055 if (getCurLexicalContext()->isObjCContainer() && 11056 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11057 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11058 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11059 11060 return D; 11061 } 11062 11063 /// \brief Given the set of return statements within a function body, 11064 /// compute the variables that are subject to the named return value 11065 /// optimization. 11066 /// 11067 /// Each of the variables that is subject to the named return value 11068 /// optimization will be marked as NRVO variables in the AST, and any 11069 /// return statement that has a marked NRVO variable as its NRVO candidate can 11070 /// use the named return value optimization. 11071 /// 11072 /// This function applies a very simplistic algorithm for NRVO: if every return 11073 /// statement in the scope of a variable has the same NRVO candidate, that 11074 /// candidate is an NRVO variable. 11075 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11076 ReturnStmt **Returns = Scope->Returns.data(); 11077 11078 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11079 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11080 if (!NRVOCandidate->isNRVOVariable()) 11081 Returns[I]->setNRVOCandidate(nullptr); 11082 } 11083 } 11084 } 11085 11086 bool Sema::canDelayFunctionBody(const Declarator &D) { 11087 // We can't delay parsing the body of a constexpr function template (yet). 11088 if (D.getDeclSpec().isConstexprSpecified()) 11089 return false; 11090 11091 // We can't delay parsing the body of a function template with a deduced 11092 // return type (yet). 11093 if (D.getDeclSpec().containsPlaceholderType()) { 11094 // If the placeholder introduces a non-deduced trailing return type, 11095 // we can still delay parsing it. 11096 if (D.getNumTypeObjects()) { 11097 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11098 if (Outer.Kind == DeclaratorChunk::Function && 11099 Outer.Fun.hasTrailingReturnType()) { 11100 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11101 return Ty.isNull() || !Ty->isUndeducedType(); 11102 } 11103 } 11104 return false; 11105 } 11106 11107 return true; 11108 } 11109 11110 bool Sema::canSkipFunctionBody(Decl *D) { 11111 // We cannot skip the body of a function (or function template) which is 11112 // constexpr, since we may need to evaluate its body in order to parse the 11113 // rest of the file. 11114 // We cannot skip the body of a function with an undeduced return type, 11115 // because any callers of that function need to know the type. 11116 if (const FunctionDecl *FD = D->getAsFunction()) 11117 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11118 return false; 11119 return Consumer.shouldSkipFunctionBody(D); 11120 } 11121 11122 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11123 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11124 FD->setHasSkippedBody(); 11125 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11126 MD->setHasSkippedBody(); 11127 return ActOnFinishFunctionBody(Decl, nullptr); 11128 } 11129 11130 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11131 return ActOnFinishFunctionBody(D, BodyArg, false); 11132 } 11133 11134 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11135 bool IsInstantiation) { 11136 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11137 11138 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11139 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11140 11141 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty()) 11142 CheckCompletedCoroutineBody(FD, Body); 11143 11144 if (FD) { 11145 FD->setBody(Body); 11146 11147 if (getLangOpts().CPlusPlus14) { 11148 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 11149 FD->getReturnType()->isUndeducedType()) { 11150 // If the function has a deduced result type but contains no 'return' 11151 // statements, the result type as written must be exactly 'auto', and 11152 // the deduced result type is 'void'. 11153 if (!FD->getReturnType()->getAs<AutoType>()) { 11154 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 11155 << FD->getReturnType(); 11156 FD->setInvalidDecl(); 11157 } else { 11158 // Substitute 'void' for the 'auto' in the type. 11159 TypeLoc ResultType = getReturnTypeLoc(FD); 11160 Context.adjustDeducedFunctionResultType( 11161 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 11162 } 11163 } 11164 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11165 // In C++11, we don't use 'auto' deduction rules for lambda call 11166 // operators because we don't support return type deduction. 11167 auto *LSI = getCurLambda(); 11168 if (LSI->HasImplicitReturnType) { 11169 deduceClosureReturnType(*LSI); 11170 11171 // C++11 [expr.prim.lambda]p4: 11172 // [...] if there are no return statements in the compound-statement 11173 // [the deduced type is] the type void 11174 QualType RetType = 11175 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11176 11177 // Update the return type to the deduced type. 11178 const FunctionProtoType *Proto = 11179 FD->getType()->getAs<FunctionProtoType>(); 11180 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11181 Proto->getExtProtoInfo())); 11182 } 11183 } 11184 11185 // The only way to be included in UndefinedButUsed is if there is an 11186 // ODR use before the definition. Avoid the expensive map lookup if this 11187 // is the first declaration. 11188 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11189 if (!FD->isExternallyVisible()) 11190 UndefinedButUsed.erase(FD); 11191 else if (FD->isInlined() && 11192 !LangOpts.GNUInline && 11193 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11194 UndefinedButUsed.erase(FD); 11195 } 11196 11197 // If the function implicitly returns zero (like 'main') or is naked, 11198 // don't complain about missing return statements. 11199 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11200 WP.disableCheckFallThrough(); 11201 11202 // MSVC permits the use of pure specifier (=0) on function definition, 11203 // defined at class scope, warn about this non-standard construct. 11204 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11205 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11206 11207 if (!FD->isInvalidDecl()) { 11208 // Don't diagnose unused parameters of defaulted or deleted functions. 11209 if (!FD->isDeleted() && !FD->isDefaulted()) 11210 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 11211 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 11212 FD->getReturnType(), FD); 11213 11214 // If this is a structor, we need a vtable. 11215 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11216 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11217 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 11218 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 11219 11220 // Try to apply the named return value optimization. We have to check 11221 // if we can do this here because lambdas keep return statements around 11222 // to deduce an implicit return type. 11223 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 11224 !FD->isDependentContext()) 11225 computeNRVO(Body, getCurFunction()); 11226 } 11227 11228 // GNU warning -Wmissing-prototypes: 11229 // Warn if a global function is defined without a previous 11230 // prototype declaration. This warning is issued even if the 11231 // definition itself provides a prototype. The aim is to detect 11232 // global functions that fail to be declared in header files. 11233 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 11234 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 11235 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 11236 11237 if (PossibleZeroParamPrototype) { 11238 // We found a declaration that is not a prototype, 11239 // but that could be a zero-parameter prototype 11240 if (TypeSourceInfo *TI = 11241 PossibleZeroParamPrototype->getTypeSourceInfo()) { 11242 TypeLoc TL = TI->getTypeLoc(); 11243 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 11244 Diag(PossibleZeroParamPrototype->getLocation(), 11245 diag::note_declaration_not_a_prototype) 11246 << PossibleZeroParamPrototype 11247 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 11248 } 11249 } 11250 } 11251 11252 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11253 const CXXMethodDecl *KeyFunction; 11254 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 11255 MD->isVirtual() && 11256 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 11257 MD == KeyFunction->getCanonicalDecl()) { 11258 // Update the key-function state if necessary for this ABI. 11259 if (FD->isInlined() && 11260 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11261 Context.setNonKeyFunction(MD); 11262 11263 // If the newly-chosen key function is already defined, then we 11264 // need to mark the vtable as used retroactively. 11265 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 11266 const FunctionDecl *Definition; 11267 if (KeyFunction && KeyFunction->isDefined(Definition)) 11268 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 11269 } else { 11270 // We just defined they key function; mark the vtable as used. 11271 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 11272 } 11273 } 11274 } 11275 11276 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 11277 "Function parsing confused"); 11278 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 11279 assert(MD == getCurMethodDecl() && "Method parsing confused"); 11280 MD->setBody(Body); 11281 if (!MD->isInvalidDecl()) { 11282 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 11283 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 11284 MD->getReturnType(), MD); 11285 11286 if (Body) 11287 computeNRVO(Body, getCurFunction()); 11288 } 11289 if (getCurFunction()->ObjCShouldCallSuper) { 11290 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 11291 << MD->getSelector().getAsString(); 11292 getCurFunction()->ObjCShouldCallSuper = false; 11293 } 11294 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 11295 const ObjCMethodDecl *InitMethod = nullptr; 11296 bool isDesignated = 11297 MD->isDesignatedInitializerForTheInterface(&InitMethod); 11298 assert(isDesignated && InitMethod); 11299 (void)isDesignated; 11300 11301 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 11302 auto IFace = MD->getClassInterface(); 11303 if (!IFace) 11304 return false; 11305 auto SuperD = IFace->getSuperClass(); 11306 if (!SuperD) 11307 return false; 11308 return SuperD->getIdentifier() == 11309 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 11310 }; 11311 // Don't issue this warning for unavailable inits or direct subclasses 11312 // of NSObject. 11313 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 11314 Diag(MD->getLocation(), 11315 diag::warn_objc_designated_init_missing_super_call); 11316 Diag(InitMethod->getLocation(), 11317 diag::note_objc_designated_init_marked_here); 11318 } 11319 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 11320 } 11321 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 11322 // Don't issue this warning for unavaialable inits. 11323 if (!MD->isUnavailable()) 11324 Diag(MD->getLocation(), 11325 diag::warn_objc_secondary_init_missing_init_call); 11326 getCurFunction()->ObjCWarnForNoInitDelegation = false; 11327 } 11328 } else { 11329 return nullptr; 11330 } 11331 11332 assert(!getCurFunction()->ObjCShouldCallSuper && 11333 "This should only be set for ObjC methods, which should have been " 11334 "handled in the block above."); 11335 11336 // Verify and clean out per-function state. 11337 if (Body && (!FD || !FD->isDefaulted())) { 11338 // C++ constructors that have function-try-blocks can't have return 11339 // statements in the handlers of that block. (C++ [except.handle]p14) 11340 // Verify this. 11341 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 11342 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 11343 11344 // Verify that gotos and switch cases don't jump into scopes illegally. 11345 if (getCurFunction()->NeedsScopeChecking() && 11346 !PP.isCodeCompletionEnabled()) 11347 DiagnoseInvalidJumps(Body); 11348 11349 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 11350 if (!Destructor->getParent()->isDependentType()) 11351 CheckDestructor(Destructor); 11352 11353 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11354 Destructor->getParent()); 11355 } 11356 11357 // If any errors have occurred, clear out any temporaries that may have 11358 // been leftover. This ensures that these temporaries won't be picked up for 11359 // deletion in some later function. 11360 if (getDiagnostics().hasErrorOccurred() || 11361 getDiagnostics().getSuppressAllDiagnostics()) { 11362 DiscardCleanupsInEvaluationContext(); 11363 } 11364 if (!getDiagnostics().hasUncompilableErrorOccurred() && 11365 !isa<FunctionTemplateDecl>(dcl)) { 11366 // Since the body is valid, issue any analysis-based warnings that are 11367 // enabled. 11368 ActivePolicy = &WP; 11369 } 11370 11371 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 11372 (!CheckConstexprFunctionDecl(FD) || 11373 !CheckConstexprFunctionBody(FD, Body))) 11374 FD->setInvalidDecl(); 11375 11376 if (FD && FD->hasAttr<NakedAttr>()) { 11377 for (const Stmt *S : Body->children()) { 11378 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 11379 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 11380 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 11381 FD->setInvalidDecl(); 11382 break; 11383 } 11384 } 11385 } 11386 11387 assert(ExprCleanupObjects.size() == 11388 ExprEvalContexts.back().NumCleanupObjects && 11389 "Leftover temporaries in function"); 11390 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 11391 assert(MaybeODRUseExprs.empty() && 11392 "Leftover expressions for odr-use checking"); 11393 } 11394 11395 if (!IsInstantiation) 11396 PopDeclContext(); 11397 11398 PopFunctionScopeInfo(ActivePolicy, dcl); 11399 // If any errors have occurred, clear out any temporaries that may have 11400 // been leftover. This ensures that these temporaries won't be picked up for 11401 // deletion in some later function. 11402 if (getDiagnostics().hasErrorOccurred()) { 11403 DiscardCleanupsInEvaluationContext(); 11404 } 11405 11406 return dcl; 11407 } 11408 11409 /// When we finish delayed parsing of an attribute, we must attach it to the 11410 /// relevant Decl. 11411 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 11412 ParsedAttributes &Attrs) { 11413 // Always attach attributes to the underlying decl. 11414 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 11415 D = TD->getTemplatedDecl(); 11416 ProcessDeclAttributeList(S, D, Attrs.getList()); 11417 11418 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 11419 if (Method->isStatic()) 11420 checkThisInStaticMemberFunctionAttributes(Method); 11421 } 11422 11423 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 11424 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 11425 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 11426 IdentifierInfo &II, Scope *S) { 11427 // Before we produce a declaration for an implicitly defined 11428 // function, see whether there was a locally-scoped declaration of 11429 // this name as a function or variable. If so, use that 11430 // (non-visible) declaration, and complain about it. 11431 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 11432 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 11433 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 11434 return ExternCPrev; 11435 } 11436 11437 // Extension in C99. Legal in C90, but warn about it. 11438 unsigned diag_id; 11439 if (II.getName().startswith("__builtin_")) 11440 diag_id = diag::warn_builtin_unknown; 11441 else if (getLangOpts().C99) 11442 diag_id = diag::ext_implicit_function_decl; 11443 else 11444 diag_id = diag::warn_implicit_function_decl; 11445 Diag(Loc, diag_id) << &II; 11446 11447 // Because typo correction is expensive, only do it if the implicit 11448 // function declaration is going to be treated as an error. 11449 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 11450 TypoCorrection Corrected; 11451 if (S && 11452 (Corrected = CorrectTypo( 11453 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 11454 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 11455 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 11456 /*ErrorRecovery*/false); 11457 } 11458 11459 // Set a Declarator for the implicit definition: int foo(); 11460 const char *Dummy; 11461 AttributeFactory attrFactory; 11462 DeclSpec DS(attrFactory); 11463 unsigned DiagID; 11464 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 11465 Context.getPrintingPolicy()); 11466 (void)Error; // Silence warning. 11467 assert(!Error && "Error setting up implicit decl!"); 11468 SourceLocation NoLoc; 11469 Declarator D(DS, Declarator::BlockContext); 11470 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 11471 /*IsAmbiguous=*/false, 11472 /*LParenLoc=*/NoLoc, 11473 /*Params=*/nullptr, 11474 /*NumParams=*/0, 11475 /*EllipsisLoc=*/NoLoc, 11476 /*RParenLoc=*/NoLoc, 11477 /*TypeQuals=*/0, 11478 /*RefQualifierIsLvalueRef=*/true, 11479 /*RefQualifierLoc=*/NoLoc, 11480 /*ConstQualifierLoc=*/NoLoc, 11481 /*VolatileQualifierLoc=*/NoLoc, 11482 /*RestrictQualifierLoc=*/NoLoc, 11483 /*MutableLoc=*/NoLoc, 11484 EST_None, 11485 /*ESpecRange=*/SourceRange(), 11486 /*Exceptions=*/nullptr, 11487 /*ExceptionRanges=*/nullptr, 11488 /*NumExceptions=*/0, 11489 /*NoexceptExpr=*/nullptr, 11490 /*ExceptionSpecTokens=*/nullptr, 11491 Loc, Loc, D), 11492 DS.getAttributes(), 11493 SourceLocation()); 11494 D.SetIdentifier(&II, Loc); 11495 11496 // Insert this function into translation-unit scope. 11497 11498 DeclContext *PrevDC = CurContext; 11499 CurContext = Context.getTranslationUnitDecl(); 11500 11501 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 11502 FD->setImplicit(); 11503 11504 CurContext = PrevDC; 11505 11506 AddKnownFunctionAttributes(FD); 11507 11508 return FD; 11509 } 11510 11511 /// \brief Adds any function attributes that we know a priori based on 11512 /// the declaration of this function. 11513 /// 11514 /// These attributes can apply both to implicitly-declared builtins 11515 /// (like __builtin___printf_chk) or to library-declared functions 11516 /// like NSLog or printf. 11517 /// 11518 /// We need to check for duplicate attributes both here and where user-written 11519 /// attributes are applied to declarations. 11520 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 11521 if (FD->isInvalidDecl()) 11522 return; 11523 11524 // If this is a built-in function, map its builtin attributes to 11525 // actual attributes. 11526 if (unsigned BuiltinID = FD->getBuiltinID()) { 11527 // Handle printf-formatting attributes. 11528 unsigned FormatIdx; 11529 bool HasVAListArg; 11530 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 11531 if (!FD->hasAttr<FormatAttr>()) { 11532 const char *fmt = "printf"; 11533 unsigned int NumParams = FD->getNumParams(); 11534 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 11535 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 11536 fmt = "NSString"; 11537 FD->addAttr(FormatAttr::CreateImplicit(Context, 11538 &Context.Idents.get(fmt), 11539 FormatIdx+1, 11540 HasVAListArg ? 0 : FormatIdx+2, 11541 FD->getLocation())); 11542 } 11543 } 11544 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 11545 HasVAListArg)) { 11546 if (!FD->hasAttr<FormatAttr>()) 11547 FD->addAttr(FormatAttr::CreateImplicit(Context, 11548 &Context.Idents.get("scanf"), 11549 FormatIdx+1, 11550 HasVAListArg ? 0 : FormatIdx+2, 11551 FD->getLocation())); 11552 } 11553 11554 // Mark const if we don't care about errno and that is the only 11555 // thing preventing the function from being const. This allows 11556 // IRgen to use LLVM intrinsics for such functions. 11557 if (!getLangOpts().MathErrno && 11558 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 11559 if (!FD->hasAttr<ConstAttr>()) 11560 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11561 } 11562 11563 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 11564 !FD->hasAttr<ReturnsTwiceAttr>()) 11565 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 11566 FD->getLocation())); 11567 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 11568 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 11569 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 11570 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11571 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads && 11572 Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 11573 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 11574 // Assign appropriate attribute depending on CUDA compilation 11575 // mode and the target builtin belongs to. E.g. during host 11576 // compilation, aux builtins are __device__, the rest are __host__. 11577 if (getLangOpts().CUDAIsDevice != 11578 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 11579 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 11580 else 11581 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 11582 } 11583 } 11584 11585 IdentifierInfo *Name = FD->getIdentifier(); 11586 if (!Name) 11587 return; 11588 if ((!getLangOpts().CPlusPlus && 11589 FD->getDeclContext()->isTranslationUnit()) || 11590 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 11591 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 11592 LinkageSpecDecl::lang_c)) { 11593 // Okay: this could be a libc/libm/Objective-C function we know 11594 // about. 11595 } else 11596 return; 11597 11598 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 11599 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 11600 // target-specific builtins, perhaps? 11601 if (!FD->hasAttr<FormatAttr>()) 11602 FD->addAttr(FormatAttr::CreateImplicit(Context, 11603 &Context.Idents.get("printf"), 2, 11604 Name->isStr("vasprintf") ? 0 : 3, 11605 FD->getLocation())); 11606 } 11607 11608 if (Name->isStr("__CFStringMakeConstantString")) { 11609 // We already have a __builtin___CFStringMakeConstantString, 11610 // but builds that use -fno-constant-cfstrings don't go through that. 11611 if (!FD->hasAttr<FormatArgAttr>()) 11612 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 11613 FD->getLocation())); 11614 } 11615 } 11616 11617 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 11618 TypeSourceInfo *TInfo) { 11619 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 11620 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 11621 11622 if (!TInfo) { 11623 assert(D.isInvalidType() && "no declarator info for valid type"); 11624 TInfo = Context.getTrivialTypeSourceInfo(T); 11625 } 11626 11627 // Scope manipulation handled by caller. 11628 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 11629 D.getLocStart(), 11630 D.getIdentifierLoc(), 11631 D.getIdentifier(), 11632 TInfo); 11633 11634 // Bail out immediately if we have an invalid declaration. 11635 if (D.isInvalidType()) { 11636 NewTD->setInvalidDecl(); 11637 return NewTD; 11638 } 11639 11640 if (D.getDeclSpec().isModulePrivateSpecified()) { 11641 if (CurContext->isFunctionOrMethod()) 11642 Diag(NewTD->getLocation(), diag::err_module_private_local) 11643 << 2 << NewTD->getDeclName() 11644 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11645 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11646 else 11647 NewTD->setModulePrivate(); 11648 } 11649 11650 // C++ [dcl.typedef]p8: 11651 // If the typedef declaration defines an unnamed class (or 11652 // enum), the first typedef-name declared by the declaration 11653 // to be that class type (or enum type) is used to denote the 11654 // class type (or enum type) for linkage purposes only. 11655 // We need to check whether the type was declared in the declaration. 11656 switch (D.getDeclSpec().getTypeSpecType()) { 11657 case TST_enum: 11658 case TST_struct: 11659 case TST_interface: 11660 case TST_union: 11661 case TST_class: { 11662 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 11663 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 11664 break; 11665 } 11666 11667 default: 11668 break; 11669 } 11670 11671 return NewTD; 11672 } 11673 11674 /// \brief Check that this is a valid underlying type for an enum declaration. 11675 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 11676 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 11677 QualType T = TI->getType(); 11678 11679 if (T->isDependentType()) 11680 return false; 11681 11682 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 11683 if (BT->isInteger()) 11684 return false; 11685 11686 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 11687 return true; 11688 } 11689 11690 /// Check whether this is a valid redeclaration of a previous enumeration. 11691 /// \return true if the redeclaration was invalid. 11692 bool Sema::CheckEnumRedeclaration( 11693 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 11694 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 11695 bool IsFixed = !EnumUnderlyingTy.isNull(); 11696 11697 if (IsScoped != Prev->isScoped()) { 11698 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 11699 << Prev->isScoped(); 11700 Diag(Prev->getLocation(), diag::note_previous_declaration); 11701 return true; 11702 } 11703 11704 if (IsFixed && Prev->isFixed()) { 11705 if (!EnumUnderlyingTy->isDependentType() && 11706 !Prev->getIntegerType()->isDependentType() && 11707 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 11708 Prev->getIntegerType())) { 11709 // TODO: Highlight the underlying type of the redeclaration. 11710 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 11711 << EnumUnderlyingTy << Prev->getIntegerType(); 11712 Diag(Prev->getLocation(), diag::note_previous_declaration) 11713 << Prev->getIntegerTypeRange(); 11714 return true; 11715 } 11716 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 11717 ; 11718 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 11719 ; 11720 } else if (IsFixed != Prev->isFixed()) { 11721 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 11722 << Prev->isFixed(); 11723 Diag(Prev->getLocation(), diag::note_previous_declaration); 11724 return true; 11725 } 11726 11727 return false; 11728 } 11729 11730 /// \brief Get diagnostic %select index for tag kind for 11731 /// redeclaration diagnostic message. 11732 /// WARNING: Indexes apply to particular diagnostics only! 11733 /// 11734 /// \returns diagnostic %select index. 11735 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 11736 switch (Tag) { 11737 case TTK_Struct: return 0; 11738 case TTK_Interface: return 1; 11739 case TTK_Class: return 2; 11740 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 11741 } 11742 } 11743 11744 /// \brief Determine if tag kind is a class-key compatible with 11745 /// class for redeclaration (class, struct, or __interface). 11746 /// 11747 /// \returns true iff the tag kind is compatible. 11748 static bool isClassCompatTagKind(TagTypeKind Tag) 11749 { 11750 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 11751 } 11752 11753 /// \brief Determine whether a tag with a given kind is acceptable 11754 /// as a redeclaration of the given tag declaration. 11755 /// 11756 /// \returns true if the new tag kind is acceptable, false otherwise. 11757 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 11758 TagTypeKind NewTag, bool isDefinition, 11759 SourceLocation NewTagLoc, 11760 const IdentifierInfo *Name) { 11761 // C++ [dcl.type.elab]p3: 11762 // The class-key or enum keyword present in the 11763 // elaborated-type-specifier shall agree in kind with the 11764 // declaration to which the name in the elaborated-type-specifier 11765 // refers. This rule also applies to the form of 11766 // elaborated-type-specifier that declares a class-name or 11767 // friend class since it can be construed as referring to the 11768 // definition of the class. Thus, in any 11769 // elaborated-type-specifier, the enum keyword shall be used to 11770 // refer to an enumeration (7.2), the union class-key shall be 11771 // used to refer to a union (clause 9), and either the class or 11772 // struct class-key shall be used to refer to a class (clause 9) 11773 // declared using the class or struct class-key. 11774 TagTypeKind OldTag = Previous->getTagKind(); 11775 if (!isDefinition || !isClassCompatTagKind(NewTag)) 11776 if (OldTag == NewTag) 11777 return true; 11778 11779 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 11780 // Warn about the struct/class tag mismatch. 11781 bool isTemplate = false; 11782 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 11783 isTemplate = Record->getDescribedClassTemplate(); 11784 11785 if (!ActiveTemplateInstantiations.empty()) { 11786 // In a template instantiation, do not offer fix-its for tag mismatches 11787 // since they usually mess up the template instead of fixing the problem. 11788 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11789 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 11790 << getRedeclDiagFromTagKind(OldTag); 11791 return true; 11792 } 11793 11794 if (isDefinition) { 11795 // On definitions, check previous tags and issue a fix-it for each 11796 // one that doesn't match the current tag. 11797 if (Previous->getDefinition()) { 11798 // Don't suggest fix-its for redefinitions. 11799 return true; 11800 } 11801 11802 bool previousMismatch = false; 11803 for (auto I : Previous->redecls()) { 11804 if (I->getTagKind() != NewTag) { 11805 if (!previousMismatch) { 11806 previousMismatch = true; 11807 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11808 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 11809 << getRedeclDiagFromTagKind(I->getTagKind()); 11810 } 11811 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11812 << getRedeclDiagFromTagKind(NewTag) 11813 << FixItHint::CreateReplacement(I->getInnerLocStart(), 11814 TypeWithKeyword::getTagTypeKindName(NewTag)); 11815 } 11816 } 11817 return true; 11818 } 11819 11820 // Check for a previous definition. If current tag and definition 11821 // are same type, do nothing. If no definition, but disagree with 11822 // with previous tag type, give a warning, but no fix-it. 11823 const TagDecl *Redecl = Previous->getDefinition() ? 11824 Previous->getDefinition() : Previous; 11825 if (Redecl->getTagKind() == NewTag) { 11826 return true; 11827 } 11828 11829 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11830 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 11831 << getRedeclDiagFromTagKind(OldTag); 11832 Diag(Redecl->getLocation(), diag::note_previous_use); 11833 11834 // If there is a previous definition, suggest a fix-it. 11835 if (Previous->getDefinition()) { 11836 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11837 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11838 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11839 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11840 } 11841 11842 return true; 11843 } 11844 return false; 11845 } 11846 11847 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11848 /// from an outer enclosing namespace or file scope inside a friend declaration. 11849 /// This should provide the commented out code in the following snippet: 11850 /// namespace N { 11851 /// struct X; 11852 /// namespace M { 11853 /// struct Y { friend struct /*N::*/ X; }; 11854 /// } 11855 /// } 11856 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11857 SourceLocation NameLoc) { 11858 // While the decl is in a namespace, do repeated lookup of that name and see 11859 // if we get the same namespace back. If we do not, continue until 11860 // translation unit scope, at which point we have a fully qualified NNS. 11861 SmallVector<IdentifierInfo *, 4> Namespaces; 11862 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11863 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11864 // This tag should be declared in a namespace, which can only be enclosed by 11865 // other namespaces. Bail if there's an anonymous namespace in the chain. 11866 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11867 if (!Namespace || Namespace->isAnonymousNamespace()) 11868 return FixItHint(); 11869 IdentifierInfo *II = Namespace->getIdentifier(); 11870 Namespaces.push_back(II); 11871 NamedDecl *Lookup = SemaRef.LookupSingleName( 11872 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11873 if (Lookup == Namespace) 11874 break; 11875 } 11876 11877 // Once we have all the namespaces, reverse them to go outermost first, and 11878 // build an NNS. 11879 SmallString<64> Insertion; 11880 llvm::raw_svector_ostream OS(Insertion); 11881 if (DC->isTranslationUnit()) 11882 OS << "::"; 11883 std::reverse(Namespaces.begin(), Namespaces.end()); 11884 for (auto *II : Namespaces) 11885 OS << II->getName() << "::"; 11886 return FixItHint::CreateInsertion(NameLoc, Insertion); 11887 } 11888 11889 /// \brief Determine whether a tag originally declared in context \p OldDC can 11890 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 11891 /// found a declaration in \p OldDC as a previous decl, perhaps through a 11892 /// using-declaration). 11893 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 11894 DeclContext *NewDC) { 11895 OldDC = OldDC->getRedeclContext(); 11896 NewDC = NewDC->getRedeclContext(); 11897 11898 if (OldDC->Equals(NewDC)) 11899 return true; 11900 11901 // In MSVC mode, we allow a redeclaration if the contexts are related (either 11902 // encloses the other). 11903 if (S.getLangOpts().MSVCCompat && 11904 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 11905 return true; 11906 11907 return false; 11908 } 11909 11910 /// Find the DeclContext in which a tag is implicitly declared if we see an 11911 /// elaborated type specifier in the specified context, and lookup finds 11912 /// nothing. 11913 static DeclContext *getTagInjectionContext(DeclContext *DC) { 11914 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 11915 DC = DC->getParent(); 11916 return DC; 11917 } 11918 11919 /// Find the Scope in which a tag is implicitly declared if we see an 11920 /// elaborated type specifier in the specified context, and lookup finds 11921 /// nothing. 11922 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 11923 while (S->isClassScope() || 11924 (LangOpts.CPlusPlus && 11925 S->isFunctionPrototypeScope()) || 11926 ((S->getFlags() & Scope::DeclScope) == 0) || 11927 (S->getEntity() && S->getEntity()->isTransparentContext())) 11928 S = S->getParent(); 11929 return S; 11930 } 11931 11932 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 11933 /// former case, Name will be non-null. In the later case, Name will be null. 11934 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11935 /// reference/declaration/definition of a tag. 11936 /// 11937 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 11938 /// trailing-type-specifier) other than one in an alias-declaration. 11939 /// 11940 /// \param SkipBody If non-null, will be set to indicate if the caller should 11941 /// skip the definition of this tag and treat it as if it were a declaration. 11942 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11943 SourceLocation KWLoc, CXXScopeSpec &SS, 11944 IdentifierInfo *Name, SourceLocation NameLoc, 11945 AttributeList *Attr, AccessSpecifier AS, 11946 SourceLocation ModulePrivateLoc, 11947 MultiTemplateParamsArg TemplateParameterLists, 11948 bool &OwnedDecl, bool &IsDependent, 11949 SourceLocation ScopedEnumKWLoc, 11950 bool ScopedEnumUsesClassTag, 11951 TypeResult UnderlyingType, 11952 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 11953 // If this is not a definition, it must have a name. 11954 IdentifierInfo *OrigName = Name; 11955 assert((Name != nullptr || TUK == TUK_Definition) && 11956 "Nameless record must be a definition!"); 11957 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11958 11959 OwnedDecl = false; 11960 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11961 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11962 11963 // FIXME: Check explicit specializations more carefully. 11964 bool isExplicitSpecialization = false; 11965 bool Invalid = false; 11966 11967 // We only need to do this matching if we have template parameters 11968 // or a scope specifier, which also conveniently avoids this work 11969 // for non-C++ cases. 11970 if (TemplateParameterLists.size() > 0 || 11971 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11972 if (TemplateParameterList *TemplateParams = 11973 MatchTemplateParametersToScopeSpecifier( 11974 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11975 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11976 if (Kind == TTK_Enum) { 11977 Diag(KWLoc, diag::err_enum_template); 11978 return nullptr; 11979 } 11980 11981 if (TemplateParams->size() > 0) { 11982 // This is a declaration or definition of a class template (which may 11983 // be a member of another template). 11984 11985 if (Invalid) 11986 return nullptr; 11987 11988 OwnedDecl = false; 11989 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11990 SS, Name, NameLoc, Attr, 11991 TemplateParams, AS, 11992 ModulePrivateLoc, 11993 /*FriendLoc*/SourceLocation(), 11994 TemplateParameterLists.size()-1, 11995 TemplateParameterLists.data(), 11996 SkipBody); 11997 return Result.get(); 11998 } else { 11999 // The "template<>" header is extraneous. 12000 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12001 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12002 isExplicitSpecialization = true; 12003 } 12004 } 12005 } 12006 12007 // Figure out the underlying type if this a enum declaration. We need to do 12008 // this early, because it's needed to detect if this is an incompatible 12009 // redeclaration. 12010 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12011 bool EnumUnderlyingIsImplicit = false; 12012 12013 if (Kind == TTK_Enum) { 12014 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12015 // No underlying type explicitly specified, or we failed to parse the 12016 // type, default to int. 12017 EnumUnderlying = Context.IntTy.getTypePtr(); 12018 else if (UnderlyingType.get()) { 12019 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12020 // integral type; any cv-qualification is ignored. 12021 TypeSourceInfo *TI = nullptr; 12022 GetTypeFromParser(UnderlyingType.get(), &TI); 12023 EnumUnderlying = TI; 12024 12025 if (CheckEnumUnderlyingType(TI)) 12026 // Recover by falling back to int. 12027 EnumUnderlying = Context.IntTy.getTypePtr(); 12028 12029 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12030 UPPC_FixedUnderlyingType)) 12031 EnumUnderlying = Context.IntTy.getTypePtr(); 12032 12033 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12034 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12035 // Microsoft enums are always of int type. 12036 EnumUnderlying = Context.IntTy.getTypePtr(); 12037 EnumUnderlyingIsImplicit = true; 12038 } 12039 } 12040 } 12041 12042 DeclContext *SearchDC = CurContext; 12043 DeclContext *DC = CurContext; 12044 bool isStdBadAlloc = false; 12045 12046 RedeclarationKind Redecl = ForRedeclaration; 12047 if (TUK == TUK_Friend || TUK == TUK_Reference) 12048 Redecl = NotForRedeclaration; 12049 12050 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12051 if (Name && SS.isNotEmpty()) { 12052 // We have a nested-name tag ('struct foo::bar'). 12053 12054 // Check for invalid 'foo::'. 12055 if (SS.isInvalid()) { 12056 Name = nullptr; 12057 goto CreateNewDecl; 12058 } 12059 12060 // If this is a friend or a reference to a class in a dependent 12061 // context, don't try to make a decl for it. 12062 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12063 DC = computeDeclContext(SS, false); 12064 if (!DC) { 12065 IsDependent = true; 12066 return nullptr; 12067 } 12068 } else { 12069 DC = computeDeclContext(SS, true); 12070 if (!DC) { 12071 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12072 << SS.getRange(); 12073 return nullptr; 12074 } 12075 } 12076 12077 if (RequireCompleteDeclContext(SS, DC)) 12078 return nullptr; 12079 12080 SearchDC = DC; 12081 // Look-up name inside 'foo::'. 12082 LookupQualifiedName(Previous, DC); 12083 12084 if (Previous.isAmbiguous()) 12085 return nullptr; 12086 12087 if (Previous.empty()) { 12088 // Name lookup did not find anything. However, if the 12089 // nested-name-specifier refers to the current instantiation, 12090 // and that current instantiation has any dependent base 12091 // classes, we might find something at instantiation time: treat 12092 // this as a dependent elaborated-type-specifier. 12093 // But this only makes any sense for reference-like lookups. 12094 if (Previous.wasNotFoundInCurrentInstantiation() && 12095 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12096 IsDependent = true; 12097 return nullptr; 12098 } 12099 12100 // A tag 'foo::bar' must already exist. 12101 Diag(NameLoc, diag::err_not_tag_in_scope) 12102 << Kind << Name << DC << SS.getRange(); 12103 Name = nullptr; 12104 Invalid = true; 12105 goto CreateNewDecl; 12106 } 12107 } else if (Name) { 12108 // C++14 [class.mem]p14: 12109 // If T is the name of a class, then each of the following shall have a 12110 // name different from T: 12111 // -- every member of class T that is itself a type 12112 if (TUK != TUK_Reference && TUK != TUK_Friend && 12113 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 12114 return nullptr; 12115 12116 // If this is a named struct, check to see if there was a previous forward 12117 // declaration or definition. 12118 // FIXME: We're looking into outer scopes here, even when we 12119 // shouldn't be. Doing so can result in ambiguities that we 12120 // shouldn't be diagnosing. 12121 LookupName(Previous, S); 12122 12123 // When declaring or defining a tag, ignore ambiguities introduced 12124 // by types using'ed into this scope. 12125 if (Previous.isAmbiguous() && 12126 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 12127 LookupResult::Filter F = Previous.makeFilter(); 12128 while (F.hasNext()) { 12129 NamedDecl *ND = F.next(); 12130 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 12131 F.erase(); 12132 } 12133 F.done(); 12134 } 12135 12136 // C++11 [namespace.memdef]p3: 12137 // If the name in a friend declaration is neither qualified nor 12138 // a template-id and the declaration is a function or an 12139 // elaborated-type-specifier, the lookup to determine whether 12140 // the entity has been previously declared shall not consider 12141 // any scopes outside the innermost enclosing namespace. 12142 // 12143 // MSVC doesn't implement the above rule for types, so a friend tag 12144 // declaration may be a redeclaration of a type declared in an enclosing 12145 // scope. They do implement this rule for friend functions. 12146 // 12147 // Does it matter that this should be by scope instead of by 12148 // semantic context? 12149 if (!Previous.empty() && TUK == TUK_Friend) { 12150 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 12151 LookupResult::Filter F = Previous.makeFilter(); 12152 bool FriendSawTagOutsideEnclosingNamespace = false; 12153 while (F.hasNext()) { 12154 NamedDecl *ND = F.next(); 12155 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12156 if (DC->isFileContext() && 12157 !EnclosingNS->Encloses(ND->getDeclContext())) { 12158 if (getLangOpts().MSVCCompat) 12159 FriendSawTagOutsideEnclosingNamespace = true; 12160 else 12161 F.erase(); 12162 } 12163 } 12164 F.done(); 12165 12166 // Diagnose this MSVC extension in the easy case where lookup would have 12167 // unambiguously found something outside the enclosing namespace. 12168 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 12169 NamedDecl *ND = Previous.getFoundDecl(); 12170 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 12171 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 12172 } 12173 } 12174 12175 // Note: there used to be some attempt at recovery here. 12176 if (Previous.isAmbiguous()) 12177 return nullptr; 12178 12179 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 12180 // FIXME: This makes sure that we ignore the contexts associated 12181 // with C structs, unions, and enums when looking for a matching 12182 // tag declaration or definition. See the similar lookup tweak 12183 // in Sema::LookupName; is there a better way to deal with this? 12184 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 12185 SearchDC = SearchDC->getParent(); 12186 } 12187 } 12188 12189 if (Previous.isSingleResult() && 12190 Previous.getFoundDecl()->isTemplateParameter()) { 12191 // Maybe we will complain about the shadowed template parameter. 12192 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 12193 // Just pretend that we didn't see the previous declaration. 12194 Previous.clear(); 12195 } 12196 12197 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 12198 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 12199 // This is a declaration of or a reference to "std::bad_alloc". 12200 isStdBadAlloc = true; 12201 12202 if (Previous.empty() && StdBadAlloc) { 12203 // std::bad_alloc has been implicitly declared (but made invisible to 12204 // name lookup). Fill in this implicit declaration as the previous 12205 // declaration, so that the declarations get chained appropriately. 12206 Previous.addDecl(getStdBadAlloc()); 12207 } 12208 } 12209 12210 // If we didn't find a previous declaration, and this is a reference 12211 // (or friend reference), move to the correct scope. In C++, we 12212 // also need to do a redeclaration lookup there, just in case 12213 // there's a shadow friend decl. 12214 if (Name && Previous.empty() && 12215 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12216 if (Invalid) goto CreateNewDecl; 12217 assert(SS.isEmpty()); 12218 12219 if (TUK == TUK_Reference) { 12220 // C++ [basic.scope.pdecl]p5: 12221 // -- for an elaborated-type-specifier of the form 12222 // 12223 // class-key identifier 12224 // 12225 // if the elaborated-type-specifier is used in the 12226 // decl-specifier-seq or parameter-declaration-clause of a 12227 // function defined in namespace scope, the identifier is 12228 // declared as a class-name in the namespace that contains 12229 // the declaration; otherwise, except as a friend 12230 // declaration, the identifier is declared in the smallest 12231 // non-class, non-function-prototype scope that contains the 12232 // declaration. 12233 // 12234 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 12235 // C structs and unions. 12236 // 12237 // It is an error in C++ to declare (rather than define) an enum 12238 // type, including via an elaborated type specifier. We'll 12239 // diagnose that later; for now, declare the enum in the same 12240 // scope as we would have picked for any other tag type. 12241 // 12242 // GNU C also supports this behavior as part of its incomplete 12243 // enum types extension, while GNU C++ does not. 12244 // 12245 // Find the context where we'll be declaring the tag. 12246 // FIXME: We would like to maintain the current DeclContext as the 12247 // lexical context, 12248 SearchDC = getTagInjectionContext(SearchDC); 12249 12250 // Find the scope where we'll be declaring the tag. 12251 S = getTagInjectionScope(S, getLangOpts()); 12252 } else { 12253 assert(TUK == TUK_Friend); 12254 // C++ [namespace.memdef]p3: 12255 // If a friend declaration in a non-local class first declares a 12256 // class or function, the friend class or function is a member of 12257 // the innermost enclosing namespace. 12258 SearchDC = SearchDC->getEnclosingNamespaceContext(); 12259 } 12260 12261 // In C++, we need to do a redeclaration lookup to properly 12262 // diagnose some problems. 12263 // FIXME: redeclaration lookup is also used (with and without C++) to find a 12264 // hidden declaration so that we don't get ambiguity errors when using a 12265 // type declared by an elaborated-type-specifier. In C that is not correct 12266 // and we should instead merge compatible types found by lookup. 12267 if (getLangOpts().CPlusPlus) { 12268 Previous.setRedeclarationKind(ForRedeclaration); 12269 LookupQualifiedName(Previous, SearchDC); 12270 } else { 12271 Previous.setRedeclarationKind(ForRedeclaration); 12272 LookupName(Previous, S); 12273 } 12274 } 12275 12276 // If we have a known previous declaration to use, then use it. 12277 if (Previous.empty() && SkipBody && SkipBody->Previous) 12278 Previous.addDecl(SkipBody->Previous); 12279 12280 if (!Previous.empty()) { 12281 NamedDecl *PrevDecl = Previous.getFoundDecl(); 12282 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 12283 12284 // It's okay to have a tag decl in the same scope as a typedef 12285 // which hides a tag decl in the same scope. Finding this 12286 // insanity with a redeclaration lookup can only actually happen 12287 // in C++. 12288 // 12289 // This is also okay for elaborated-type-specifiers, which is 12290 // technically forbidden by the current standard but which is 12291 // okay according to the likely resolution of an open issue; 12292 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 12293 if (getLangOpts().CPlusPlus) { 12294 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12295 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 12296 TagDecl *Tag = TT->getDecl(); 12297 if (Tag->getDeclName() == Name && 12298 Tag->getDeclContext()->getRedeclContext() 12299 ->Equals(TD->getDeclContext()->getRedeclContext())) { 12300 PrevDecl = Tag; 12301 Previous.clear(); 12302 Previous.addDecl(Tag); 12303 Previous.resolveKind(); 12304 } 12305 } 12306 } 12307 } 12308 12309 // If this is a redeclaration of a using shadow declaration, it must 12310 // declare a tag in the same context. In MSVC mode, we allow a 12311 // redefinition if either context is within the other. 12312 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 12313 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 12314 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 12315 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 12316 !(OldTag && isAcceptableTagRedeclContext( 12317 *this, OldTag->getDeclContext(), SearchDC))) { 12318 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 12319 Diag(Shadow->getTargetDecl()->getLocation(), 12320 diag::note_using_decl_target); 12321 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 12322 << 0; 12323 // Recover by ignoring the old declaration. 12324 Previous.clear(); 12325 goto CreateNewDecl; 12326 } 12327 } 12328 12329 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 12330 // If this is a use of a previous tag, or if the tag is already declared 12331 // in the same scope (so that the definition/declaration completes or 12332 // rementions the tag), reuse the decl. 12333 if (TUK == TUK_Reference || TUK == TUK_Friend || 12334 isDeclInScope(DirectPrevDecl, SearchDC, S, 12335 SS.isNotEmpty() || isExplicitSpecialization)) { 12336 // Make sure that this wasn't declared as an enum and now used as a 12337 // struct or something similar. 12338 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 12339 TUK == TUK_Definition, KWLoc, 12340 Name)) { 12341 bool SafeToContinue 12342 = (PrevTagDecl->getTagKind() != TTK_Enum && 12343 Kind != TTK_Enum); 12344 if (SafeToContinue) 12345 Diag(KWLoc, diag::err_use_with_wrong_tag) 12346 << Name 12347 << FixItHint::CreateReplacement(SourceRange(KWLoc), 12348 PrevTagDecl->getKindName()); 12349 else 12350 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 12351 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 12352 12353 if (SafeToContinue) 12354 Kind = PrevTagDecl->getTagKind(); 12355 else { 12356 // Recover by making this an anonymous redefinition. 12357 Name = nullptr; 12358 Previous.clear(); 12359 Invalid = true; 12360 } 12361 } 12362 12363 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 12364 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 12365 12366 // If this is an elaborated-type-specifier for a scoped enumeration, 12367 // the 'class' keyword is not necessary and not permitted. 12368 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12369 if (ScopedEnum) 12370 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 12371 << PrevEnum->isScoped() 12372 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 12373 return PrevTagDecl; 12374 } 12375 12376 QualType EnumUnderlyingTy; 12377 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12378 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 12379 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 12380 EnumUnderlyingTy = QualType(T, 0); 12381 12382 // All conflicts with previous declarations are recovered by 12383 // returning the previous declaration, unless this is a definition, 12384 // in which case we want the caller to bail out. 12385 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 12386 ScopedEnum, EnumUnderlyingTy, 12387 EnumUnderlyingIsImplicit, PrevEnum)) 12388 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 12389 } 12390 12391 // C++11 [class.mem]p1: 12392 // A member shall not be declared twice in the member-specification, 12393 // except that a nested class or member class template can be declared 12394 // and then later defined. 12395 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 12396 S->isDeclScope(PrevDecl)) { 12397 Diag(NameLoc, diag::ext_member_redeclared); 12398 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 12399 } 12400 12401 if (!Invalid) { 12402 // If this is a use, just return the declaration we found, unless 12403 // we have attributes. 12404 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12405 if (Attr) { 12406 // FIXME: Diagnose these attributes. For now, we create a new 12407 // declaration to hold them. 12408 } else if (TUK == TUK_Reference && 12409 (PrevTagDecl->getFriendObjectKind() == 12410 Decl::FOK_Undeclared || 12411 PP.getModuleContainingLocation( 12412 PrevDecl->getLocation()) != 12413 PP.getModuleContainingLocation(KWLoc)) && 12414 SS.isEmpty()) { 12415 // This declaration is a reference to an existing entity, but 12416 // has different visibility from that entity: it either makes 12417 // a friend visible or it makes a type visible in a new module. 12418 // In either case, create a new declaration. We only do this if 12419 // the declaration would have meant the same thing if no prior 12420 // declaration were found, that is, if it was found in the same 12421 // scope where we would have injected a declaration. 12422 if (!getTagInjectionContext(CurContext)->getRedeclContext() 12423 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 12424 return PrevTagDecl; 12425 // This is in the injected scope, create a new declaration in 12426 // that scope. 12427 S = getTagInjectionScope(S, getLangOpts()); 12428 } else { 12429 return PrevTagDecl; 12430 } 12431 } 12432 12433 // Diagnose attempts to redefine a tag. 12434 if (TUK == TUK_Definition) { 12435 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 12436 // If we're defining a specialization and the previous definition 12437 // is from an implicit instantiation, don't emit an error 12438 // here; we'll catch this in the general case below. 12439 bool IsExplicitSpecializationAfterInstantiation = false; 12440 if (isExplicitSpecialization) { 12441 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 12442 IsExplicitSpecializationAfterInstantiation = 12443 RD->getTemplateSpecializationKind() != 12444 TSK_ExplicitSpecialization; 12445 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 12446 IsExplicitSpecializationAfterInstantiation = 12447 ED->getTemplateSpecializationKind() != 12448 TSK_ExplicitSpecialization; 12449 } 12450 12451 NamedDecl *Hidden = nullptr; 12452 if (SkipBody && getLangOpts().CPlusPlus && 12453 !hasVisibleDefinition(Def, &Hidden)) { 12454 // There is a definition of this tag, but it is not visible. We 12455 // explicitly make use of C++'s one definition rule here, and 12456 // assume that this definition is identical to the hidden one 12457 // we already have. Make the existing definition visible and 12458 // use it in place of this one. 12459 SkipBody->ShouldSkip = true; 12460 makeMergedDefinitionVisible(Hidden, KWLoc); 12461 return Def; 12462 } else if (!IsExplicitSpecializationAfterInstantiation) { 12463 // A redeclaration in function prototype scope in C isn't 12464 // visible elsewhere, so merely issue a warning. 12465 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 12466 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 12467 else 12468 Diag(NameLoc, diag::err_redefinition) << Name; 12469 Diag(Def->getLocation(), diag::note_previous_definition); 12470 // If this is a redefinition, recover by making this 12471 // struct be anonymous, which will make any later 12472 // references get the previous definition. 12473 Name = nullptr; 12474 Previous.clear(); 12475 Invalid = true; 12476 } 12477 } else { 12478 // If the type is currently being defined, complain 12479 // about a nested redefinition. 12480 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 12481 if (TD->isBeingDefined()) { 12482 Diag(NameLoc, diag::err_nested_redefinition) << Name; 12483 Diag(PrevTagDecl->getLocation(), 12484 diag::note_previous_definition); 12485 Name = nullptr; 12486 Previous.clear(); 12487 Invalid = true; 12488 } 12489 } 12490 12491 // Okay, this is definition of a previously declared or referenced 12492 // tag. We're going to create a new Decl for it. 12493 } 12494 12495 // Okay, we're going to make a redeclaration. If this is some kind 12496 // of reference, make sure we build the redeclaration in the same DC 12497 // as the original, and ignore the current access specifier. 12498 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12499 SearchDC = PrevTagDecl->getDeclContext(); 12500 AS = AS_none; 12501 } 12502 } 12503 // If we get here we have (another) forward declaration or we 12504 // have a definition. Just create a new decl. 12505 12506 } else { 12507 // If we get here, this is a definition of a new tag type in a nested 12508 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 12509 // new decl/type. We set PrevDecl to NULL so that the entities 12510 // have distinct types. 12511 Previous.clear(); 12512 } 12513 // If we get here, we're going to create a new Decl. If PrevDecl 12514 // is non-NULL, it's a definition of the tag declared by 12515 // PrevDecl. If it's NULL, we have a new definition. 12516 12517 // Otherwise, PrevDecl is not a tag, but was found with tag 12518 // lookup. This is only actually possible in C++, where a few 12519 // things like templates still live in the tag namespace. 12520 } else { 12521 // Use a better diagnostic if an elaborated-type-specifier 12522 // found the wrong kind of type on the first 12523 // (non-redeclaration) lookup. 12524 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 12525 !Previous.isForRedeclaration()) { 12526 unsigned Kind = 0; 12527 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 12528 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 12529 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 12530 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 12531 Diag(PrevDecl->getLocation(), diag::note_declared_at); 12532 Invalid = true; 12533 12534 // Otherwise, only diagnose if the declaration is in scope. 12535 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 12536 SS.isNotEmpty() || isExplicitSpecialization)) { 12537 // do nothing 12538 12539 // Diagnose implicit declarations introduced by elaborated types. 12540 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 12541 unsigned Kind = 0; 12542 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 12543 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 12544 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 12545 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 12546 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 12547 Invalid = true; 12548 12549 // Otherwise it's a declaration. Call out a particularly common 12550 // case here. 12551 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12552 unsigned Kind = 0; 12553 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 12554 Diag(NameLoc, diag::err_tag_definition_of_typedef) 12555 << Name << Kind << TND->getUnderlyingType(); 12556 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 12557 Invalid = true; 12558 12559 // Otherwise, diagnose. 12560 } else { 12561 // The tag name clashes with something else in the target scope, 12562 // issue an error and recover by making this tag be anonymous. 12563 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 12564 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12565 Name = nullptr; 12566 Invalid = true; 12567 } 12568 12569 // The existing declaration isn't relevant to us; we're in a 12570 // new scope, so clear out the previous declaration. 12571 Previous.clear(); 12572 } 12573 } 12574 12575 CreateNewDecl: 12576 12577 TagDecl *PrevDecl = nullptr; 12578 if (Previous.isSingleResult()) 12579 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 12580 12581 // If there is an identifier, use the location of the identifier as the 12582 // location of the decl, otherwise use the location of the struct/union 12583 // keyword. 12584 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 12585 12586 // Otherwise, create a new declaration. If there is a previous 12587 // declaration of the same entity, the two will be linked via 12588 // PrevDecl. 12589 TagDecl *New; 12590 12591 bool IsForwardReference = false; 12592 if (Kind == TTK_Enum) { 12593 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 12594 // enum X { A, B, C } D; D should chain to X. 12595 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 12596 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 12597 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 12598 // If this is an undefined enum, warn. 12599 if (TUK != TUK_Definition && !Invalid) { 12600 TagDecl *Def; 12601 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 12602 cast<EnumDecl>(New)->isFixed()) { 12603 // C++0x: 7.2p2: opaque-enum-declaration. 12604 // Conflicts are diagnosed above. Do nothing. 12605 } 12606 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 12607 Diag(Loc, diag::ext_forward_ref_enum_def) 12608 << New; 12609 Diag(Def->getLocation(), diag::note_previous_definition); 12610 } else { 12611 unsigned DiagID = diag::ext_forward_ref_enum; 12612 if (getLangOpts().MSVCCompat) 12613 DiagID = diag::ext_ms_forward_ref_enum; 12614 else if (getLangOpts().CPlusPlus) 12615 DiagID = diag::err_forward_ref_enum; 12616 Diag(Loc, DiagID); 12617 12618 // If this is a forward-declared reference to an enumeration, make a 12619 // note of it; we won't actually be introducing the declaration into 12620 // the declaration context. 12621 if (TUK == TUK_Reference) 12622 IsForwardReference = true; 12623 } 12624 } 12625 12626 if (EnumUnderlying) { 12627 EnumDecl *ED = cast<EnumDecl>(New); 12628 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12629 ED->setIntegerTypeSourceInfo(TI); 12630 else 12631 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 12632 ED->setPromotionType(ED->getIntegerType()); 12633 } 12634 } else { 12635 // struct/union/class 12636 12637 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 12638 // struct X { int A; } D; D should chain to X. 12639 if (getLangOpts().CPlusPlus) { 12640 // FIXME: Look for a way to use RecordDecl for simple structs. 12641 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12642 cast_or_null<CXXRecordDecl>(PrevDecl)); 12643 12644 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 12645 StdBadAlloc = cast<CXXRecordDecl>(New); 12646 } else 12647 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12648 cast_or_null<RecordDecl>(PrevDecl)); 12649 } 12650 12651 // C++11 [dcl.type]p3: 12652 // A type-specifier-seq shall not define a class or enumeration [...]. 12653 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 12654 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 12655 << Context.getTagDeclType(New); 12656 Invalid = true; 12657 } 12658 12659 // Maybe add qualifier info. 12660 if (SS.isNotEmpty()) { 12661 if (SS.isSet()) { 12662 // If this is either a declaration or a definition, check the 12663 // nested-name-specifier against the current context. We don't do this 12664 // for explicit specializations, because they have similar checking 12665 // (with more specific diagnostics) in the call to 12666 // CheckMemberSpecialization, below. 12667 if (!isExplicitSpecialization && 12668 (TUK == TUK_Definition || TUK == TUK_Declaration) && 12669 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 12670 Invalid = true; 12671 12672 New->setQualifierInfo(SS.getWithLocInContext(Context)); 12673 if (TemplateParameterLists.size() > 0) { 12674 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 12675 } 12676 } 12677 else 12678 Invalid = true; 12679 } 12680 12681 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 12682 // Add alignment attributes if necessary; these attributes are checked when 12683 // the ASTContext lays out the structure. 12684 // 12685 // It is important for implementing the correct semantics that this 12686 // happen here (in act on tag decl). The #pragma pack stack is 12687 // maintained as a result of parser callbacks which can occur at 12688 // many points during the parsing of a struct declaration (because 12689 // the #pragma tokens are effectively skipped over during the 12690 // parsing of the struct). 12691 if (TUK == TUK_Definition) { 12692 AddAlignmentAttributesForRecord(RD); 12693 AddMsStructLayoutForRecord(RD); 12694 } 12695 } 12696 12697 if (ModulePrivateLoc.isValid()) { 12698 if (isExplicitSpecialization) 12699 Diag(New->getLocation(), diag::err_module_private_specialization) 12700 << 2 12701 << FixItHint::CreateRemoval(ModulePrivateLoc); 12702 // __module_private__ does not apply to local classes. However, we only 12703 // diagnose this as an error when the declaration specifiers are 12704 // freestanding. Here, we just ignore the __module_private__. 12705 else if (!SearchDC->isFunctionOrMethod()) 12706 New->setModulePrivate(); 12707 } 12708 12709 // If this is a specialization of a member class (of a class template), 12710 // check the specialization. 12711 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 12712 Invalid = true; 12713 12714 // If we're declaring or defining a tag in function prototype scope in C, 12715 // note that this type can only be used within the function and add it to 12716 // the list of decls to inject into the function definition scope. 12717 if ((Name || Kind == TTK_Enum) && 12718 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 12719 if (getLangOpts().CPlusPlus) { 12720 // C++ [dcl.fct]p6: 12721 // Types shall not be defined in return or parameter types. 12722 if (TUK == TUK_Definition && !IsTypeSpecifier) { 12723 Diag(Loc, diag::err_type_defined_in_param_type) 12724 << Name; 12725 Invalid = true; 12726 } 12727 } else if (!PrevDecl) { 12728 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 12729 } 12730 DeclsInPrototypeScope.push_back(New); 12731 } 12732 12733 if (Invalid) 12734 New->setInvalidDecl(); 12735 12736 if (Attr) 12737 ProcessDeclAttributeList(S, New, Attr); 12738 12739 // Set the lexical context. If the tag has a C++ scope specifier, the 12740 // lexical context will be different from the semantic context. 12741 New->setLexicalDeclContext(CurContext); 12742 12743 // Mark this as a friend decl if applicable. 12744 // In Microsoft mode, a friend declaration also acts as a forward 12745 // declaration so we always pass true to setObjectOfFriendDecl to make 12746 // the tag name visible. 12747 if (TUK == TUK_Friend) 12748 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 12749 12750 // Set the access specifier. 12751 if (!Invalid && SearchDC->isRecord()) 12752 SetMemberAccessSpecifier(New, PrevDecl, AS); 12753 12754 if (TUK == TUK_Definition) 12755 New->startDefinition(); 12756 12757 // If this has an identifier, add it to the scope stack. 12758 if (TUK == TUK_Friend) { 12759 // We might be replacing an existing declaration in the lookup tables; 12760 // if so, borrow its access specifier. 12761 if (PrevDecl) 12762 New->setAccess(PrevDecl->getAccess()); 12763 12764 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 12765 DC->makeDeclVisibleInContext(New); 12766 if (Name) // can be null along some error paths 12767 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12768 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 12769 } else if (Name) { 12770 S = getNonFieldDeclScope(S); 12771 PushOnScopeChains(New, S, !IsForwardReference); 12772 if (IsForwardReference) 12773 SearchDC->makeDeclVisibleInContext(New); 12774 } else { 12775 CurContext->addDecl(New); 12776 } 12777 12778 // If this is the C FILE type, notify the AST context. 12779 if (IdentifierInfo *II = New->getIdentifier()) 12780 if (!New->isInvalidDecl() && 12781 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 12782 II->isStr("FILE")) 12783 Context.setFILEDecl(New); 12784 12785 if (PrevDecl) 12786 mergeDeclAttributes(New, PrevDecl); 12787 12788 // If there's a #pragma GCC visibility in scope, set the visibility of this 12789 // record. 12790 AddPushedVisibilityAttribute(New); 12791 12792 OwnedDecl = true; 12793 // In C++, don't return an invalid declaration. We can't recover well from 12794 // the cases where we make the type anonymous. 12795 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 12796 } 12797 12798 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 12799 AdjustDeclIfTemplate(TagD); 12800 TagDecl *Tag = cast<TagDecl>(TagD); 12801 12802 // Enter the tag context. 12803 PushDeclContext(S, Tag); 12804 12805 ActOnDocumentableDecl(TagD); 12806 12807 // If there's a #pragma GCC visibility in scope, set the visibility of this 12808 // record. 12809 AddPushedVisibilityAttribute(Tag); 12810 } 12811 12812 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 12813 assert(isa<ObjCContainerDecl>(IDecl) && 12814 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 12815 DeclContext *OCD = cast<DeclContext>(IDecl); 12816 assert(getContainingDC(OCD) == CurContext && 12817 "The next DeclContext should be lexically contained in the current one."); 12818 CurContext = OCD; 12819 return IDecl; 12820 } 12821 12822 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 12823 SourceLocation FinalLoc, 12824 bool IsFinalSpelledSealed, 12825 SourceLocation LBraceLoc) { 12826 AdjustDeclIfTemplate(TagD); 12827 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 12828 12829 FieldCollector->StartClass(); 12830 12831 if (!Record->getIdentifier()) 12832 return; 12833 12834 if (FinalLoc.isValid()) 12835 Record->addAttr(new (Context) 12836 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 12837 12838 // C++ [class]p2: 12839 // [...] The class-name is also inserted into the scope of the 12840 // class itself; this is known as the injected-class-name. For 12841 // purposes of access checking, the injected-class-name is treated 12842 // as if it were a public member name. 12843 CXXRecordDecl *InjectedClassName 12844 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 12845 Record->getLocStart(), Record->getLocation(), 12846 Record->getIdentifier(), 12847 /*PrevDecl=*/nullptr, 12848 /*DelayTypeCreation=*/true); 12849 Context.getTypeDeclType(InjectedClassName, Record); 12850 InjectedClassName->setImplicit(); 12851 InjectedClassName->setAccess(AS_public); 12852 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 12853 InjectedClassName->setDescribedClassTemplate(Template); 12854 PushOnScopeChains(InjectedClassName, S); 12855 assert(InjectedClassName->isInjectedClassName() && 12856 "Broken injected-class-name"); 12857 } 12858 12859 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 12860 SourceLocation RBraceLoc) { 12861 AdjustDeclIfTemplate(TagD); 12862 TagDecl *Tag = cast<TagDecl>(TagD); 12863 Tag->setRBraceLoc(RBraceLoc); 12864 12865 // Make sure we "complete" the definition even it is invalid. 12866 if (Tag->isBeingDefined()) { 12867 assert(Tag->isInvalidDecl() && "We should already have completed it"); 12868 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12869 RD->completeDefinition(); 12870 } 12871 12872 if (isa<CXXRecordDecl>(Tag)) 12873 FieldCollector->FinishClass(); 12874 12875 // Exit this scope of this tag's definition. 12876 PopDeclContext(); 12877 12878 if (getCurLexicalContext()->isObjCContainer() && 12879 Tag->getDeclContext()->isFileContext()) 12880 Tag->setTopLevelDeclInObjCContainer(); 12881 12882 // Notify the consumer that we've defined a tag. 12883 if (!Tag->isInvalidDecl()) 12884 Consumer.HandleTagDeclDefinition(Tag); 12885 } 12886 12887 void Sema::ActOnObjCContainerFinishDefinition() { 12888 // Exit this scope of this interface definition. 12889 PopDeclContext(); 12890 } 12891 12892 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 12893 assert(DC == CurContext && "Mismatch of container contexts"); 12894 OriginalLexicalContext = DC; 12895 ActOnObjCContainerFinishDefinition(); 12896 } 12897 12898 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 12899 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 12900 OriginalLexicalContext = nullptr; 12901 } 12902 12903 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 12904 AdjustDeclIfTemplate(TagD); 12905 TagDecl *Tag = cast<TagDecl>(TagD); 12906 Tag->setInvalidDecl(); 12907 12908 // Make sure we "complete" the definition even it is invalid. 12909 if (Tag->isBeingDefined()) { 12910 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12911 RD->completeDefinition(); 12912 } 12913 12914 // We're undoing ActOnTagStartDefinition here, not 12915 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 12916 // the FieldCollector. 12917 12918 PopDeclContext(); 12919 } 12920 12921 // Note that FieldName may be null for anonymous bitfields. 12922 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 12923 IdentifierInfo *FieldName, 12924 QualType FieldTy, bool IsMsStruct, 12925 Expr *BitWidth, bool *ZeroWidth) { 12926 // Default to true; that shouldn't confuse checks for emptiness 12927 if (ZeroWidth) 12928 *ZeroWidth = true; 12929 12930 // C99 6.7.2.1p4 - verify the field type. 12931 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 12932 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 12933 // Handle incomplete types with specific error. 12934 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12935 return ExprError(); 12936 if (FieldName) 12937 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12938 << FieldName << FieldTy << BitWidth->getSourceRange(); 12939 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12940 << FieldTy << BitWidth->getSourceRange(); 12941 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12942 UPPC_BitFieldWidth)) 12943 return ExprError(); 12944 12945 // If the bit-width is type- or value-dependent, don't try to check 12946 // it now. 12947 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12948 return BitWidth; 12949 12950 llvm::APSInt Value; 12951 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12952 if (ICE.isInvalid()) 12953 return ICE; 12954 BitWidth = ICE.get(); 12955 12956 if (Value != 0 && ZeroWidth) 12957 *ZeroWidth = false; 12958 12959 // Zero-width bitfield is ok for anonymous field. 12960 if (Value == 0 && FieldName) 12961 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12962 12963 if (Value.isSigned() && Value.isNegative()) { 12964 if (FieldName) 12965 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12966 << FieldName << Value.toString(10); 12967 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12968 << Value.toString(10); 12969 } 12970 12971 if (!FieldTy->isDependentType()) { 12972 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 12973 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 12974 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 12975 12976 // Over-wide bitfields are an error in C or when using the MSVC bitfield 12977 // ABI. 12978 bool CStdConstraintViolation = 12979 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 12980 bool MSBitfieldViolation = 12981 Value.ugt(TypeStorageSize) && 12982 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 12983 if (CStdConstraintViolation || MSBitfieldViolation) { 12984 unsigned DiagWidth = 12985 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 12986 if (FieldName) 12987 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 12988 << FieldName << (unsigned)Value.getZExtValue() 12989 << !CStdConstraintViolation << DiagWidth; 12990 12991 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 12992 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 12993 << DiagWidth; 12994 } 12995 12996 // Warn on types where the user might conceivably expect to get all 12997 // specified bits as value bits: that's all integral types other than 12998 // 'bool'. 12999 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13000 if (FieldName) 13001 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13002 << FieldName << (unsigned)Value.getZExtValue() 13003 << (unsigned)TypeWidth; 13004 else 13005 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13006 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13007 } 13008 } 13009 13010 return BitWidth; 13011 } 13012 13013 /// ActOnField - Each field of a C struct/union is passed into this in order 13014 /// to create a FieldDecl object for it. 13015 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13016 Declarator &D, Expr *BitfieldWidth) { 13017 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13018 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13019 /*InitStyle=*/ICIS_NoInit, AS_public); 13020 return Res; 13021 } 13022 13023 /// HandleField - Analyze a field of a C struct or a C++ data member. 13024 /// 13025 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13026 SourceLocation DeclStart, 13027 Declarator &D, Expr *BitWidth, 13028 InClassInitStyle InitStyle, 13029 AccessSpecifier AS) { 13030 IdentifierInfo *II = D.getIdentifier(); 13031 SourceLocation Loc = DeclStart; 13032 if (II) Loc = D.getIdentifierLoc(); 13033 13034 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13035 QualType T = TInfo->getType(); 13036 if (getLangOpts().CPlusPlus) { 13037 CheckExtraCXXDefaultArguments(D); 13038 13039 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13040 UPPC_DataMemberType)) { 13041 D.setInvalidType(); 13042 T = Context.IntTy; 13043 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13044 } 13045 } 13046 13047 // TR 18037 does not allow fields to be declared with address spaces. 13048 if (T.getQualifiers().hasAddressSpace()) { 13049 Diag(Loc, diag::err_field_with_address_space); 13050 D.setInvalidType(); 13051 } 13052 13053 // OpenCL 1.2 spec, s6.9 r: 13054 // The event type cannot be used to declare a structure or union field. 13055 if (LangOpts.OpenCL && T->isEventT()) { 13056 Diag(Loc, diag::err_event_t_struct_field); 13057 D.setInvalidType(); 13058 } 13059 13060 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13061 13062 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13063 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13064 diag::err_invalid_thread) 13065 << DeclSpec::getSpecifierName(TSCS); 13066 13067 // Check to see if this name was declared as a member previously 13068 NamedDecl *PrevDecl = nullptr; 13069 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13070 LookupName(Previous, S); 13071 switch (Previous.getResultKind()) { 13072 case LookupResult::Found: 13073 case LookupResult::FoundUnresolvedValue: 13074 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13075 break; 13076 13077 case LookupResult::FoundOverloaded: 13078 PrevDecl = Previous.getRepresentativeDecl(); 13079 break; 13080 13081 case LookupResult::NotFound: 13082 case LookupResult::NotFoundInCurrentInstantiation: 13083 case LookupResult::Ambiguous: 13084 break; 13085 } 13086 Previous.suppressDiagnostics(); 13087 13088 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13089 // Maybe we will complain about the shadowed template parameter. 13090 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13091 // Just pretend that we didn't see the previous declaration. 13092 PrevDecl = nullptr; 13093 } 13094 13095 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13096 PrevDecl = nullptr; 13097 13098 bool Mutable 13099 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 13100 SourceLocation TSSL = D.getLocStart(); 13101 FieldDecl *NewFD 13102 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 13103 TSSL, AS, PrevDecl, &D); 13104 13105 if (NewFD->isInvalidDecl()) 13106 Record->setInvalidDecl(); 13107 13108 if (D.getDeclSpec().isModulePrivateSpecified()) 13109 NewFD->setModulePrivate(); 13110 13111 if (NewFD->isInvalidDecl() && PrevDecl) { 13112 // Don't introduce NewFD into scope; there's already something 13113 // with the same name in the same scope. 13114 } else if (II) { 13115 PushOnScopeChains(NewFD, S); 13116 } else 13117 Record->addDecl(NewFD); 13118 13119 return NewFD; 13120 } 13121 13122 /// \brief Build a new FieldDecl and check its well-formedness. 13123 /// 13124 /// This routine builds a new FieldDecl given the fields name, type, 13125 /// record, etc. \p PrevDecl should refer to any previous declaration 13126 /// with the same name and in the same scope as the field to be 13127 /// created. 13128 /// 13129 /// \returns a new FieldDecl. 13130 /// 13131 /// \todo The Declarator argument is a hack. It will be removed once 13132 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 13133 TypeSourceInfo *TInfo, 13134 RecordDecl *Record, SourceLocation Loc, 13135 bool Mutable, Expr *BitWidth, 13136 InClassInitStyle InitStyle, 13137 SourceLocation TSSL, 13138 AccessSpecifier AS, NamedDecl *PrevDecl, 13139 Declarator *D) { 13140 IdentifierInfo *II = Name.getAsIdentifierInfo(); 13141 bool InvalidDecl = false; 13142 if (D) InvalidDecl = D->isInvalidType(); 13143 13144 // If we receive a broken type, recover by assuming 'int' and 13145 // marking this declaration as invalid. 13146 if (T.isNull()) { 13147 InvalidDecl = true; 13148 T = Context.IntTy; 13149 } 13150 13151 QualType EltTy = Context.getBaseElementType(T); 13152 if (!EltTy->isDependentType()) { 13153 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 13154 // Fields of incomplete type force their record to be invalid. 13155 Record->setInvalidDecl(); 13156 InvalidDecl = true; 13157 } else { 13158 NamedDecl *Def; 13159 EltTy->isIncompleteType(&Def); 13160 if (Def && Def->isInvalidDecl()) { 13161 Record->setInvalidDecl(); 13162 InvalidDecl = true; 13163 } 13164 } 13165 } 13166 13167 // OpenCL v1.2 s6.9.c: bitfields are not supported. 13168 if (BitWidth && getLangOpts().OpenCL) { 13169 Diag(Loc, diag::err_opencl_bitfields); 13170 InvalidDecl = true; 13171 } 13172 13173 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13174 // than a variably modified type. 13175 if (!InvalidDecl && T->isVariablyModifiedType()) { 13176 bool SizeIsNegative; 13177 llvm::APSInt Oversized; 13178 13179 TypeSourceInfo *FixedTInfo = 13180 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 13181 SizeIsNegative, 13182 Oversized); 13183 if (FixedTInfo) { 13184 Diag(Loc, diag::warn_illegal_constant_array_size); 13185 TInfo = FixedTInfo; 13186 T = FixedTInfo->getType(); 13187 } else { 13188 if (SizeIsNegative) 13189 Diag(Loc, diag::err_typecheck_negative_array_size); 13190 else if (Oversized.getBoolValue()) 13191 Diag(Loc, diag::err_array_too_large) 13192 << Oversized.toString(10); 13193 else 13194 Diag(Loc, diag::err_typecheck_field_variable_size); 13195 InvalidDecl = true; 13196 } 13197 } 13198 13199 // Fields can not have abstract class types 13200 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 13201 diag::err_abstract_type_in_decl, 13202 AbstractFieldType)) 13203 InvalidDecl = true; 13204 13205 bool ZeroWidth = false; 13206 if (InvalidDecl) 13207 BitWidth = nullptr; 13208 // If this is declared as a bit-field, check the bit-field. 13209 if (BitWidth) { 13210 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 13211 &ZeroWidth).get(); 13212 if (!BitWidth) { 13213 InvalidDecl = true; 13214 BitWidth = nullptr; 13215 ZeroWidth = false; 13216 } 13217 } 13218 13219 // Check that 'mutable' is consistent with the type of the declaration. 13220 if (!InvalidDecl && Mutable) { 13221 unsigned DiagID = 0; 13222 if (T->isReferenceType()) 13223 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 13224 : diag::err_mutable_reference; 13225 else if (T.isConstQualified()) 13226 DiagID = diag::err_mutable_const; 13227 13228 if (DiagID) { 13229 SourceLocation ErrLoc = Loc; 13230 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 13231 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 13232 Diag(ErrLoc, DiagID); 13233 if (DiagID != diag::ext_mutable_reference) { 13234 Mutable = false; 13235 InvalidDecl = true; 13236 } 13237 } 13238 } 13239 13240 // C++11 [class.union]p8 (DR1460): 13241 // At most one variant member of a union may have a 13242 // brace-or-equal-initializer. 13243 if (InitStyle != ICIS_NoInit) 13244 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 13245 13246 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 13247 BitWidth, Mutable, InitStyle); 13248 if (InvalidDecl) 13249 NewFD->setInvalidDecl(); 13250 13251 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 13252 Diag(Loc, diag::err_duplicate_member) << II; 13253 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13254 NewFD->setInvalidDecl(); 13255 } 13256 13257 if (!InvalidDecl && getLangOpts().CPlusPlus) { 13258 if (Record->isUnion()) { 13259 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13260 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13261 if (RDecl->getDefinition()) { 13262 // C++ [class.union]p1: An object of a class with a non-trivial 13263 // constructor, a non-trivial copy constructor, a non-trivial 13264 // destructor, or a non-trivial copy assignment operator 13265 // cannot be a member of a union, nor can an array of such 13266 // objects. 13267 if (CheckNontrivialField(NewFD)) 13268 NewFD->setInvalidDecl(); 13269 } 13270 } 13271 13272 // C++ [class.union]p1: If a union contains a member of reference type, 13273 // the program is ill-formed, except when compiling with MSVC extensions 13274 // enabled. 13275 if (EltTy->isReferenceType()) { 13276 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 13277 diag::ext_union_member_of_reference_type : 13278 diag::err_union_member_of_reference_type) 13279 << NewFD->getDeclName() << EltTy; 13280 if (!getLangOpts().MicrosoftExt) 13281 NewFD->setInvalidDecl(); 13282 } 13283 } 13284 } 13285 13286 // FIXME: We need to pass in the attributes given an AST 13287 // representation, not a parser representation. 13288 if (D) { 13289 // FIXME: The current scope is almost... but not entirely... correct here. 13290 ProcessDeclAttributes(getCurScope(), NewFD, *D); 13291 13292 if (NewFD->hasAttrs()) 13293 CheckAlignasUnderalignment(NewFD); 13294 } 13295 13296 // In auto-retain/release, infer strong retension for fields of 13297 // retainable type. 13298 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 13299 NewFD->setInvalidDecl(); 13300 13301 if (T.isObjCGCWeak()) 13302 Diag(Loc, diag::warn_attribute_weak_on_field); 13303 13304 NewFD->setAccess(AS); 13305 return NewFD; 13306 } 13307 13308 bool Sema::CheckNontrivialField(FieldDecl *FD) { 13309 assert(FD); 13310 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 13311 13312 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 13313 return false; 13314 13315 QualType EltTy = Context.getBaseElementType(FD->getType()); 13316 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13317 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13318 if (RDecl->getDefinition()) { 13319 // We check for copy constructors before constructors 13320 // because otherwise we'll never get complaints about 13321 // copy constructors. 13322 13323 CXXSpecialMember member = CXXInvalid; 13324 // We're required to check for any non-trivial constructors. Since the 13325 // implicit default constructor is suppressed if there are any 13326 // user-declared constructors, we just need to check that there is a 13327 // trivial default constructor and a trivial copy constructor. (We don't 13328 // worry about move constructors here, since this is a C++98 check.) 13329 if (RDecl->hasNonTrivialCopyConstructor()) 13330 member = CXXCopyConstructor; 13331 else if (!RDecl->hasTrivialDefaultConstructor()) 13332 member = CXXDefaultConstructor; 13333 else if (RDecl->hasNonTrivialCopyAssignment()) 13334 member = CXXCopyAssignment; 13335 else if (RDecl->hasNonTrivialDestructor()) 13336 member = CXXDestructor; 13337 13338 if (member != CXXInvalid) { 13339 if (!getLangOpts().CPlusPlus11 && 13340 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 13341 // Objective-C++ ARC: it is an error to have a non-trivial field of 13342 // a union. However, system headers in Objective-C programs 13343 // occasionally have Objective-C lifetime objects within unions, 13344 // and rather than cause the program to fail, we make those 13345 // members unavailable. 13346 SourceLocation Loc = FD->getLocation(); 13347 if (getSourceManager().isInSystemHeader(Loc)) { 13348 if (!FD->hasAttr<UnavailableAttr>()) 13349 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13350 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 13351 return false; 13352 } 13353 } 13354 13355 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 13356 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 13357 diag::err_illegal_union_or_anon_struct_member) 13358 << FD->getParent()->isUnion() << FD->getDeclName() << member; 13359 DiagnoseNontrivial(RDecl, member); 13360 return !getLangOpts().CPlusPlus11; 13361 } 13362 } 13363 } 13364 13365 return false; 13366 } 13367 13368 /// TranslateIvarVisibility - Translate visibility from a token ID to an 13369 /// AST enum value. 13370 static ObjCIvarDecl::AccessControl 13371 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 13372 switch (ivarVisibility) { 13373 default: llvm_unreachable("Unknown visitibility kind"); 13374 case tok::objc_private: return ObjCIvarDecl::Private; 13375 case tok::objc_public: return ObjCIvarDecl::Public; 13376 case tok::objc_protected: return ObjCIvarDecl::Protected; 13377 case tok::objc_package: return ObjCIvarDecl::Package; 13378 } 13379 } 13380 13381 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 13382 /// in order to create an IvarDecl object for it. 13383 Decl *Sema::ActOnIvar(Scope *S, 13384 SourceLocation DeclStart, 13385 Declarator &D, Expr *BitfieldWidth, 13386 tok::ObjCKeywordKind Visibility) { 13387 13388 IdentifierInfo *II = D.getIdentifier(); 13389 Expr *BitWidth = (Expr*)BitfieldWidth; 13390 SourceLocation Loc = DeclStart; 13391 if (II) Loc = D.getIdentifierLoc(); 13392 13393 // FIXME: Unnamed fields can be handled in various different ways, for 13394 // example, unnamed unions inject all members into the struct namespace! 13395 13396 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13397 QualType T = TInfo->getType(); 13398 13399 if (BitWidth) { 13400 // 6.7.2.1p3, 6.7.2.1p4 13401 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 13402 if (!BitWidth) 13403 D.setInvalidType(); 13404 } else { 13405 // Not a bitfield. 13406 13407 // validate II. 13408 13409 } 13410 if (T->isReferenceType()) { 13411 Diag(Loc, diag::err_ivar_reference_type); 13412 D.setInvalidType(); 13413 } 13414 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13415 // than a variably modified type. 13416 else if (T->isVariablyModifiedType()) { 13417 Diag(Loc, diag::err_typecheck_ivar_variable_size); 13418 D.setInvalidType(); 13419 } 13420 13421 // Get the visibility (access control) for this ivar. 13422 ObjCIvarDecl::AccessControl ac = 13423 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 13424 : ObjCIvarDecl::None; 13425 // Must set ivar's DeclContext to its enclosing interface. 13426 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 13427 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 13428 return nullptr; 13429 ObjCContainerDecl *EnclosingContext; 13430 if (ObjCImplementationDecl *IMPDecl = 13431 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13432 if (LangOpts.ObjCRuntime.isFragile()) { 13433 // Case of ivar declared in an implementation. Context is that of its class. 13434 EnclosingContext = IMPDecl->getClassInterface(); 13435 assert(EnclosingContext && "Implementation has no class interface!"); 13436 } 13437 else 13438 EnclosingContext = EnclosingDecl; 13439 } else { 13440 if (ObjCCategoryDecl *CDecl = 13441 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13442 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 13443 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 13444 return nullptr; 13445 } 13446 } 13447 EnclosingContext = EnclosingDecl; 13448 } 13449 13450 // Construct the decl. 13451 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 13452 DeclStart, Loc, II, T, 13453 TInfo, ac, (Expr *)BitfieldWidth); 13454 13455 if (II) { 13456 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 13457 ForRedeclaration); 13458 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 13459 && !isa<TagDecl>(PrevDecl)) { 13460 Diag(Loc, diag::err_duplicate_member) << II; 13461 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13462 NewID->setInvalidDecl(); 13463 } 13464 } 13465 13466 // Process attributes attached to the ivar. 13467 ProcessDeclAttributes(S, NewID, D); 13468 13469 if (D.isInvalidType()) 13470 NewID->setInvalidDecl(); 13471 13472 // In ARC, infer 'retaining' for ivars of retainable type. 13473 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 13474 NewID->setInvalidDecl(); 13475 13476 if (D.getDeclSpec().isModulePrivateSpecified()) 13477 NewID->setModulePrivate(); 13478 13479 if (II) { 13480 // FIXME: When interfaces are DeclContexts, we'll need to add 13481 // these to the interface. 13482 S->AddDecl(NewID); 13483 IdResolver.AddDecl(NewID); 13484 } 13485 13486 if (LangOpts.ObjCRuntime.isNonFragile() && 13487 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 13488 Diag(Loc, diag::warn_ivars_in_interface); 13489 13490 return NewID; 13491 } 13492 13493 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 13494 /// class and class extensions. For every class \@interface and class 13495 /// extension \@interface, if the last ivar is a bitfield of any type, 13496 /// then add an implicit `char :0` ivar to the end of that interface. 13497 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 13498 SmallVectorImpl<Decl *> &AllIvarDecls) { 13499 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 13500 return; 13501 13502 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 13503 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 13504 13505 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 13506 return; 13507 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 13508 if (!ID) { 13509 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 13510 if (!CD->IsClassExtension()) 13511 return; 13512 } 13513 // No need to add this to end of @implementation. 13514 else 13515 return; 13516 } 13517 // All conditions are met. Add a new bitfield to the tail end of ivars. 13518 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 13519 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 13520 13521 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 13522 DeclLoc, DeclLoc, nullptr, 13523 Context.CharTy, 13524 Context.getTrivialTypeSourceInfo(Context.CharTy, 13525 DeclLoc), 13526 ObjCIvarDecl::Private, BW, 13527 true); 13528 AllIvarDecls.push_back(Ivar); 13529 } 13530 13531 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 13532 ArrayRef<Decl *> Fields, SourceLocation LBrac, 13533 SourceLocation RBrac, AttributeList *Attr) { 13534 assert(EnclosingDecl && "missing record or interface decl"); 13535 13536 // If this is an Objective-C @implementation or category and we have 13537 // new fields here we should reset the layout of the interface since 13538 // it will now change. 13539 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 13540 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 13541 switch (DC->getKind()) { 13542 default: break; 13543 case Decl::ObjCCategory: 13544 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 13545 break; 13546 case Decl::ObjCImplementation: 13547 Context. 13548 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 13549 break; 13550 } 13551 } 13552 13553 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 13554 13555 // Start counting up the number of named members; make sure to include 13556 // members of anonymous structs and unions in the total. 13557 unsigned NumNamedMembers = 0; 13558 if (Record) { 13559 for (const auto *I : Record->decls()) { 13560 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 13561 if (IFD->getDeclName()) 13562 ++NumNamedMembers; 13563 } 13564 } 13565 13566 // Verify that all the fields are okay. 13567 SmallVector<FieldDecl*, 32> RecFields; 13568 13569 bool ARCErrReported = false; 13570 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 13571 i != end; ++i) { 13572 FieldDecl *FD = cast<FieldDecl>(*i); 13573 13574 // Get the type for the field. 13575 const Type *FDTy = FD->getType().getTypePtr(); 13576 13577 if (!FD->isAnonymousStructOrUnion()) { 13578 // Remember all fields written by the user. 13579 RecFields.push_back(FD); 13580 } 13581 13582 // If the field is already invalid for some reason, don't emit more 13583 // diagnostics about it. 13584 if (FD->isInvalidDecl()) { 13585 EnclosingDecl->setInvalidDecl(); 13586 continue; 13587 } 13588 13589 // C99 6.7.2.1p2: 13590 // A structure or union shall not contain a member with 13591 // incomplete or function type (hence, a structure shall not 13592 // contain an instance of itself, but may contain a pointer to 13593 // an instance of itself), except that the last member of a 13594 // structure with more than one named member may have incomplete 13595 // array type; such a structure (and any union containing, 13596 // possibly recursively, a member that is such a structure) 13597 // shall not be a member of a structure or an element of an 13598 // array. 13599 if (FDTy->isFunctionType()) { 13600 // Field declared as a function. 13601 Diag(FD->getLocation(), diag::err_field_declared_as_function) 13602 << FD->getDeclName(); 13603 FD->setInvalidDecl(); 13604 EnclosingDecl->setInvalidDecl(); 13605 continue; 13606 } else if (FDTy->isIncompleteArrayType() && Record && 13607 ((i + 1 == Fields.end() && !Record->isUnion()) || 13608 ((getLangOpts().MicrosoftExt || 13609 getLangOpts().CPlusPlus) && 13610 (i + 1 == Fields.end() || Record->isUnion())))) { 13611 // Flexible array member. 13612 // Microsoft and g++ is more permissive regarding flexible array. 13613 // It will accept flexible array in union and also 13614 // as the sole element of a struct/class. 13615 unsigned DiagID = 0; 13616 if (Record->isUnion()) 13617 DiagID = getLangOpts().MicrosoftExt 13618 ? diag::ext_flexible_array_union_ms 13619 : getLangOpts().CPlusPlus 13620 ? diag::ext_flexible_array_union_gnu 13621 : diag::err_flexible_array_union; 13622 else if (Fields.size() == 1) 13623 DiagID = getLangOpts().MicrosoftExt 13624 ? diag::ext_flexible_array_empty_aggregate_ms 13625 : getLangOpts().CPlusPlus 13626 ? diag::ext_flexible_array_empty_aggregate_gnu 13627 : NumNamedMembers < 1 13628 ? diag::err_flexible_array_empty_aggregate 13629 : 0; 13630 13631 if (DiagID) 13632 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 13633 << Record->getTagKind(); 13634 // While the layout of types that contain virtual bases is not specified 13635 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 13636 // virtual bases after the derived members. This would make a flexible 13637 // array member declared at the end of an object not adjacent to the end 13638 // of the type. 13639 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 13640 if (RD->getNumVBases() != 0) 13641 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 13642 << FD->getDeclName() << Record->getTagKind(); 13643 if (!getLangOpts().C99) 13644 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 13645 << FD->getDeclName() << Record->getTagKind(); 13646 13647 // If the element type has a non-trivial destructor, we would not 13648 // implicitly destroy the elements, so disallow it for now. 13649 // 13650 // FIXME: GCC allows this. We should probably either implicitly delete 13651 // the destructor of the containing class, or just allow this. 13652 QualType BaseElem = Context.getBaseElementType(FD->getType()); 13653 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 13654 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 13655 << FD->getDeclName() << FD->getType(); 13656 FD->setInvalidDecl(); 13657 EnclosingDecl->setInvalidDecl(); 13658 continue; 13659 } 13660 // Okay, we have a legal flexible array member at the end of the struct. 13661 Record->setHasFlexibleArrayMember(true); 13662 } else if (!FDTy->isDependentType() && 13663 RequireCompleteType(FD->getLocation(), FD->getType(), 13664 diag::err_field_incomplete)) { 13665 // Incomplete type 13666 FD->setInvalidDecl(); 13667 EnclosingDecl->setInvalidDecl(); 13668 continue; 13669 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 13670 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 13671 // A type which contains a flexible array member is considered to be a 13672 // flexible array member. 13673 Record->setHasFlexibleArrayMember(true); 13674 if (!Record->isUnion()) { 13675 // If this is a struct/class and this is not the last element, reject 13676 // it. Note that GCC supports variable sized arrays in the middle of 13677 // structures. 13678 if (i + 1 != Fields.end()) 13679 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 13680 << FD->getDeclName() << FD->getType(); 13681 else { 13682 // We support flexible arrays at the end of structs in 13683 // other structs as an extension. 13684 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 13685 << FD->getDeclName(); 13686 } 13687 } 13688 } 13689 if (isa<ObjCContainerDecl>(EnclosingDecl) && 13690 RequireNonAbstractType(FD->getLocation(), FD->getType(), 13691 diag::err_abstract_type_in_decl, 13692 AbstractIvarType)) { 13693 // Ivars can not have abstract class types 13694 FD->setInvalidDecl(); 13695 } 13696 if (Record && FDTTy->getDecl()->hasObjectMember()) 13697 Record->setHasObjectMember(true); 13698 if (Record && FDTTy->getDecl()->hasVolatileMember()) 13699 Record->setHasVolatileMember(true); 13700 } else if (FDTy->isObjCObjectType()) { 13701 /// A field cannot be an Objective-c object 13702 Diag(FD->getLocation(), diag::err_statically_allocated_object) 13703 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 13704 QualType T = Context.getObjCObjectPointerType(FD->getType()); 13705 FD->setType(T); 13706 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 13707 (!getLangOpts().CPlusPlus || Record->isUnion())) { 13708 // It's an error in ARC if a field has lifetime. 13709 // We don't want to report this in a system header, though, 13710 // so we just make the field unavailable. 13711 // FIXME: that's really not sufficient; we need to make the type 13712 // itself invalid to, say, initialize or copy. 13713 QualType T = FD->getType(); 13714 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 13715 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 13716 SourceLocation loc = FD->getLocation(); 13717 if (getSourceManager().isInSystemHeader(loc)) { 13718 if (!FD->hasAttr<UnavailableAttr>()) { 13719 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13720 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 13721 } 13722 } else { 13723 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 13724 << T->isBlockPointerType() << Record->getTagKind(); 13725 } 13726 ARCErrReported = true; 13727 } 13728 } else if (getLangOpts().ObjC1 && 13729 getLangOpts().getGC() != LangOptions::NonGC && 13730 Record && !Record->hasObjectMember()) { 13731 if (FD->getType()->isObjCObjectPointerType() || 13732 FD->getType().isObjCGCStrong()) 13733 Record->setHasObjectMember(true); 13734 else if (Context.getAsArrayType(FD->getType())) { 13735 QualType BaseType = Context.getBaseElementType(FD->getType()); 13736 if (BaseType->isRecordType() && 13737 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 13738 Record->setHasObjectMember(true); 13739 else if (BaseType->isObjCObjectPointerType() || 13740 BaseType.isObjCGCStrong()) 13741 Record->setHasObjectMember(true); 13742 } 13743 } 13744 if (Record && FD->getType().isVolatileQualified()) 13745 Record->setHasVolatileMember(true); 13746 // Keep track of the number of named members. 13747 if (FD->getIdentifier()) 13748 ++NumNamedMembers; 13749 } 13750 13751 // Okay, we successfully defined 'Record'. 13752 if (Record) { 13753 bool Completed = false; 13754 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 13755 if (!CXXRecord->isInvalidDecl()) { 13756 // Set access bits correctly on the directly-declared conversions. 13757 for (CXXRecordDecl::conversion_iterator 13758 I = CXXRecord->conversion_begin(), 13759 E = CXXRecord->conversion_end(); I != E; ++I) 13760 I.setAccess((*I)->getAccess()); 13761 13762 if (!CXXRecord->isDependentType()) { 13763 if (CXXRecord->hasUserDeclaredDestructor()) { 13764 // Adjust user-defined destructor exception spec. 13765 if (getLangOpts().CPlusPlus11) 13766 AdjustDestructorExceptionSpec(CXXRecord, 13767 CXXRecord->getDestructor()); 13768 } 13769 13770 // Add any implicitly-declared members to this class. 13771 AddImplicitlyDeclaredMembersToClass(CXXRecord); 13772 13773 // If we have virtual base classes, we may end up finding multiple 13774 // final overriders for a given virtual function. Check for this 13775 // problem now. 13776 if (CXXRecord->getNumVBases()) { 13777 CXXFinalOverriderMap FinalOverriders; 13778 CXXRecord->getFinalOverriders(FinalOverriders); 13779 13780 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 13781 MEnd = FinalOverriders.end(); 13782 M != MEnd; ++M) { 13783 for (OverridingMethods::iterator SO = M->second.begin(), 13784 SOEnd = M->second.end(); 13785 SO != SOEnd; ++SO) { 13786 assert(SO->second.size() > 0 && 13787 "Virtual function without overridding functions?"); 13788 if (SO->second.size() == 1) 13789 continue; 13790 13791 // C++ [class.virtual]p2: 13792 // In a derived class, if a virtual member function of a base 13793 // class subobject has more than one final overrider the 13794 // program is ill-formed. 13795 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 13796 << (const NamedDecl *)M->first << Record; 13797 Diag(M->first->getLocation(), 13798 diag::note_overridden_virtual_function); 13799 for (OverridingMethods::overriding_iterator 13800 OM = SO->second.begin(), 13801 OMEnd = SO->second.end(); 13802 OM != OMEnd; ++OM) 13803 Diag(OM->Method->getLocation(), diag::note_final_overrider) 13804 << (const NamedDecl *)M->first << OM->Method->getParent(); 13805 13806 Record->setInvalidDecl(); 13807 } 13808 } 13809 CXXRecord->completeDefinition(&FinalOverriders); 13810 Completed = true; 13811 } 13812 } 13813 } 13814 } 13815 13816 if (!Completed) 13817 Record->completeDefinition(); 13818 13819 if (Record->hasAttrs()) { 13820 CheckAlignasUnderalignment(Record); 13821 13822 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 13823 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 13824 IA->getRange(), IA->getBestCase(), 13825 IA->getSemanticSpelling()); 13826 } 13827 13828 // Check if the structure/union declaration is a type that can have zero 13829 // size in C. For C this is a language extension, for C++ it may cause 13830 // compatibility problems. 13831 bool CheckForZeroSize; 13832 if (!getLangOpts().CPlusPlus) { 13833 CheckForZeroSize = true; 13834 } else { 13835 // For C++ filter out types that cannot be referenced in C code. 13836 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 13837 CheckForZeroSize = 13838 CXXRecord->getLexicalDeclContext()->isExternCContext() && 13839 !CXXRecord->isDependentType() && 13840 CXXRecord->isCLike(); 13841 } 13842 if (CheckForZeroSize) { 13843 bool ZeroSize = true; 13844 bool IsEmpty = true; 13845 unsigned NonBitFields = 0; 13846 for (RecordDecl::field_iterator I = Record->field_begin(), 13847 E = Record->field_end(); 13848 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 13849 IsEmpty = false; 13850 if (I->isUnnamedBitfield()) { 13851 if (I->getBitWidthValue(Context) > 0) 13852 ZeroSize = false; 13853 } else { 13854 ++NonBitFields; 13855 QualType FieldType = I->getType(); 13856 if (FieldType->isIncompleteType() || 13857 !Context.getTypeSizeInChars(FieldType).isZero()) 13858 ZeroSize = false; 13859 } 13860 } 13861 13862 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 13863 // allowed in C++, but warn if its declaration is inside 13864 // extern "C" block. 13865 if (ZeroSize) { 13866 Diag(RecLoc, getLangOpts().CPlusPlus ? 13867 diag::warn_zero_size_struct_union_in_extern_c : 13868 diag::warn_zero_size_struct_union_compat) 13869 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 13870 } 13871 13872 // Structs without named members are extension in C (C99 6.7.2.1p7), 13873 // but are accepted by GCC. 13874 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 13875 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 13876 diag::ext_no_named_members_in_struct_union) 13877 << Record->isUnion(); 13878 } 13879 } 13880 } else { 13881 ObjCIvarDecl **ClsFields = 13882 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 13883 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 13884 ID->setEndOfDefinitionLoc(RBrac); 13885 // Add ivar's to class's DeclContext. 13886 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13887 ClsFields[i]->setLexicalDeclContext(ID); 13888 ID->addDecl(ClsFields[i]); 13889 } 13890 // Must enforce the rule that ivars in the base classes may not be 13891 // duplicates. 13892 if (ID->getSuperClass()) 13893 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 13894 } else if (ObjCImplementationDecl *IMPDecl = 13895 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13896 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 13897 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 13898 // Ivar declared in @implementation never belongs to the implementation. 13899 // Only it is in implementation's lexical context. 13900 ClsFields[I]->setLexicalDeclContext(IMPDecl); 13901 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 13902 IMPDecl->setIvarLBraceLoc(LBrac); 13903 IMPDecl->setIvarRBraceLoc(RBrac); 13904 } else if (ObjCCategoryDecl *CDecl = 13905 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13906 // case of ivars in class extension; all other cases have been 13907 // reported as errors elsewhere. 13908 // FIXME. Class extension does not have a LocEnd field. 13909 // CDecl->setLocEnd(RBrac); 13910 // Add ivar's to class extension's DeclContext. 13911 // Diagnose redeclaration of private ivars. 13912 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 13913 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13914 if (IDecl) { 13915 if (const ObjCIvarDecl *ClsIvar = 13916 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 13917 Diag(ClsFields[i]->getLocation(), 13918 diag::err_duplicate_ivar_declaration); 13919 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 13920 continue; 13921 } 13922 for (const auto *Ext : IDecl->known_extensions()) { 13923 if (const ObjCIvarDecl *ClsExtIvar 13924 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 13925 Diag(ClsFields[i]->getLocation(), 13926 diag::err_duplicate_ivar_declaration); 13927 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 13928 continue; 13929 } 13930 } 13931 } 13932 ClsFields[i]->setLexicalDeclContext(CDecl); 13933 CDecl->addDecl(ClsFields[i]); 13934 } 13935 CDecl->setIvarLBraceLoc(LBrac); 13936 CDecl->setIvarRBraceLoc(RBrac); 13937 } 13938 } 13939 13940 if (Attr) 13941 ProcessDeclAttributeList(S, Record, Attr); 13942 } 13943 13944 /// \brief Determine whether the given integral value is representable within 13945 /// the given type T. 13946 static bool isRepresentableIntegerValue(ASTContext &Context, 13947 llvm::APSInt &Value, 13948 QualType T) { 13949 assert(T->isIntegralType(Context) && "Integral type required!"); 13950 unsigned BitWidth = Context.getIntWidth(T); 13951 13952 if (Value.isUnsigned() || Value.isNonNegative()) { 13953 if (T->isSignedIntegerOrEnumerationType()) 13954 --BitWidth; 13955 return Value.getActiveBits() <= BitWidth; 13956 } 13957 return Value.getMinSignedBits() <= BitWidth; 13958 } 13959 13960 // \brief Given an integral type, return the next larger integral type 13961 // (or a NULL type of no such type exists). 13962 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13963 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13964 // enum checking below. 13965 assert(T->isIntegralType(Context) && "Integral type required!"); 13966 const unsigned NumTypes = 4; 13967 QualType SignedIntegralTypes[NumTypes] = { 13968 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13969 }; 13970 QualType UnsignedIntegralTypes[NumTypes] = { 13971 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13972 Context.UnsignedLongLongTy 13973 }; 13974 13975 unsigned BitWidth = Context.getTypeSize(T); 13976 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13977 : UnsignedIntegralTypes; 13978 for (unsigned I = 0; I != NumTypes; ++I) 13979 if (Context.getTypeSize(Types[I]) > BitWidth) 13980 return Types[I]; 13981 13982 return QualType(); 13983 } 13984 13985 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13986 EnumConstantDecl *LastEnumConst, 13987 SourceLocation IdLoc, 13988 IdentifierInfo *Id, 13989 Expr *Val) { 13990 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13991 llvm::APSInt EnumVal(IntWidth); 13992 QualType EltTy; 13993 13994 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13995 Val = nullptr; 13996 13997 if (Val) 13998 Val = DefaultLvalueConversion(Val).get(); 13999 14000 if (Val) { 14001 if (Enum->isDependentType() || Val->isTypeDependent()) 14002 EltTy = Context.DependentTy; 14003 else { 14004 SourceLocation ExpLoc; 14005 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14006 !getLangOpts().MSVCCompat) { 14007 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14008 // constant-expression in the enumerator-definition shall be a converted 14009 // constant expression of the underlying type. 14010 EltTy = Enum->getIntegerType(); 14011 ExprResult Converted = 14012 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14013 CCEK_Enumerator); 14014 if (Converted.isInvalid()) 14015 Val = nullptr; 14016 else 14017 Val = Converted.get(); 14018 } else if (!Val->isValueDependent() && 14019 !(Val = VerifyIntegerConstantExpression(Val, 14020 &EnumVal).get())) { 14021 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14022 } else { 14023 if (Enum->isFixed()) { 14024 EltTy = Enum->getIntegerType(); 14025 14026 // In Obj-C and Microsoft mode, require the enumeration value to be 14027 // representable in the underlying type of the enumeration. In C++11, 14028 // we perform a non-narrowing conversion as part of converted constant 14029 // expression checking. 14030 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14031 if (getLangOpts().MSVCCompat) { 14032 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14033 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14034 } else 14035 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14036 } else 14037 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14038 } else if (getLangOpts().CPlusPlus) { 14039 // C++11 [dcl.enum]p5: 14040 // If the underlying type is not fixed, the type of each enumerator 14041 // is the type of its initializing value: 14042 // - If an initializer is specified for an enumerator, the 14043 // initializing value has the same type as the expression. 14044 EltTy = Val->getType(); 14045 } else { 14046 // C99 6.7.2.2p2: 14047 // The expression that defines the value of an enumeration constant 14048 // shall be an integer constant expression that has a value 14049 // representable as an int. 14050 14051 // Complain if the value is not representable in an int. 14052 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14053 Diag(IdLoc, diag::ext_enum_value_not_int) 14054 << EnumVal.toString(10) << Val->getSourceRange() 14055 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14056 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14057 // Force the type of the expression to 'int'. 14058 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14059 } 14060 EltTy = Val->getType(); 14061 } 14062 } 14063 } 14064 } 14065 14066 if (!Val) { 14067 if (Enum->isDependentType()) 14068 EltTy = Context.DependentTy; 14069 else if (!LastEnumConst) { 14070 // C++0x [dcl.enum]p5: 14071 // If the underlying type is not fixed, the type of each enumerator 14072 // is the type of its initializing value: 14073 // - If no initializer is specified for the first enumerator, the 14074 // initializing value has an unspecified integral type. 14075 // 14076 // GCC uses 'int' for its unspecified integral type, as does 14077 // C99 6.7.2.2p3. 14078 if (Enum->isFixed()) { 14079 EltTy = Enum->getIntegerType(); 14080 } 14081 else { 14082 EltTy = Context.IntTy; 14083 } 14084 } else { 14085 // Assign the last value + 1. 14086 EnumVal = LastEnumConst->getInitVal(); 14087 ++EnumVal; 14088 EltTy = LastEnumConst->getType(); 14089 14090 // Check for overflow on increment. 14091 if (EnumVal < LastEnumConst->getInitVal()) { 14092 // C++0x [dcl.enum]p5: 14093 // If the underlying type is not fixed, the type of each enumerator 14094 // is the type of its initializing value: 14095 // 14096 // - Otherwise the type of the initializing value is the same as 14097 // the type of the initializing value of the preceding enumerator 14098 // unless the incremented value is not representable in that type, 14099 // in which case the type is an unspecified integral type 14100 // sufficient to contain the incremented value. If no such type 14101 // exists, the program is ill-formed. 14102 QualType T = getNextLargerIntegralType(Context, EltTy); 14103 if (T.isNull() || Enum->isFixed()) { 14104 // There is no integral type larger enough to represent this 14105 // value. Complain, then allow the value to wrap around. 14106 EnumVal = LastEnumConst->getInitVal(); 14107 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 14108 ++EnumVal; 14109 if (Enum->isFixed()) 14110 // When the underlying type is fixed, this is ill-formed. 14111 Diag(IdLoc, diag::err_enumerator_wrapped) 14112 << EnumVal.toString(10) 14113 << EltTy; 14114 else 14115 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 14116 << EnumVal.toString(10); 14117 } else { 14118 EltTy = T; 14119 } 14120 14121 // Retrieve the last enumerator's value, extent that type to the 14122 // type that is supposed to be large enough to represent the incremented 14123 // value, then increment. 14124 EnumVal = LastEnumConst->getInitVal(); 14125 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14126 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 14127 ++EnumVal; 14128 14129 // If we're not in C++, diagnose the overflow of enumerator values, 14130 // which in C99 means that the enumerator value is not representable in 14131 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 14132 // permits enumerator values that are representable in some larger 14133 // integral type. 14134 if (!getLangOpts().CPlusPlus && !T.isNull()) 14135 Diag(IdLoc, diag::warn_enum_value_overflow); 14136 } else if (!getLangOpts().CPlusPlus && 14137 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14138 // Enforce C99 6.7.2.2p2 even when we compute the next value. 14139 Diag(IdLoc, diag::ext_enum_value_not_int) 14140 << EnumVal.toString(10) << 1; 14141 } 14142 } 14143 } 14144 14145 if (!EltTy->isDependentType()) { 14146 // Make the enumerator value match the signedness and size of the 14147 // enumerator's type. 14148 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 14149 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14150 } 14151 14152 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 14153 Val, EnumVal); 14154 } 14155 14156 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 14157 SourceLocation IILoc) { 14158 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 14159 !getLangOpts().CPlusPlus) 14160 return SkipBodyInfo(); 14161 14162 // We have an anonymous enum definition. Look up the first enumerator to 14163 // determine if we should merge the definition with an existing one and 14164 // skip the body. 14165 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 14166 ForRedeclaration); 14167 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 14168 if (!PrevECD) 14169 return SkipBodyInfo(); 14170 14171 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 14172 NamedDecl *Hidden; 14173 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 14174 SkipBodyInfo Skip; 14175 Skip.Previous = Hidden; 14176 return Skip; 14177 } 14178 14179 return SkipBodyInfo(); 14180 } 14181 14182 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 14183 SourceLocation IdLoc, IdentifierInfo *Id, 14184 AttributeList *Attr, 14185 SourceLocation EqualLoc, Expr *Val) { 14186 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 14187 EnumConstantDecl *LastEnumConst = 14188 cast_or_null<EnumConstantDecl>(lastEnumConst); 14189 14190 // The scope passed in may not be a decl scope. Zip up the scope tree until 14191 // we find one that is. 14192 S = getNonFieldDeclScope(S); 14193 14194 // Verify that there isn't already something declared with this name in this 14195 // scope. 14196 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 14197 ForRedeclaration); 14198 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14199 // Maybe we will complain about the shadowed template parameter. 14200 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 14201 // Just pretend that we didn't see the previous declaration. 14202 PrevDecl = nullptr; 14203 } 14204 14205 // C++ [class.mem]p15: 14206 // If T is the name of a class, then each of the following shall have a name 14207 // different from T: 14208 // - every enumerator of every member of class T that is an unscoped 14209 // enumerated type 14210 if (!TheEnumDecl->isScoped()) 14211 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 14212 DeclarationNameInfo(Id, IdLoc)); 14213 14214 EnumConstantDecl *New = 14215 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 14216 if (!New) 14217 return nullptr; 14218 14219 if (PrevDecl) { 14220 // When in C++, we may get a TagDecl with the same name; in this case the 14221 // enum constant will 'hide' the tag. 14222 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 14223 "Received TagDecl when not in C++!"); 14224 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 14225 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 14226 if (isa<EnumConstantDecl>(PrevDecl)) 14227 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 14228 else 14229 Diag(IdLoc, diag::err_redefinition) << Id; 14230 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14231 return nullptr; 14232 } 14233 } 14234 14235 // Process attributes. 14236 if (Attr) ProcessDeclAttributeList(S, New, Attr); 14237 14238 // Register this decl in the current scope stack. 14239 New->setAccess(TheEnumDecl->getAccess()); 14240 PushOnScopeChains(New, S); 14241 14242 ActOnDocumentableDecl(New); 14243 14244 return New; 14245 } 14246 14247 // Returns true when the enum initial expression does not trigger the 14248 // duplicate enum warning. A few common cases are exempted as follows: 14249 // Element2 = Element1 14250 // Element2 = Element1 + 1 14251 // Element2 = Element1 - 1 14252 // Where Element2 and Element1 are from the same enum. 14253 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 14254 Expr *InitExpr = ECD->getInitExpr(); 14255 if (!InitExpr) 14256 return true; 14257 InitExpr = InitExpr->IgnoreImpCasts(); 14258 14259 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 14260 if (!BO->isAdditiveOp()) 14261 return true; 14262 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 14263 if (!IL) 14264 return true; 14265 if (IL->getValue() != 1) 14266 return true; 14267 14268 InitExpr = BO->getLHS(); 14269 } 14270 14271 // This checks if the elements are from the same enum. 14272 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 14273 if (!DRE) 14274 return true; 14275 14276 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 14277 if (!EnumConstant) 14278 return true; 14279 14280 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 14281 Enum) 14282 return true; 14283 14284 return false; 14285 } 14286 14287 namespace { 14288 struct DupKey { 14289 int64_t val; 14290 bool isTombstoneOrEmptyKey; 14291 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 14292 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 14293 }; 14294 14295 static DupKey GetDupKey(const llvm::APSInt& Val) { 14296 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 14297 false); 14298 } 14299 14300 struct DenseMapInfoDupKey { 14301 static DupKey getEmptyKey() { return DupKey(0, true); } 14302 static DupKey getTombstoneKey() { return DupKey(1, true); } 14303 static unsigned getHashValue(const DupKey Key) { 14304 return (unsigned)(Key.val * 37); 14305 } 14306 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 14307 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 14308 LHS.val == RHS.val; 14309 } 14310 }; 14311 } // end anonymous namespace 14312 14313 // Emits a warning when an element is implicitly set a value that 14314 // a previous element has already been set to. 14315 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 14316 EnumDecl *Enum, 14317 QualType EnumType) { 14318 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 14319 return; 14320 // Avoid anonymous enums 14321 if (!Enum->getIdentifier()) 14322 return; 14323 14324 // Only check for small enums. 14325 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 14326 return; 14327 14328 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 14329 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 14330 14331 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 14332 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 14333 ValueToVectorMap; 14334 14335 DuplicatesVector DupVector; 14336 ValueToVectorMap EnumMap; 14337 14338 // Populate the EnumMap with all values represented by enum constants without 14339 // an initialier. 14340 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14341 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 14342 14343 // Null EnumConstantDecl means a previous diagnostic has been emitted for 14344 // this constant. Skip this enum since it may be ill-formed. 14345 if (!ECD) { 14346 return; 14347 } 14348 14349 if (ECD->getInitExpr()) 14350 continue; 14351 14352 DupKey Key = GetDupKey(ECD->getInitVal()); 14353 DeclOrVector &Entry = EnumMap[Key]; 14354 14355 // First time encountering this value. 14356 if (Entry.isNull()) 14357 Entry = ECD; 14358 } 14359 14360 // Create vectors for any values that has duplicates. 14361 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14362 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 14363 if (!ValidDuplicateEnum(ECD, Enum)) 14364 continue; 14365 14366 DupKey Key = GetDupKey(ECD->getInitVal()); 14367 14368 DeclOrVector& Entry = EnumMap[Key]; 14369 if (Entry.isNull()) 14370 continue; 14371 14372 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 14373 // Ensure constants are different. 14374 if (D == ECD) 14375 continue; 14376 14377 // Create new vector and push values onto it. 14378 ECDVector *Vec = new ECDVector(); 14379 Vec->push_back(D); 14380 Vec->push_back(ECD); 14381 14382 // Update entry to point to the duplicates vector. 14383 Entry = Vec; 14384 14385 // Store the vector somewhere we can consult later for quick emission of 14386 // diagnostics. 14387 DupVector.push_back(Vec); 14388 continue; 14389 } 14390 14391 ECDVector *Vec = Entry.get<ECDVector*>(); 14392 // Make sure constants are not added more than once. 14393 if (*Vec->begin() == ECD) 14394 continue; 14395 14396 Vec->push_back(ECD); 14397 } 14398 14399 // Emit diagnostics. 14400 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 14401 DupVectorEnd = DupVector.end(); 14402 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 14403 ECDVector *Vec = *DupVectorIter; 14404 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 14405 14406 // Emit warning for one enum constant. 14407 ECDVector::iterator I = Vec->begin(); 14408 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 14409 << (*I)->getName() << (*I)->getInitVal().toString(10) 14410 << (*I)->getSourceRange(); 14411 ++I; 14412 14413 // Emit one note for each of the remaining enum constants with 14414 // the same value. 14415 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 14416 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 14417 << (*I)->getName() << (*I)->getInitVal().toString(10) 14418 << (*I)->getSourceRange(); 14419 delete Vec; 14420 } 14421 } 14422 14423 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 14424 bool AllowMask) const { 14425 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 14426 assert(ED->isCompleteDefinition() && "expected enum definition"); 14427 14428 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 14429 llvm::APInt &FlagBits = R.first->second; 14430 14431 if (R.second) { 14432 for (auto *E : ED->enumerators()) { 14433 const auto &EVal = E->getInitVal(); 14434 // Only single-bit enumerators introduce new flag values. 14435 if (EVal.isPowerOf2()) 14436 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 14437 } 14438 } 14439 14440 // A value is in a flag enum if either its bits are a subset of the enum's 14441 // flag bits (the first condition) or we are allowing masks and the same is 14442 // true of its complement (the second condition). When masks are allowed, we 14443 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 14444 // 14445 // While it's true that any value could be used as a mask, the assumption is 14446 // that a mask will have all of the insignificant bits set. Anything else is 14447 // likely a logic error. 14448 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 14449 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 14450 } 14451 14452 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 14453 SourceLocation RBraceLoc, Decl *EnumDeclX, 14454 ArrayRef<Decl *> Elements, 14455 Scope *S, AttributeList *Attr) { 14456 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 14457 QualType EnumType = Context.getTypeDeclType(Enum); 14458 14459 if (Attr) 14460 ProcessDeclAttributeList(S, Enum, Attr); 14461 14462 if (Enum->isDependentType()) { 14463 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14464 EnumConstantDecl *ECD = 14465 cast_or_null<EnumConstantDecl>(Elements[i]); 14466 if (!ECD) continue; 14467 14468 ECD->setType(EnumType); 14469 } 14470 14471 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 14472 return; 14473 } 14474 14475 // TODO: If the result value doesn't fit in an int, it must be a long or long 14476 // long value. ISO C does not support this, but GCC does as an extension, 14477 // emit a warning. 14478 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14479 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 14480 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 14481 14482 // Verify that all the values are okay, compute the size of the values, and 14483 // reverse the list. 14484 unsigned NumNegativeBits = 0; 14485 unsigned NumPositiveBits = 0; 14486 14487 // Keep track of whether all elements have type int. 14488 bool AllElementsInt = true; 14489 14490 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14491 EnumConstantDecl *ECD = 14492 cast_or_null<EnumConstantDecl>(Elements[i]); 14493 if (!ECD) continue; // Already issued a diagnostic. 14494 14495 const llvm::APSInt &InitVal = ECD->getInitVal(); 14496 14497 // Keep track of the size of positive and negative values. 14498 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 14499 NumPositiveBits = std::max(NumPositiveBits, 14500 (unsigned)InitVal.getActiveBits()); 14501 else 14502 NumNegativeBits = std::max(NumNegativeBits, 14503 (unsigned)InitVal.getMinSignedBits()); 14504 14505 // Keep track of whether every enum element has type int (very commmon). 14506 if (AllElementsInt) 14507 AllElementsInt = ECD->getType() == Context.IntTy; 14508 } 14509 14510 // Figure out the type that should be used for this enum. 14511 QualType BestType; 14512 unsigned BestWidth; 14513 14514 // C++0x N3000 [conv.prom]p3: 14515 // An rvalue of an unscoped enumeration type whose underlying 14516 // type is not fixed can be converted to an rvalue of the first 14517 // of the following types that can represent all the values of 14518 // the enumeration: int, unsigned int, long int, unsigned long 14519 // int, long long int, or unsigned long long int. 14520 // C99 6.4.4.3p2: 14521 // An identifier declared as an enumeration constant has type int. 14522 // The C99 rule is modified by a gcc extension 14523 QualType BestPromotionType; 14524 14525 bool Packed = Enum->hasAttr<PackedAttr>(); 14526 // -fshort-enums is the equivalent to specifying the packed attribute on all 14527 // enum definitions. 14528 if (LangOpts.ShortEnums) 14529 Packed = true; 14530 14531 if (Enum->isFixed()) { 14532 BestType = Enum->getIntegerType(); 14533 if (BestType->isPromotableIntegerType()) 14534 BestPromotionType = Context.getPromotedIntegerType(BestType); 14535 else 14536 BestPromotionType = BestType; 14537 14538 BestWidth = Context.getIntWidth(BestType); 14539 } 14540 else if (NumNegativeBits) { 14541 // If there is a negative value, figure out the smallest integer type (of 14542 // int/long/longlong) that fits. 14543 // If it's packed, check also if it fits a char or a short. 14544 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 14545 BestType = Context.SignedCharTy; 14546 BestWidth = CharWidth; 14547 } else if (Packed && NumNegativeBits <= ShortWidth && 14548 NumPositiveBits < ShortWidth) { 14549 BestType = Context.ShortTy; 14550 BestWidth = ShortWidth; 14551 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 14552 BestType = Context.IntTy; 14553 BestWidth = IntWidth; 14554 } else { 14555 BestWidth = Context.getTargetInfo().getLongWidth(); 14556 14557 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 14558 BestType = Context.LongTy; 14559 } else { 14560 BestWidth = Context.getTargetInfo().getLongLongWidth(); 14561 14562 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 14563 Diag(Enum->getLocation(), diag::ext_enum_too_large); 14564 BestType = Context.LongLongTy; 14565 } 14566 } 14567 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 14568 } else { 14569 // If there is no negative value, figure out the smallest type that fits 14570 // all of the enumerator values. 14571 // If it's packed, check also if it fits a char or a short. 14572 if (Packed && NumPositiveBits <= CharWidth) { 14573 BestType = Context.UnsignedCharTy; 14574 BestPromotionType = Context.IntTy; 14575 BestWidth = CharWidth; 14576 } else if (Packed && NumPositiveBits <= ShortWidth) { 14577 BestType = Context.UnsignedShortTy; 14578 BestPromotionType = Context.IntTy; 14579 BestWidth = ShortWidth; 14580 } else if (NumPositiveBits <= IntWidth) { 14581 BestType = Context.UnsignedIntTy; 14582 BestWidth = IntWidth; 14583 BestPromotionType 14584 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14585 ? Context.UnsignedIntTy : Context.IntTy; 14586 } else if (NumPositiveBits <= 14587 (BestWidth = Context.getTargetInfo().getLongWidth())) { 14588 BestType = Context.UnsignedLongTy; 14589 BestPromotionType 14590 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14591 ? Context.UnsignedLongTy : Context.LongTy; 14592 } else { 14593 BestWidth = Context.getTargetInfo().getLongLongWidth(); 14594 assert(NumPositiveBits <= BestWidth && 14595 "How could an initializer get larger than ULL?"); 14596 BestType = Context.UnsignedLongLongTy; 14597 BestPromotionType 14598 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14599 ? Context.UnsignedLongLongTy : Context.LongLongTy; 14600 } 14601 } 14602 14603 // Loop over all of the enumerator constants, changing their types to match 14604 // the type of the enum if needed. 14605 for (auto *D : Elements) { 14606 auto *ECD = cast_or_null<EnumConstantDecl>(D); 14607 if (!ECD) continue; // Already issued a diagnostic. 14608 14609 // Standard C says the enumerators have int type, but we allow, as an 14610 // extension, the enumerators to be larger than int size. If each 14611 // enumerator value fits in an int, type it as an int, otherwise type it the 14612 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 14613 // that X has type 'int', not 'unsigned'. 14614 14615 // Determine whether the value fits into an int. 14616 llvm::APSInt InitVal = ECD->getInitVal(); 14617 14618 // If it fits into an integer type, force it. Otherwise force it to match 14619 // the enum decl type. 14620 QualType NewTy; 14621 unsigned NewWidth; 14622 bool NewSign; 14623 if (!getLangOpts().CPlusPlus && 14624 !Enum->isFixed() && 14625 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 14626 NewTy = Context.IntTy; 14627 NewWidth = IntWidth; 14628 NewSign = true; 14629 } else if (ECD->getType() == BestType) { 14630 // Already the right type! 14631 if (getLangOpts().CPlusPlus) 14632 // C++ [dcl.enum]p4: Following the closing brace of an 14633 // enum-specifier, each enumerator has the type of its 14634 // enumeration. 14635 ECD->setType(EnumType); 14636 continue; 14637 } else { 14638 NewTy = BestType; 14639 NewWidth = BestWidth; 14640 NewSign = BestType->isSignedIntegerOrEnumerationType(); 14641 } 14642 14643 // Adjust the APSInt value. 14644 InitVal = InitVal.extOrTrunc(NewWidth); 14645 InitVal.setIsSigned(NewSign); 14646 ECD->setInitVal(InitVal); 14647 14648 // Adjust the Expr initializer and type. 14649 if (ECD->getInitExpr() && 14650 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 14651 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 14652 CK_IntegralCast, 14653 ECD->getInitExpr(), 14654 /*base paths*/ nullptr, 14655 VK_RValue)); 14656 if (getLangOpts().CPlusPlus) 14657 // C++ [dcl.enum]p4: Following the closing brace of an 14658 // enum-specifier, each enumerator has the type of its 14659 // enumeration. 14660 ECD->setType(EnumType); 14661 else 14662 ECD->setType(NewTy); 14663 } 14664 14665 Enum->completeDefinition(BestType, BestPromotionType, 14666 NumPositiveBits, NumNegativeBits); 14667 14668 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 14669 14670 if (Enum->hasAttr<FlagEnumAttr>()) { 14671 for (Decl *D : Elements) { 14672 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 14673 if (!ECD) continue; // Already issued a diagnostic. 14674 14675 llvm::APSInt InitVal = ECD->getInitVal(); 14676 if (InitVal != 0 && !InitVal.isPowerOf2() && 14677 !IsValueInFlagEnum(Enum, InitVal, true)) 14678 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 14679 << ECD << Enum; 14680 } 14681 } 14682 14683 // Now that the enum type is defined, ensure it's not been underaligned. 14684 if (Enum->hasAttrs()) 14685 CheckAlignasUnderalignment(Enum); 14686 } 14687 14688 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 14689 SourceLocation StartLoc, 14690 SourceLocation EndLoc) { 14691 StringLiteral *AsmString = cast<StringLiteral>(expr); 14692 14693 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 14694 AsmString, StartLoc, 14695 EndLoc); 14696 CurContext->addDecl(New); 14697 return New; 14698 } 14699 14700 static void checkModuleImportContext(Sema &S, Module *M, 14701 SourceLocation ImportLoc, DeclContext *DC, 14702 bool FromInclude = false) { 14703 SourceLocation ExternCLoc; 14704 14705 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 14706 switch (LSD->getLanguage()) { 14707 case LinkageSpecDecl::lang_c: 14708 if (ExternCLoc.isInvalid()) 14709 ExternCLoc = LSD->getLocStart(); 14710 break; 14711 case LinkageSpecDecl::lang_cxx: 14712 break; 14713 } 14714 DC = LSD->getParent(); 14715 } 14716 14717 while (isa<LinkageSpecDecl>(DC)) 14718 DC = DC->getParent(); 14719 14720 if (!isa<TranslationUnitDecl>(DC)) { 14721 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 14722 ? diag::ext_module_import_not_at_top_level_noop 14723 : diag::err_module_import_not_at_top_level_fatal) 14724 << M->getFullModuleName() << DC; 14725 S.Diag(cast<Decl>(DC)->getLocStart(), 14726 diag::note_module_import_not_at_top_level) << DC; 14727 } else if (!M->IsExternC && ExternCLoc.isValid()) { 14728 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 14729 << M->getFullModuleName(); 14730 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c); 14731 } 14732 } 14733 14734 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) { 14735 return checkModuleImportContext(*this, M, ImportLoc, CurContext); 14736 } 14737 14738 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 14739 SourceLocation ImportLoc, 14740 ModuleIdPath Path) { 14741 Module *Mod = 14742 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 14743 /*IsIncludeDirective=*/false); 14744 if (!Mod) 14745 return true; 14746 14747 VisibleModules.setVisible(Mod, ImportLoc); 14748 14749 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 14750 14751 // FIXME: we should support importing a submodule within a different submodule 14752 // of the same top-level module. Until we do, make it an error rather than 14753 // silently ignoring the import. 14754 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 14755 Diag(ImportLoc, getLangOpts().CompilingModule 14756 ? diag::err_module_self_import 14757 : diag::err_module_import_in_implementation) 14758 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 14759 14760 SmallVector<SourceLocation, 2> IdentifierLocs; 14761 Module *ModCheck = Mod; 14762 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 14763 // If we've run out of module parents, just drop the remaining identifiers. 14764 // We need the length to be consistent. 14765 if (!ModCheck) 14766 break; 14767 ModCheck = ModCheck->Parent; 14768 14769 IdentifierLocs.push_back(Path[I].second); 14770 } 14771 14772 ImportDecl *Import = ImportDecl::Create(Context, 14773 Context.getTranslationUnitDecl(), 14774 AtLoc.isValid()? AtLoc : ImportLoc, 14775 Mod, IdentifierLocs); 14776 Context.getTranslationUnitDecl()->addDecl(Import); 14777 return Import; 14778 } 14779 14780 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 14781 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 14782 14783 // Determine whether we're in the #include buffer for a module. The #includes 14784 // in that buffer do not qualify as module imports; they're just an 14785 // implementation detail of us building the module. 14786 // 14787 // FIXME: Should we even get ActOnModuleInclude calls for those? 14788 bool IsInModuleIncludes = 14789 TUKind == TU_Module && 14790 getSourceManager().isWrittenInMainFile(DirectiveLoc); 14791 14792 // Similarly, if we're in the implementation of a module, don't 14793 // synthesize an illegal module import. FIXME: Why not? 14794 bool ShouldAddImport = 14795 !IsInModuleIncludes && 14796 (getLangOpts().CompilingModule || 14797 getLangOpts().CurrentModule.empty() || 14798 getLangOpts().CurrentModule != Mod->getTopLevelModuleName()); 14799 14800 // If this module import was due to an inclusion directive, create an 14801 // implicit import declaration to capture it in the AST. 14802 if (ShouldAddImport) { 14803 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14804 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14805 DirectiveLoc, Mod, 14806 DirectiveLoc); 14807 TU->addDecl(ImportD); 14808 Consumer.HandleImplicitImportDecl(ImportD); 14809 } 14810 14811 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 14812 VisibleModules.setVisible(Mod, DirectiveLoc); 14813 } 14814 14815 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 14816 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14817 14818 if (getLangOpts().ModulesLocalVisibility) 14819 VisibleModulesStack.push_back(std::move(VisibleModules)); 14820 VisibleModules.setVisible(Mod, DirectiveLoc); 14821 } 14822 14823 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) { 14824 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14825 14826 if (getLangOpts().ModulesLocalVisibility) { 14827 VisibleModules = std::move(VisibleModulesStack.back()); 14828 VisibleModulesStack.pop_back(); 14829 VisibleModules.setVisible(Mod, DirectiveLoc); 14830 // Leaving a module hides namespace names, so our visible namespace cache 14831 // is now out of date. 14832 VisibleNamespaceCache.clear(); 14833 } 14834 } 14835 14836 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 14837 Module *Mod) { 14838 // Bail if we're not allowed to implicitly import a module here. 14839 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 14840 return; 14841 14842 // Create the implicit import declaration. 14843 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14844 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14845 Loc, Mod, Loc); 14846 TU->addDecl(ImportD); 14847 Consumer.HandleImplicitImportDecl(ImportD); 14848 14849 // Make the module visible. 14850 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 14851 VisibleModules.setVisible(Mod, Loc); 14852 } 14853 14854 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 14855 IdentifierInfo* AliasName, 14856 SourceLocation PragmaLoc, 14857 SourceLocation NameLoc, 14858 SourceLocation AliasNameLoc) { 14859 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 14860 LookupOrdinaryName); 14861 AsmLabelAttr *Attr = 14862 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 14863 14864 // If a declaration that: 14865 // 1) declares a function or a variable 14866 // 2) has external linkage 14867 // already exists, add a label attribute to it. 14868 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 14869 if (isDeclExternC(PrevDecl)) 14870 PrevDecl->addAttr(Attr); 14871 else 14872 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 14873 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 14874 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 14875 } else 14876 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 14877 } 14878 14879 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 14880 SourceLocation PragmaLoc, 14881 SourceLocation NameLoc) { 14882 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 14883 14884 if (PrevDecl) { 14885 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 14886 } else { 14887 (void)WeakUndeclaredIdentifiers.insert( 14888 std::pair<IdentifierInfo*,WeakInfo> 14889 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 14890 } 14891 } 14892 14893 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 14894 IdentifierInfo* AliasName, 14895 SourceLocation PragmaLoc, 14896 SourceLocation NameLoc, 14897 SourceLocation AliasNameLoc) { 14898 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 14899 LookupOrdinaryName); 14900 WeakInfo W = WeakInfo(Name, NameLoc); 14901 14902 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 14903 if (!PrevDecl->hasAttr<AliasAttr>()) 14904 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 14905 DeclApplyPragmaWeak(TUScope, ND, W); 14906 } else { 14907 (void)WeakUndeclaredIdentifiers.insert( 14908 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 14909 } 14910 } 14911 14912 Decl *Sema::getObjCDeclContext() const { 14913 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 14914 } 14915 14916 AvailabilityResult Sema::getCurContextAvailability() const { 14917 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 14918 if (!D) 14919 return AR_Available; 14920 14921 // If we are within an Objective-C method, we should consult 14922 // both the availability of the method as well as the 14923 // enclosing class. If the class is (say) deprecated, 14924 // the entire method is considered deprecated from the 14925 // purpose of checking if the current context is deprecated. 14926 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 14927 AvailabilityResult R = MD->getAvailability(); 14928 if (R != AR_Available) 14929 return R; 14930 D = MD->getClassInterface(); 14931 } 14932 // If we are within an Objective-c @implementation, it 14933 // gets the same availability context as the @interface. 14934 else if (const ObjCImplementationDecl *ID = 14935 dyn_cast<ObjCImplementationDecl>(D)) { 14936 D = ID->getClassInterface(); 14937 } 14938 // Recover from user error. 14939 return D ? D->getAvailability() : AR_Available; 14940 } 14941