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___float128: 112 case tok::kw_wchar_t: 113 case tok::kw_bool: 114 case tok::kw___underlying_type: 115 case tok::kw___auto_type: 116 return true; 117 118 case tok::annot_typename: 119 case tok::kw_char16_t: 120 case tok::kw_char32_t: 121 case tok::kw_typeof: 122 case tok::annot_decltype: 123 case tok::kw_decltype: 124 return getLangOpts().CPlusPlus; 125 126 default: 127 break; 128 } 129 130 return false; 131 } 132 133 namespace { 134 enum class UnqualifiedTypeNameLookupResult { 135 NotFound, 136 FoundNonType, 137 FoundType 138 }; 139 } // end anonymous namespace 140 141 /// \brief Tries to perform unqualified lookup of the type decls in bases for 142 /// dependent class. 143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 144 /// type decl, \a FoundType if only type decls are found. 145 static UnqualifiedTypeNameLookupResult 146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 147 SourceLocation NameLoc, 148 const CXXRecordDecl *RD) { 149 if (!RD->hasDefinition()) 150 return UnqualifiedTypeNameLookupResult::NotFound; 151 // Look for type decls in base classes. 152 UnqualifiedTypeNameLookupResult FoundTypeDecl = 153 UnqualifiedTypeNameLookupResult::NotFound; 154 for (const auto &Base : RD->bases()) { 155 const CXXRecordDecl *BaseRD = nullptr; 156 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 157 BaseRD = BaseTT->getAsCXXRecordDecl(); 158 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 159 // Look for type decls in dependent base classes that have known primary 160 // templates. 161 if (!TST || !TST->isDependentType()) 162 continue; 163 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 164 if (!TD) 165 continue; 166 if (auto *BasePrimaryTemplate = 167 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 168 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 169 BaseRD = BasePrimaryTemplate; 170 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 171 if (const ClassTemplatePartialSpecializationDecl *PS = 172 CTD->findPartialSpecialization(Base.getType())) 173 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 174 BaseRD = PS; 175 } 176 } 177 } 178 if (BaseRD) { 179 for (NamedDecl *ND : BaseRD->lookup(&II)) { 180 if (!isa<TypeDecl>(ND)) 181 return UnqualifiedTypeNameLookupResult::FoundNonType; 182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 183 } 184 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 185 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 186 case UnqualifiedTypeNameLookupResult::FoundNonType: 187 return UnqualifiedTypeNameLookupResult::FoundNonType; 188 case UnqualifiedTypeNameLookupResult::FoundType: 189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 190 break; 191 case UnqualifiedTypeNameLookupResult::NotFound: 192 break; 193 } 194 } 195 } 196 } 197 198 return FoundTypeDecl; 199 } 200 201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 202 const IdentifierInfo &II, 203 SourceLocation NameLoc) { 204 // Lookup in the parent class template context, if any. 205 const CXXRecordDecl *RD = nullptr; 206 UnqualifiedTypeNameLookupResult FoundTypeDecl = 207 UnqualifiedTypeNameLookupResult::NotFound; 208 for (DeclContext *DC = S.CurContext; 209 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 210 DC = DC->getParent()) { 211 // Look for type decls in dependent base classes that have known primary 212 // templates. 213 RD = dyn_cast<CXXRecordDecl>(DC); 214 if (RD && RD->getDescribedClassTemplate()) 215 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 216 } 217 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 218 return nullptr; 219 220 // We found some types in dependent base classes. Recover as if the user 221 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 222 // lookup during template instantiation. 223 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 224 225 ASTContext &Context = S.Context; 226 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 227 cast<Type>(Context.getRecordType(RD))); 228 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 229 230 CXXScopeSpec SS; 231 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 232 233 TypeLocBuilder Builder; 234 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 235 DepTL.setNameLoc(NameLoc); 236 DepTL.setElaboratedKeywordLoc(SourceLocation()); 237 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 238 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 239 } 240 241 /// \brief If the identifier refers to a type name within this scope, 242 /// return the declaration of that type. 243 /// 244 /// This routine performs ordinary name lookup of the identifier II 245 /// within the given scope, with optional C++ scope specifier SS, to 246 /// determine whether the name refers to a type. If so, returns an 247 /// opaque pointer (actually a QualType) corresponding to that 248 /// type. Otherwise, returns NULL. 249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 250 Scope *S, CXXScopeSpec *SS, 251 bool isClassName, bool HasTrailingDot, 252 ParsedType ObjectTypePtr, 253 bool IsCtorOrDtorName, 254 bool WantNontrivialTypeSourceInfo, 255 IdentifierInfo **CorrectedII) { 256 // Determine where we will perform name lookup. 257 DeclContext *LookupCtx = nullptr; 258 if (ObjectTypePtr) { 259 QualType ObjectType = ObjectTypePtr.get(); 260 if (ObjectType->isRecordType()) 261 LookupCtx = computeDeclContext(ObjectType); 262 } else if (SS && SS->isNotEmpty()) { 263 LookupCtx = computeDeclContext(*SS, false); 264 265 if (!LookupCtx) { 266 if (isDependentScopeSpecifier(*SS)) { 267 // C++ [temp.res]p3: 268 // A qualified-id that refers to a type and in which the 269 // nested-name-specifier depends on a template-parameter (14.6.2) 270 // shall be prefixed by the keyword typename to indicate that the 271 // qualified-id denotes a type, forming an 272 // elaborated-type-specifier (7.1.5.3). 273 // 274 // We therefore do not perform any name lookup if the result would 275 // refer to a member of an unknown specialization. 276 if (!isClassName && !IsCtorOrDtorName) 277 return nullptr; 278 279 // We know from the grammar that this name refers to a type, 280 // so build a dependent node to describe the type. 281 if (WantNontrivialTypeSourceInfo) 282 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 283 284 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 285 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 286 II, NameLoc); 287 return ParsedType::make(T); 288 } 289 290 return nullptr; 291 } 292 293 if (!LookupCtx->isDependentContext() && 294 RequireCompleteDeclContext(*SS, LookupCtx)) 295 return nullptr; 296 } 297 298 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 299 // lookup for class-names. 300 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 301 LookupOrdinaryName; 302 LookupResult Result(*this, &II, NameLoc, Kind); 303 if (LookupCtx) { 304 // Perform "qualified" name lookup into the declaration context we 305 // computed, which is either the type of the base of a member access 306 // expression or the declaration context associated with a prior 307 // nested-name-specifier. 308 LookupQualifiedName(Result, LookupCtx); 309 310 if (ObjectTypePtr && Result.empty()) { 311 // C++ [basic.lookup.classref]p3: 312 // If the unqualified-id is ~type-name, the type-name is looked up 313 // in the context of the entire postfix-expression. If the type T of 314 // the object expression is of a class type C, the type-name is also 315 // looked up in the scope of class C. At least one of the lookups shall 316 // find a name that refers to (possibly cv-qualified) T. 317 LookupName(Result, S); 318 } 319 } else { 320 // Perform unqualified name lookup. 321 LookupName(Result, S); 322 323 // For unqualified lookup in a class template in MSVC mode, look into 324 // dependent base classes where the primary class template is known. 325 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 326 if (ParsedType TypeInBase = 327 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 328 return TypeInBase; 329 } 330 } 331 332 NamedDecl *IIDecl = nullptr; 333 switch (Result.getResultKind()) { 334 case LookupResult::NotFound: 335 case LookupResult::NotFoundInCurrentInstantiation: 336 if (CorrectedII) { 337 TypoCorrection Correction = CorrectTypo( 338 Result.getLookupNameInfo(), Kind, S, SS, 339 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName), 340 CTK_ErrorRecovery); 341 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 342 TemplateTy Template; 343 bool MemberOfUnknownSpecialization; 344 UnqualifiedId TemplateName; 345 TemplateName.setIdentifier(NewII, NameLoc); 346 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 347 CXXScopeSpec NewSS, *NewSSPtr = SS; 348 if (SS && NNS) { 349 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 350 NewSSPtr = &NewSS; 351 } 352 if (Correction && (NNS || NewII != &II) && 353 // Ignore a correction to a template type as the to-be-corrected 354 // identifier is not a template (typo correction for template names 355 // is handled elsewhere). 356 !(getLangOpts().CPlusPlus && NewSSPtr && 357 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 358 Template, MemberOfUnknownSpecialization))) { 359 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 360 isClassName, HasTrailingDot, ObjectTypePtr, 361 IsCtorOrDtorName, 362 WantNontrivialTypeSourceInfo); 363 if (Ty) { 364 diagnoseTypo(Correction, 365 PDiag(diag::err_unknown_type_or_class_name_suggest) 366 << Result.getLookupName() << isClassName); 367 if (SS && NNS) 368 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 369 *CorrectedII = NewII; 370 return Ty; 371 } 372 } 373 } 374 // If typo correction failed or was not performed, fall through 375 case LookupResult::FoundOverloaded: 376 case LookupResult::FoundUnresolvedValue: 377 Result.suppressDiagnostics(); 378 return nullptr; 379 380 case LookupResult::Ambiguous: 381 // Recover from type-hiding ambiguities by hiding the type. We'll 382 // do the lookup again when looking for an object, and we can 383 // diagnose the error then. If we don't do this, then the error 384 // about hiding the type will be immediately followed by an error 385 // that only makes sense if the identifier was treated like a type. 386 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 387 Result.suppressDiagnostics(); 388 return nullptr; 389 } 390 391 // Look to see if we have a type anywhere in the list of results. 392 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 393 Res != ResEnd; ++Res) { 394 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 395 if (!IIDecl || 396 (*Res)->getLocation().getRawEncoding() < 397 IIDecl->getLocation().getRawEncoding()) 398 IIDecl = *Res; 399 } 400 } 401 402 if (!IIDecl) { 403 // None of the entities we found is a type, so there is no way 404 // to even assume that the result is a type. In this case, don't 405 // complain about the ambiguity. The parser will either try to 406 // perform this lookup again (e.g., as an object name), which 407 // will produce the ambiguity, or will complain that it expected 408 // a type name. 409 Result.suppressDiagnostics(); 410 return nullptr; 411 } 412 413 // We found a type within the ambiguous lookup; diagnose the 414 // ambiguity and then return that type. This might be the right 415 // answer, or it might not be, but it suppresses any attempt to 416 // perform the name lookup again. 417 break; 418 419 case LookupResult::Found: 420 IIDecl = Result.getFoundDecl(); 421 break; 422 } 423 424 assert(IIDecl && "Didn't find decl"); 425 426 QualType T; 427 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 428 DiagnoseUseOfDecl(IIDecl, NameLoc); 429 430 T = Context.getTypeDeclType(TD); 431 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 432 433 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 434 // constructor or destructor name (in such a case, the scope specifier 435 // will be attached to the enclosing Expr or Decl node). 436 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 437 if (WantNontrivialTypeSourceInfo) { 438 // Construct a type with type-source information. 439 TypeLocBuilder Builder; 440 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 441 442 T = getElaboratedType(ETK_None, *SS, T); 443 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 444 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 445 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 446 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 447 } else { 448 T = getElaboratedType(ETK_None, *SS, T); 449 } 450 } 451 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 452 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 453 if (!HasTrailingDot) 454 T = Context.getObjCInterfaceType(IDecl); 455 } 456 457 if (T.isNull()) { 458 // If it's not plausibly a type, suppress diagnostics. 459 Result.suppressDiagnostics(); 460 return nullptr; 461 } 462 return ParsedType::make(T); 463 } 464 465 // Builds a fake NNS for the given decl context. 466 static NestedNameSpecifier * 467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 468 for (;; DC = DC->getLookupParent()) { 469 DC = DC->getPrimaryContext(); 470 auto *ND = dyn_cast<NamespaceDecl>(DC); 471 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 472 return NestedNameSpecifier::Create(Context, nullptr, ND); 473 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 474 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 475 RD->getTypeForDecl()); 476 else if (isa<TranslationUnitDecl>(DC)) 477 return NestedNameSpecifier::GlobalSpecifier(Context); 478 } 479 llvm_unreachable("something isn't in TU scope?"); 480 } 481 482 /// Find the parent class with dependent bases of the innermost enclosing method 483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 484 /// up allowing unqualified dependent type names at class-level, which MSVC 485 /// correctly rejects. 486 static const CXXRecordDecl * 487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 488 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 489 DC = DC->getPrimaryContext(); 490 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 491 if (MD->getParent()->hasAnyDependentBases()) 492 return MD->getParent(); 493 } 494 return nullptr; 495 } 496 497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 498 SourceLocation NameLoc, 499 bool IsTemplateTypeArg) { 500 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 501 502 NestedNameSpecifier *NNS = nullptr; 503 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 504 // If we weren't able to parse a default template argument, delay lookup 505 // until instantiation time by making a non-dependent DependentTypeName. We 506 // pretend we saw a NestedNameSpecifier referring to the current scope, and 507 // lookup is retried. 508 // FIXME: This hurts our diagnostic quality, since we get errors like "no 509 // type named 'Foo' in 'current_namespace'" when the user didn't write any 510 // name specifiers. 511 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 512 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 513 } else if (const CXXRecordDecl *RD = 514 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 515 // Build a DependentNameType that will perform lookup into RD at 516 // instantiation time. 517 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 518 RD->getTypeForDecl()); 519 520 // Diagnose that this identifier was undeclared, and retry the lookup during 521 // template instantiation. 522 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 523 << RD; 524 } else { 525 // This is not a situation that we should recover from. 526 return ParsedType(); 527 } 528 529 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 530 531 // Build type location information. We synthesized the qualifier, so we have 532 // to build a fake NestedNameSpecifierLoc. 533 NestedNameSpecifierLocBuilder NNSLocBuilder; 534 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 535 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 536 537 TypeLocBuilder Builder; 538 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 539 DepTL.setNameLoc(NameLoc); 540 DepTL.setElaboratedKeywordLoc(SourceLocation()); 541 DepTL.setQualifierLoc(QualifierLoc); 542 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 543 } 544 545 /// isTagName() - This method is called *for error recovery purposes only* 546 /// to determine if the specified name is a valid tag name ("struct foo"). If 547 /// so, this returns the TST for the tag corresponding to it (TST_enum, 548 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 549 /// cases in C where the user forgot to specify the tag. 550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 551 // Do a tag name lookup in this scope. 552 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 553 LookupName(R, S, false); 554 R.suppressDiagnostics(); 555 if (R.getResultKind() == LookupResult::Found) 556 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 557 switch (TD->getTagKind()) { 558 case TTK_Struct: return DeclSpec::TST_struct; 559 case TTK_Interface: return DeclSpec::TST_interface; 560 case TTK_Union: return DeclSpec::TST_union; 561 case TTK_Class: return DeclSpec::TST_class; 562 case TTK_Enum: return DeclSpec::TST_enum; 563 } 564 } 565 566 return DeclSpec::TST_unspecified; 567 } 568 569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 571 /// then downgrade the missing typename error to a warning. 572 /// This is needed for MSVC compatibility; Example: 573 /// @code 574 /// template<class T> class A { 575 /// public: 576 /// typedef int TYPE; 577 /// }; 578 /// template<class T> class B : public A<T> { 579 /// public: 580 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 581 /// }; 582 /// @endcode 583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 584 if (CurContext->isRecord()) { 585 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 586 return true; 587 588 const Type *Ty = SS->getScopeRep()->getAsType(); 589 590 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 591 for (const auto &Base : RD->bases()) 592 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 593 return true; 594 return S->isFunctionPrototypeScope(); 595 } 596 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 597 } 598 599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 600 SourceLocation IILoc, 601 Scope *S, 602 CXXScopeSpec *SS, 603 ParsedType &SuggestedType, 604 bool AllowClassTemplates) { 605 // We don't have anything to suggest (yet). 606 SuggestedType = nullptr; 607 608 // There may have been a typo in the name of the type. Look up typo 609 // results, in case we have something that we can suggest. 610 if (TypoCorrection Corrected = 611 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 612 llvm::make_unique<TypeNameValidatorCCC>( 613 false, false, AllowClassTemplates), 614 CTK_ErrorRecovery)) { 615 if (Corrected.isKeyword()) { 616 // We corrected to a keyword. 617 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 618 II = Corrected.getCorrectionAsIdentifierInfo(); 619 } else { 620 // We found a similarly-named type or interface; suggest that. 621 if (!SS || !SS->isSet()) { 622 diagnoseTypo(Corrected, 623 PDiag(diag::err_unknown_typename_suggest) << II); 624 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 625 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 626 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 627 II->getName().equals(CorrectedStr); 628 diagnoseTypo(Corrected, 629 PDiag(diag::err_unknown_nested_typename_suggest) 630 << II << DC << DroppedSpecifier << SS->getRange()); 631 } else { 632 llvm_unreachable("could not have corrected a typo here"); 633 } 634 635 CXXScopeSpec tmpSS; 636 if (Corrected.getCorrectionSpecifier()) 637 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 638 SourceRange(IILoc)); 639 SuggestedType = 640 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 641 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 642 /*IsCtorOrDtorName=*/false, 643 /*NonTrivialTypeSourceInfo=*/true); 644 } 645 return; 646 } 647 648 if (getLangOpts().CPlusPlus) { 649 // See if II is a class template that the user forgot to pass arguments to. 650 UnqualifiedId Name; 651 Name.setIdentifier(II, IILoc); 652 CXXScopeSpec EmptySS; 653 TemplateTy TemplateResult; 654 bool MemberOfUnknownSpecialization; 655 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 656 Name, nullptr, true, TemplateResult, 657 MemberOfUnknownSpecialization) == TNK_Type_template) { 658 TemplateName TplName = TemplateResult.get(); 659 Diag(IILoc, diag::err_template_missing_args) << TplName; 660 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 661 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 662 << TplDecl->getTemplateParameters()->getSourceRange(); 663 } 664 return; 665 } 666 } 667 668 // FIXME: Should we move the logic that tries to recover from a missing tag 669 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 670 671 if (!SS || (!SS->isSet() && !SS->isInvalid())) 672 Diag(IILoc, diag::err_unknown_typename) << II; 673 else if (DeclContext *DC = computeDeclContext(*SS, false)) 674 Diag(IILoc, diag::err_typename_nested_not_found) 675 << II << DC << SS->getRange(); 676 else if (isDependentScopeSpecifier(*SS)) { 677 unsigned DiagID = diag::err_typename_missing; 678 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 679 DiagID = diag::ext_typename_missing; 680 681 Diag(SS->getRange().getBegin(), DiagID) 682 << SS->getScopeRep() << II->getName() 683 << SourceRange(SS->getRange().getBegin(), IILoc) 684 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 685 SuggestedType = ActOnTypenameType(S, SourceLocation(), 686 *SS, *II, IILoc).get(); 687 } else { 688 assert(SS && SS->isInvalid() && 689 "Invalid scope specifier has already been diagnosed"); 690 } 691 } 692 693 /// \brief Determine whether the given result set contains either a type name 694 /// or 695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 696 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 697 NextToken.is(tok::less); 698 699 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 700 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 701 return true; 702 703 if (CheckTemplate && isa<TemplateDecl>(*I)) 704 return true; 705 } 706 707 return false; 708 } 709 710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 711 Scope *S, CXXScopeSpec &SS, 712 IdentifierInfo *&Name, 713 SourceLocation NameLoc) { 714 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 715 SemaRef.LookupParsedName(R, S, &SS); 716 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 717 StringRef FixItTagName; 718 switch (Tag->getTagKind()) { 719 case TTK_Class: 720 FixItTagName = "class "; 721 break; 722 723 case TTK_Enum: 724 FixItTagName = "enum "; 725 break; 726 727 case TTK_Struct: 728 FixItTagName = "struct "; 729 break; 730 731 case TTK_Interface: 732 FixItTagName = "__interface "; 733 break; 734 735 case TTK_Union: 736 FixItTagName = "union "; 737 break; 738 } 739 740 StringRef TagName = FixItTagName.drop_back(); 741 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 742 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 743 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 744 745 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 746 I != IEnd; ++I) 747 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 748 << Name << TagName; 749 750 // Replace lookup results with just the tag decl. 751 Result.clear(Sema::LookupTagName); 752 SemaRef.LookupParsedName(Result, S, &SS); 753 return true; 754 } 755 756 return false; 757 } 758 759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 761 QualType T, SourceLocation NameLoc) { 762 ASTContext &Context = S.Context; 763 764 TypeLocBuilder Builder; 765 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 766 767 T = S.getElaboratedType(ETK_None, SS, T); 768 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 769 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 770 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 771 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 772 } 773 774 Sema::NameClassification 775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 776 SourceLocation NameLoc, const Token &NextToken, 777 bool IsAddressOfOperand, 778 std::unique_ptr<CorrectionCandidateCallback> CCC) { 779 DeclarationNameInfo NameInfo(Name, NameLoc); 780 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 781 782 if (NextToken.is(tok::coloncolon)) { 783 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 784 QualType(), false, SS, nullptr, false); 785 } 786 787 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 788 LookupParsedName(Result, S, &SS, !CurMethod); 789 790 // For unqualified lookup in a class template in MSVC mode, look into 791 // dependent base classes where the primary class template is known. 792 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 793 if (ParsedType TypeInBase = 794 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 795 return TypeInBase; 796 } 797 798 // Perform lookup for Objective-C instance variables (including automatically 799 // synthesized instance variables), if we're in an Objective-C method. 800 // FIXME: This lookup really, really needs to be folded in to the normal 801 // unqualified lookup mechanism. 802 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 803 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 804 if (E.get() || E.isInvalid()) 805 return E; 806 } 807 808 bool SecondTry = false; 809 bool IsFilteredTemplateName = false; 810 811 Corrected: 812 switch (Result.getResultKind()) { 813 case LookupResult::NotFound: 814 // If an unqualified-id is followed by a '(', then we have a function 815 // call. 816 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 817 // In C++, this is an ADL-only call. 818 // FIXME: Reference? 819 if (getLangOpts().CPlusPlus) 820 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 821 822 // C90 6.3.2.2: 823 // If the expression that precedes the parenthesized argument list in a 824 // function call consists solely of an identifier, and if no 825 // declaration is visible for this identifier, the identifier is 826 // implicitly declared exactly as if, in the innermost block containing 827 // the function call, the declaration 828 // 829 // extern int identifier (); 830 // 831 // appeared. 832 // 833 // We also allow this in C99 as an extension. 834 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 835 Result.addDecl(D); 836 Result.resolveKind(); 837 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 838 } 839 } 840 841 // In C, we first see whether there is a tag type by the same name, in 842 // which case it's likely that the user just forgot to write "enum", 843 // "struct", or "union". 844 if (!getLangOpts().CPlusPlus && !SecondTry && 845 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 846 break; 847 } 848 849 // Perform typo correction to determine if there is another name that is 850 // close to this name. 851 if (!SecondTry && CCC) { 852 SecondTry = true; 853 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 854 Result.getLookupKind(), S, 855 &SS, std::move(CCC), 856 CTK_ErrorRecovery)) { 857 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 858 unsigned QualifiedDiag = diag::err_no_member_suggest; 859 860 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 861 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 862 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 863 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 864 UnqualifiedDiag = diag::err_no_template_suggest; 865 QualifiedDiag = diag::err_no_member_template_suggest; 866 } else if (UnderlyingFirstDecl && 867 (isa<TypeDecl>(UnderlyingFirstDecl) || 868 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 869 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 870 UnqualifiedDiag = diag::err_unknown_typename_suggest; 871 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 872 } 873 874 if (SS.isEmpty()) { 875 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 876 } else {// FIXME: is this even reachable? Test it. 877 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 878 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 879 Name->getName().equals(CorrectedStr); 880 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 881 << Name << computeDeclContext(SS, false) 882 << DroppedSpecifier << SS.getRange()); 883 } 884 885 // Update the name, so that the caller has the new name. 886 Name = Corrected.getCorrectionAsIdentifierInfo(); 887 888 // Typo correction corrected to a keyword. 889 if (Corrected.isKeyword()) 890 return Name; 891 892 // Also update the LookupResult... 893 // FIXME: This should probably go away at some point 894 Result.clear(); 895 Result.setLookupName(Corrected.getCorrection()); 896 if (FirstDecl) 897 Result.addDecl(FirstDecl); 898 899 // If we found an Objective-C instance variable, let 900 // LookupInObjCMethod build the appropriate expression to 901 // reference the ivar. 902 // FIXME: This is a gross hack. 903 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 904 Result.clear(); 905 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 906 return E; 907 } 908 909 goto Corrected; 910 } 911 } 912 913 // We failed to correct; just fall through and let the parser deal with it. 914 Result.suppressDiagnostics(); 915 return NameClassification::Unknown(); 916 917 case LookupResult::NotFoundInCurrentInstantiation: { 918 // We performed name lookup into the current instantiation, and there were 919 // dependent bases, so we treat this result the same way as any other 920 // dependent nested-name-specifier. 921 922 // C++ [temp.res]p2: 923 // A name used in a template declaration or definition and that is 924 // dependent on a template-parameter is assumed not to name a type 925 // unless the applicable name lookup finds a type name or the name is 926 // qualified by the keyword typename. 927 // 928 // FIXME: If the next token is '<', we might want to ask the parser to 929 // perform some heroics to see if we actually have a 930 // template-argument-list, which would indicate a missing 'template' 931 // keyword here. 932 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 933 NameInfo, IsAddressOfOperand, 934 /*TemplateArgs=*/nullptr); 935 } 936 937 case LookupResult::Found: 938 case LookupResult::FoundOverloaded: 939 case LookupResult::FoundUnresolvedValue: 940 break; 941 942 case LookupResult::Ambiguous: 943 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 944 hasAnyAcceptableTemplateNames(Result)) { 945 // C++ [temp.local]p3: 946 // A lookup that finds an injected-class-name (10.2) can result in an 947 // ambiguity in certain cases (for example, if it is found in more than 948 // one base class). If all of the injected-class-names that are found 949 // refer to specializations of the same class template, and if the name 950 // is followed by a template-argument-list, the reference refers to the 951 // class template itself and not a specialization thereof, and is not 952 // ambiguous. 953 // 954 // This filtering can make an ambiguous result into an unambiguous one, 955 // so try again after filtering out template names. 956 FilterAcceptableTemplateNames(Result); 957 if (!Result.isAmbiguous()) { 958 IsFilteredTemplateName = true; 959 break; 960 } 961 } 962 963 // Diagnose the ambiguity and return an error. 964 return NameClassification::Error(); 965 } 966 967 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 968 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 969 // C++ [temp.names]p3: 970 // After name lookup (3.4) finds that a name is a template-name or that 971 // an operator-function-id or a literal- operator-id refers to a set of 972 // overloaded functions any member of which is a function template if 973 // this is followed by a <, the < is always taken as the delimiter of a 974 // template-argument-list and never as the less-than operator. 975 if (!IsFilteredTemplateName) 976 FilterAcceptableTemplateNames(Result); 977 978 if (!Result.empty()) { 979 bool IsFunctionTemplate; 980 bool IsVarTemplate; 981 TemplateName Template; 982 if (Result.end() - Result.begin() > 1) { 983 IsFunctionTemplate = true; 984 Template = Context.getOverloadedTemplateName(Result.begin(), 985 Result.end()); 986 } else { 987 TemplateDecl *TD 988 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 989 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 990 IsVarTemplate = isa<VarTemplateDecl>(TD); 991 992 if (SS.isSet() && !SS.isInvalid()) 993 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 994 /*TemplateKeyword=*/false, 995 TD); 996 else 997 Template = TemplateName(TD); 998 } 999 1000 if (IsFunctionTemplate) { 1001 // Function templates always go through overload resolution, at which 1002 // point we'll perform the various checks (e.g., accessibility) we need 1003 // to based on which function we selected. 1004 Result.suppressDiagnostics(); 1005 1006 return NameClassification::FunctionTemplate(Template); 1007 } 1008 1009 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1010 : NameClassification::TypeTemplate(Template); 1011 } 1012 } 1013 1014 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1015 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1016 DiagnoseUseOfDecl(Type, NameLoc); 1017 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1018 QualType T = Context.getTypeDeclType(Type); 1019 if (SS.isNotEmpty()) 1020 return buildNestedType(*this, SS, T, NameLoc); 1021 return ParsedType::make(T); 1022 } 1023 1024 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1025 if (!Class) { 1026 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1027 if (ObjCCompatibleAliasDecl *Alias = 1028 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1029 Class = Alias->getClassInterface(); 1030 } 1031 1032 if (Class) { 1033 DiagnoseUseOfDecl(Class, NameLoc); 1034 1035 if (NextToken.is(tok::period)) { 1036 // Interface. <something> is parsed as a property reference expression. 1037 // Just return "unknown" as a fall-through for now. 1038 Result.suppressDiagnostics(); 1039 return NameClassification::Unknown(); 1040 } 1041 1042 QualType T = Context.getObjCInterfaceType(Class); 1043 return ParsedType::make(T); 1044 } 1045 1046 // We can have a type template here if we're classifying a template argument. 1047 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 1048 return NameClassification::TypeTemplate( 1049 TemplateName(cast<TemplateDecl>(FirstDecl))); 1050 1051 // Check for a tag type hidden by a non-type decl in a few cases where it 1052 // seems likely a type is wanted instead of the non-type that was found. 1053 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1054 if ((NextToken.is(tok::identifier) || 1055 (NextIsOp && 1056 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1057 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1058 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1059 DiagnoseUseOfDecl(Type, NameLoc); 1060 QualType T = Context.getTypeDeclType(Type); 1061 if (SS.isNotEmpty()) 1062 return buildNestedType(*this, SS, T, NameLoc); 1063 return ParsedType::make(T); 1064 } 1065 1066 if (FirstDecl->isCXXClassMember()) 1067 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1068 nullptr, S); 1069 1070 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1071 return BuildDeclarationNameExpr(SS, Result, ADL); 1072 } 1073 1074 // Determines the context to return to after temporarily entering a 1075 // context. This depends in an unnecessarily complicated way on the 1076 // exact ordering of callbacks from the parser. 1077 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1078 1079 // Functions defined inline within classes aren't parsed until we've 1080 // finished parsing the top-level class, so the top-level class is 1081 // the context we'll need to return to. 1082 // A Lambda call operator whose parent is a class must not be treated 1083 // as an inline member function. A Lambda can be used legally 1084 // either as an in-class member initializer or a default argument. These 1085 // are parsed once the class has been marked complete and so the containing 1086 // context would be the nested class (when the lambda is defined in one); 1087 // If the class is not complete, then the lambda is being used in an 1088 // ill-formed fashion (such as to specify the width of a bit-field, or 1089 // in an array-bound) - in which case we still want to return the 1090 // lexically containing DC (which could be a nested class). 1091 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1092 DC = DC->getLexicalParent(); 1093 1094 // A function not defined within a class will always return to its 1095 // lexical context. 1096 if (!isa<CXXRecordDecl>(DC)) 1097 return DC; 1098 1099 // A C++ inline method/friend is parsed *after* the topmost class 1100 // it was declared in is fully parsed ("complete"); the topmost 1101 // class is the context we need to return to. 1102 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1103 DC = RD; 1104 1105 // Return the declaration context of the topmost class the inline method is 1106 // declared in. 1107 return DC; 1108 } 1109 1110 return DC->getLexicalParent(); 1111 } 1112 1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1114 assert(getContainingDC(DC) == CurContext && 1115 "The next DeclContext should be lexically contained in the current one."); 1116 CurContext = DC; 1117 S->setEntity(DC); 1118 } 1119 1120 void Sema::PopDeclContext() { 1121 assert(CurContext && "DeclContext imbalance!"); 1122 1123 CurContext = getContainingDC(CurContext); 1124 assert(CurContext && "Popped translation unit!"); 1125 } 1126 1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1128 Decl *D) { 1129 // Unlike PushDeclContext, the context to which we return is not necessarily 1130 // the containing DC of TD, because the new context will be some pre-existing 1131 // TagDecl definition instead of a fresh one. 1132 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1133 CurContext = cast<TagDecl>(D)->getDefinition(); 1134 assert(CurContext && "skipping definition of undefined tag"); 1135 // Start lookups from the parent of the current context; we don't want to look 1136 // into the pre-existing complete definition. 1137 S->setEntity(CurContext->getLookupParent()); 1138 return Result; 1139 } 1140 1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1142 CurContext = static_cast<decltype(CurContext)>(Context); 1143 } 1144 1145 /// EnterDeclaratorContext - Used when we must lookup names in the context 1146 /// of a declarator's nested name specifier. 1147 /// 1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1149 // C++0x [basic.lookup.unqual]p13: 1150 // A name used in the definition of a static data member of class 1151 // X (after the qualified-id of the static member) is looked up as 1152 // if the name was used in a member function of X. 1153 // C++0x [basic.lookup.unqual]p14: 1154 // If a variable member of a namespace is defined outside of the 1155 // scope of its namespace then any name used in the definition of 1156 // the variable member (after the declarator-id) is looked up as 1157 // if the definition of the variable member occurred in its 1158 // namespace. 1159 // Both of these imply that we should push a scope whose context 1160 // is the semantic context of the declaration. We can't use 1161 // PushDeclContext here because that context is not necessarily 1162 // lexically contained in the current context. Fortunately, 1163 // the containing scope should have the appropriate information. 1164 1165 assert(!S->getEntity() && "scope already has entity"); 1166 1167 #ifndef NDEBUG 1168 Scope *Ancestor = S->getParent(); 1169 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1170 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1171 #endif 1172 1173 CurContext = DC; 1174 S->setEntity(DC); 1175 } 1176 1177 void Sema::ExitDeclaratorContext(Scope *S) { 1178 assert(S->getEntity() == CurContext && "Context imbalance!"); 1179 1180 // Switch back to the lexical context. The safety of this is 1181 // enforced by an assert in EnterDeclaratorContext. 1182 Scope *Ancestor = S->getParent(); 1183 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1184 CurContext = Ancestor->getEntity(); 1185 1186 // We don't need to do anything with the scope, which is going to 1187 // disappear. 1188 } 1189 1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1191 // We assume that the caller has already called 1192 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1193 FunctionDecl *FD = D->getAsFunction(); 1194 if (!FD) 1195 return; 1196 1197 // Same implementation as PushDeclContext, but enters the context 1198 // from the lexical parent, rather than the top-level class. 1199 assert(CurContext == FD->getLexicalParent() && 1200 "The next DeclContext should be lexically contained in the current one."); 1201 CurContext = FD; 1202 S->setEntity(CurContext); 1203 1204 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1205 ParmVarDecl *Param = FD->getParamDecl(P); 1206 // If the parameter has an identifier, then add it to the scope 1207 if (Param->getIdentifier()) { 1208 S->AddDecl(Param); 1209 IdResolver.AddDecl(Param); 1210 } 1211 } 1212 } 1213 1214 void Sema::ActOnExitFunctionContext() { 1215 // Same implementation as PopDeclContext, but returns to the lexical parent, 1216 // rather than the top-level class. 1217 assert(CurContext && "DeclContext imbalance!"); 1218 CurContext = CurContext->getLexicalParent(); 1219 assert(CurContext && "Popped translation unit!"); 1220 } 1221 1222 /// \brief Determine whether we allow overloading of the function 1223 /// PrevDecl with another declaration. 1224 /// 1225 /// This routine determines whether overloading is possible, not 1226 /// whether some new function is actually an overload. It will return 1227 /// true in C++ (where we can always provide overloads) or, as an 1228 /// extension, in C when the previous function is already an 1229 /// overloaded function declaration or has the "overloadable" 1230 /// attribute. 1231 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1232 ASTContext &Context) { 1233 if (Context.getLangOpts().CPlusPlus) 1234 return true; 1235 1236 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1237 return true; 1238 1239 return (Previous.getResultKind() == LookupResult::Found 1240 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1241 } 1242 1243 /// Add this decl to the scope shadowed decl chains. 1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1245 // Move up the scope chain until we find the nearest enclosing 1246 // non-transparent context. The declaration will be introduced into this 1247 // scope. 1248 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1249 S = S->getParent(); 1250 1251 // Add scoped declarations into their context, so that they can be 1252 // found later. Declarations without a context won't be inserted 1253 // into any context. 1254 if (AddToContext) 1255 CurContext->addDecl(D); 1256 1257 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1258 // are function-local declarations. 1259 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1260 !D->getDeclContext()->getRedeclContext()->Equals( 1261 D->getLexicalDeclContext()->getRedeclContext()) && 1262 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1263 return; 1264 1265 // Template instantiations should also not be pushed into scope. 1266 if (isa<FunctionDecl>(D) && 1267 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1268 return; 1269 1270 // If this replaces anything in the current scope, 1271 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1272 IEnd = IdResolver.end(); 1273 for (; I != IEnd; ++I) { 1274 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1275 S->RemoveDecl(*I); 1276 IdResolver.RemoveDecl(*I); 1277 1278 // Should only need to replace one decl. 1279 break; 1280 } 1281 } 1282 1283 S->AddDecl(D); 1284 1285 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1286 // Implicitly-generated labels may end up getting generated in an order that 1287 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1288 // the label at the appropriate place in the identifier chain. 1289 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1290 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1291 if (IDC == CurContext) { 1292 if (!S->isDeclScope(*I)) 1293 continue; 1294 } else if (IDC->Encloses(CurContext)) 1295 break; 1296 } 1297 1298 IdResolver.InsertDeclAfter(I, D); 1299 } else { 1300 IdResolver.AddDecl(D); 1301 } 1302 } 1303 1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1305 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1306 TUScope->AddDecl(D); 1307 } 1308 1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1310 bool AllowInlineNamespace) { 1311 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1312 } 1313 1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1315 DeclContext *TargetDC = DC->getPrimaryContext(); 1316 do { 1317 if (DeclContext *ScopeDC = S->getEntity()) 1318 if (ScopeDC->getPrimaryContext() == TargetDC) 1319 return S; 1320 } while ((S = S->getParent())); 1321 1322 return nullptr; 1323 } 1324 1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1326 DeclContext*, 1327 ASTContext&); 1328 1329 /// Filters out lookup results that don't fall within the given scope 1330 /// as determined by isDeclInScope. 1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1332 bool ConsiderLinkage, 1333 bool AllowInlineNamespace) { 1334 LookupResult::Filter F = R.makeFilter(); 1335 while (F.hasNext()) { 1336 NamedDecl *D = F.next(); 1337 1338 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1339 continue; 1340 1341 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1342 continue; 1343 1344 F.erase(); 1345 } 1346 1347 F.done(); 1348 } 1349 1350 static bool isUsingDecl(NamedDecl *D) { 1351 return isa<UsingShadowDecl>(D) || 1352 isa<UnresolvedUsingTypenameDecl>(D) || 1353 isa<UnresolvedUsingValueDecl>(D); 1354 } 1355 1356 /// Removes using shadow declarations from the lookup results. 1357 static void RemoveUsingDecls(LookupResult &R) { 1358 LookupResult::Filter F = R.makeFilter(); 1359 while (F.hasNext()) 1360 if (isUsingDecl(F.next())) 1361 F.erase(); 1362 1363 F.done(); 1364 } 1365 1366 /// \brief Check for this common pattern: 1367 /// @code 1368 /// class S { 1369 /// S(const S&); // DO NOT IMPLEMENT 1370 /// void operator=(const S&); // DO NOT IMPLEMENT 1371 /// }; 1372 /// @endcode 1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1374 // FIXME: Should check for private access too but access is set after we get 1375 // the decl here. 1376 if (D->doesThisDeclarationHaveABody()) 1377 return false; 1378 1379 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1380 return CD->isCopyConstructor(); 1381 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1382 return Method->isCopyAssignmentOperator(); 1383 return false; 1384 } 1385 1386 // We need this to handle 1387 // 1388 // typedef struct { 1389 // void *foo() { return 0; } 1390 // } A; 1391 // 1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1393 // for example. If 'A', foo will have external linkage. If we have '*A', 1394 // foo will have no linkage. Since we can't know until we get to the end 1395 // of the typedef, this function finds out if D might have non-external linkage. 1396 // Callers should verify at the end of the TU if it D has external linkage or 1397 // not. 1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1399 const DeclContext *DC = D->getDeclContext(); 1400 while (!DC->isTranslationUnit()) { 1401 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1402 if (!RD->hasNameForLinkage()) 1403 return true; 1404 } 1405 DC = DC->getParent(); 1406 } 1407 1408 return !D->isExternallyVisible(); 1409 } 1410 1411 // FIXME: This needs to be refactored; some other isInMainFile users want 1412 // these semantics. 1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1414 if (S.TUKind != TU_Complete) 1415 return false; 1416 return S.SourceMgr.isInMainFile(Loc); 1417 } 1418 1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1420 assert(D); 1421 1422 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1423 return false; 1424 1425 // Ignore all entities declared within templates, and out-of-line definitions 1426 // of members of class templates. 1427 if (D->getDeclContext()->isDependentContext() || 1428 D->getLexicalDeclContext()->isDependentContext()) 1429 return false; 1430 1431 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1432 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1433 return false; 1434 1435 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1436 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1437 return false; 1438 } else { 1439 // 'static inline' functions are defined in headers; don't warn. 1440 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1441 return false; 1442 } 1443 1444 if (FD->doesThisDeclarationHaveABody() && 1445 Context.DeclMustBeEmitted(FD)) 1446 return false; 1447 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1448 // Constants and utility variables are defined in headers with internal 1449 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1450 // like "inline".) 1451 if (!isMainFileLoc(*this, VD->getLocation())) 1452 return false; 1453 1454 if (Context.DeclMustBeEmitted(VD)) 1455 return false; 1456 1457 if (VD->isStaticDataMember() && 1458 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1459 return false; 1460 } else { 1461 return false; 1462 } 1463 1464 // Only warn for unused decls internal to the translation unit. 1465 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1466 // for inline functions defined in the main source file, for instance. 1467 return mightHaveNonExternalLinkage(D); 1468 } 1469 1470 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1471 if (!D) 1472 return; 1473 1474 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1475 const FunctionDecl *First = FD->getFirstDecl(); 1476 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1477 return; // First should already be in the vector. 1478 } 1479 1480 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1481 const VarDecl *First = VD->getFirstDecl(); 1482 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1483 return; // First should already be in the vector. 1484 } 1485 1486 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1487 UnusedFileScopedDecls.push_back(D); 1488 } 1489 1490 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1491 if (D->isInvalidDecl()) 1492 return false; 1493 1494 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1495 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1496 return false; 1497 1498 if (isa<LabelDecl>(D)) 1499 return true; 1500 1501 // Except for labels, we only care about unused decls that are local to 1502 // functions. 1503 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1504 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1505 // For dependent types, the diagnostic is deferred. 1506 WithinFunction = 1507 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1508 if (!WithinFunction) 1509 return false; 1510 1511 if (isa<TypedefNameDecl>(D)) 1512 return true; 1513 1514 // White-list anything that isn't a local variable. 1515 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1516 return false; 1517 1518 // Types of valid local variables should be complete, so this should succeed. 1519 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1520 1521 // White-list anything with an __attribute__((unused)) type. 1522 QualType Ty = VD->getType(); 1523 1524 // Only look at the outermost level of typedef. 1525 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1526 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1527 return false; 1528 } 1529 1530 // If we failed to complete the type for some reason, or if the type is 1531 // dependent, don't diagnose the variable. 1532 if (Ty->isIncompleteType() || Ty->isDependentType()) 1533 return false; 1534 1535 if (const TagType *TT = Ty->getAs<TagType>()) { 1536 const TagDecl *Tag = TT->getDecl(); 1537 if (Tag->hasAttr<UnusedAttr>()) 1538 return false; 1539 1540 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1541 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1542 return false; 1543 1544 if (const Expr *Init = VD->getInit()) { 1545 if (const ExprWithCleanups *Cleanups = 1546 dyn_cast<ExprWithCleanups>(Init)) 1547 Init = Cleanups->getSubExpr(); 1548 const CXXConstructExpr *Construct = 1549 dyn_cast<CXXConstructExpr>(Init); 1550 if (Construct && !Construct->isElidable()) { 1551 CXXConstructorDecl *CD = Construct->getConstructor(); 1552 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1553 return false; 1554 } 1555 } 1556 } 1557 } 1558 1559 // TODO: __attribute__((unused)) templates? 1560 } 1561 1562 return true; 1563 } 1564 1565 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1566 FixItHint &Hint) { 1567 if (isa<LabelDecl>(D)) { 1568 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1569 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1570 if (AfterColon.isInvalid()) 1571 return; 1572 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1573 getCharRange(D->getLocStart(), AfterColon)); 1574 } 1575 } 1576 1577 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1578 if (D->getTypeForDecl()->isDependentType()) 1579 return; 1580 1581 for (auto *TmpD : D->decls()) { 1582 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1583 DiagnoseUnusedDecl(T); 1584 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1585 DiagnoseUnusedNestedTypedefs(R); 1586 } 1587 } 1588 1589 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1590 /// unless they are marked attr(unused). 1591 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1592 if (!ShouldDiagnoseUnusedDecl(D)) 1593 return; 1594 1595 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1596 // typedefs can be referenced later on, so the diagnostics are emitted 1597 // at end-of-translation-unit. 1598 UnusedLocalTypedefNameCandidates.insert(TD); 1599 return; 1600 } 1601 1602 FixItHint Hint; 1603 GenerateFixForUnusedDecl(D, Context, Hint); 1604 1605 unsigned DiagID; 1606 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1607 DiagID = diag::warn_unused_exception_param; 1608 else if (isa<LabelDecl>(D)) 1609 DiagID = diag::warn_unused_label; 1610 else 1611 DiagID = diag::warn_unused_variable; 1612 1613 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1614 } 1615 1616 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1617 // Verify that we have no forward references left. If so, there was a goto 1618 // or address of a label taken, but no definition of it. Label fwd 1619 // definitions are indicated with a null substmt which is also not a resolved 1620 // MS inline assembly label name. 1621 bool Diagnose = false; 1622 if (L->isMSAsmLabel()) 1623 Diagnose = !L->isResolvedMSAsmLabel(); 1624 else 1625 Diagnose = L->getStmt() == nullptr; 1626 if (Diagnose) 1627 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1628 } 1629 1630 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1631 S->mergeNRVOIntoParent(); 1632 1633 if (S->decl_empty()) return; 1634 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1635 "Scope shouldn't contain decls!"); 1636 1637 for (auto *TmpD : S->decls()) { 1638 assert(TmpD && "This decl didn't get pushed??"); 1639 1640 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1641 NamedDecl *D = cast<NamedDecl>(TmpD); 1642 1643 if (!D->getDeclName()) continue; 1644 1645 // Diagnose unused variables in this scope. 1646 if (!S->hasUnrecoverableErrorOccurred()) { 1647 DiagnoseUnusedDecl(D); 1648 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1649 DiagnoseUnusedNestedTypedefs(RD); 1650 } 1651 1652 // If this was a forward reference to a label, verify it was defined. 1653 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1654 CheckPoppedLabel(LD, *this); 1655 1656 // Remove this name from our lexical scope, and warn on it if we haven't 1657 // already. 1658 IdResolver.RemoveDecl(D); 1659 auto ShadowI = ShadowingDecls.find(D); 1660 if (ShadowI != ShadowingDecls.end()) { 1661 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1662 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1663 << D << FD << FD->getParent(); 1664 Diag(FD->getLocation(), diag::note_previous_declaration); 1665 } 1666 ShadowingDecls.erase(ShadowI); 1667 } 1668 } 1669 } 1670 1671 /// \brief Look for an Objective-C class in the translation unit. 1672 /// 1673 /// \param Id The name of the Objective-C class we're looking for. If 1674 /// typo-correction fixes this name, the Id will be updated 1675 /// to the fixed name. 1676 /// 1677 /// \param IdLoc The location of the name in the translation unit. 1678 /// 1679 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1680 /// if there is no class with the given name. 1681 /// 1682 /// \returns The declaration of the named Objective-C class, or NULL if the 1683 /// class could not be found. 1684 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1685 SourceLocation IdLoc, 1686 bool DoTypoCorrection) { 1687 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1688 // creation from this context. 1689 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1690 1691 if (!IDecl && DoTypoCorrection) { 1692 // Perform typo correction at the given location, but only if we 1693 // find an Objective-C class name. 1694 if (TypoCorrection C = CorrectTypo( 1695 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1696 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1697 CTK_ErrorRecovery)) { 1698 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1699 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1700 Id = IDecl->getIdentifier(); 1701 } 1702 } 1703 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1704 // This routine must always return a class definition, if any. 1705 if (Def && Def->getDefinition()) 1706 Def = Def->getDefinition(); 1707 return Def; 1708 } 1709 1710 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1711 /// from S, where a non-field would be declared. This routine copes 1712 /// with the difference between C and C++ scoping rules in structs and 1713 /// unions. For example, the following code is well-formed in C but 1714 /// ill-formed in C++: 1715 /// @code 1716 /// struct S6 { 1717 /// enum { BAR } e; 1718 /// }; 1719 /// 1720 /// void test_S6() { 1721 /// struct S6 a; 1722 /// a.e = BAR; 1723 /// } 1724 /// @endcode 1725 /// For the declaration of BAR, this routine will return a different 1726 /// scope. The scope S will be the scope of the unnamed enumeration 1727 /// within S6. In C++, this routine will return the scope associated 1728 /// with S6, because the enumeration's scope is a transparent 1729 /// context but structures can contain non-field names. In C, this 1730 /// routine will return the translation unit scope, since the 1731 /// enumeration's scope is a transparent context and structures cannot 1732 /// contain non-field names. 1733 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1734 while (((S->getFlags() & Scope::DeclScope) == 0) || 1735 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1736 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1737 S = S->getParent(); 1738 return S; 1739 } 1740 1741 /// \brief Looks up the declaration of "struct objc_super" and 1742 /// saves it for later use in building builtin declaration of 1743 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1744 /// pre-existing declaration exists no action takes place. 1745 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1746 IdentifierInfo *II) { 1747 if (!II->isStr("objc_msgSendSuper")) 1748 return; 1749 ASTContext &Context = ThisSema.Context; 1750 1751 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1752 SourceLocation(), Sema::LookupTagName); 1753 ThisSema.LookupName(Result, S); 1754 if (Result.getResultKind() == LookupResult::Found) 1755 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1756 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1757 } 1758 1759 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1760 switch (Error) { 1761 case ASTContext::GE_None: 1762 return ""; 1763 case ASTContext::GE_Missing_stdio: 1764 return "stdio.h"; 1765 case ASTContext::GE_Missing_setjmp: 1766 return "setjmp.h"; 1767 case ASTContext::GE_Missing_ucontext: 1768 return "ucontext.h"; 1769 } 1770 llvm_unreachable("unhandled error kind"); 1771 } 1772 1773 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1774 /// file scope. lazily create a decl for it. ForRedeclaration is true 1775 /// if we're creating this built-in in anticipation of redeclaring the 1776 /// built-in. 1777 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1778 Scope *S, bool ForRedeclaration, 1779 SourceLocation Loc) { 1780 LookupPredefedObjCSuperType(*this, S, II); 1781 1782 ASTContext::GetBuiltinTypeError Error; 1783 QualType R = Context.GetBuiltinType(ID, Error); 1784 if (Error) { 1785 if (ForRedeclaration) 1786 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1787 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1788 return nullptr; 1789 } 1790 1791 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1792 Diag(Loc, diag::ext_implicit_lib_function_decl) 1793 << Context.BuiltinInfo.getName(ID) << R; 1794 if (Context.BuiltinInfo.getHeaderName(ID) && 1795 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1796 Diag(Loc, diag::note_include_header_or_declare) 1797 << Context.BuiltinInfo.getHeaderName(ID) 1798 << Context.BuiltinInfo.getName(ID); 1799 } 1800 1801 if (R.isNull()) 1802 return nullptr; 1803 1804 DeclContext *Parent = Context.getTranslationUnitDecl(); 1805 if (getLangOpts().CPlusPlus) { 1806 LinkageSpecDecl *CLinkageDecl = 1807 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1808 LinkageSpecDecl::lang_c, false); 1809 CLinkageDecl->setImplicit(); 1810 Parent->addDecl(CLinkageDecl); 1811 Parent = CLinkageDecl; 1812 } 1813 1814 FunctionDecl *New = FunctionDecl::Create(Context, 1815 Parent, 1816 Loc, Loc, II, R, /*TInfo=*/nullptr, 1817 SC_Extern, 1818 false, 1819 R->isFunctionProtoType()); 1820 New->setImplicit(); 1821 1822 // Create Decl objects for each parameter, adding them to the 1823 // FunctionDecl. 1824 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1825 SmallVector<ParmVarDecl*, 16> Params; 1826 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1827 ParmVarDecl *parm = 1828 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1829 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1830 SC_None, nullptr); 1831 parm->setScopeInfo(0, i); 1832 Params.push_back(parm); 1833 } 1834 New->setParams(Params); 1835 } 1836 1837 AddKnownFunctionAttributes(New); 1838 RegisterLocallyScopedExternCDecl(New, S); 1839 1840 // TUScope is the translation-unit scope to insert this function into. 1841 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1842 // relate Scopes to DeclContexts, and probably eliminate CurContext 1843 // entirely, but we're not there yet. 1844 DeclContext *SavedContext = CurContext; 1845 CurContext = Parent; 1846 PushOnScopeChains(New, TUScope); 1847 CurContext = SavedContext; 1848 return New; 1849 } 1850 1851 /// Typedef declarations don't have linkage, but they still denote the same 1852 /// entity if their types are the same. 1853 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1854 /// isSameEntity. 1855 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1856 TypedefNameDecl *Decl, 1857 LookupResult &Previous) { 1858 // This is only interesting when modules are enabled. 1859 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1860 return; 1861 1862 // Empty sets are uninteresting. 1863 if (Previous.empty()) 1864 return; 1865 1866 LookupResult::Filter Filter = Previous.makeFilter(); 1867 while (Filter.hasNext()) { 1868 NamedDecl *Old = Filter.next(); 1869 1870 // Non-hidden declarations are never ignored. 1871 if (S.isVisible(Old)) 1872 continue; 1873 1874 // Declarations of the same entity are not ignored, even if they have 1875 // different linkages. 1876 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1877 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1878 Decl->getUnderlyingType())) 1879 continue; 1880 1881 // If both declarations give a tag declaration a typedef name for linkage 1882 // purposes, then they declare the same entity. 1883 if (S.getLangOpts().CPlusPlus && 1884 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1885 Decl->getAnonDeclWithTypedefName()) 1886 continue; 1887 } 1888 1889 Filter.erase(); 1890 } 1891 1892 Filter.done(); 1893 } 1894 1895 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1896 QualType OldType; 1897 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1898 OldType = OldTypedef->getUnderlyingType(); 1899 else 1900 OldType = Context.getTypeDeclType(Old); 1901 QualType NewType = New->getUnderlyingType(); 1902 1903 if (NewType->isVariablyModifiedType()) { 1904 // Must not redefine a typedef with a variably-modified type. 1905 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1906 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1907 << Kind << NewType; 1908 if (Old->getLocation().isValid()) 1909 Diag(Old->getLocation(), diag::note_previous_definition); 1910 New->setInvalidDecl(); 1911 return true; 1912 } 1913 1914 if (OldType != NewType && 1915 !OldType->isDependentType() && 1916 !NewType->isDependentType() && 1917 !Context.hasSameType(OldType, NewType)) { 1918 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1919 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1920 << Kind << NewType << OldType; 1921 if (Old->getLocation().isValid()) 1922 Diag(Old->getLocation(), diag::note_previous_definition); 1923 New->setInvalidDecl(); 1924 return true; 1925 } 1926 return false; 1927 } 1928 1929 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1930 /// same name and scope as a previous declaration 'Old'. Figure out 1931 /// how to resolve this situation, merging decls or emitting 1932 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1933 /// 1934 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 1935 LookupResult &OldDecls) { 1936 // If the new decl is known invalid already, don't bother doing any 1937 // merging checks. 1938 if (New->isInvalidDecl()) return; 1939 1940 // Allow multiple definitions for ObjC built-in typedefs. 1941 // FIXME: Verify the underlying types are equivalent! 1942 if (getLangOpts().ObjC1) { 1943 const IdentifierInfo *TypeID = New->getIdentifier(); 1944 switch (TypeID->getLength()) { 1945 default: break; 1946 case 2: 1947 { 1948 if (!TypeID->isStr("id")) 1949 break; 1950 QualType T = New->getUnderlyingType(); 1951 if (!T->isPointerType()) 1952 break; 1953 if (!T->isVoidPointerType()) { 1954 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1955 if (!PT->isStructureType()) 1956 break; 1957 } 1958 Context.setObjCIdRedefinitionType(T); 1959 // Install the built-in type for 'id', ignoring the current definition. 1960 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1961 return; 1962 } 1963 case 5: 1964 if (!TypeID->isStr("Class")) 1965 break; 1966 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1967 // Install the built-in type for 'Class', ignoring the current definition. 1968 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1969 return; 1970 case 3: 1971 if (!TypeID->isStr("SEL")) 1972 break; 1973 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1974 // Install the built-in type for 'SEL', ignoring the current definition. 1975 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1976 return; 1977 } 1978 // Fall through - the typedef name was not a builtin type. 1979 } 1980 1981 // Verify the old decl was also a type. 1982 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1983 if (!Old) { 1984 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1985 << New->getDeclName(); 1986 1987 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1988 if (OldD->getLocation().isValid()) 1989 Diag(OldD->getLocation(), diag::note_previous_definition); 1990 1991 return New->setInvalidDecl(); 1992 } 1993 1994 // If the old declaration is invalid, just give up here. 1995 if (Old->isInvalidDecl()) 1996 return New->setInvalidDecl(); 1997 1998 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1999 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2000 auto *NewTag = New->getAnonDeclWithTypedefName(); 2001 NamedDecl *Hidden = nullptr; 2002 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2003 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2004 !hasVisibleDefinition(OldTag, &Hidden)) { 2005 // There is a definition of this tag, but it is not visible. Use it 2006 // instead of our tag. 2007 New->setTypeForDecl(OldTD->getTypeForDecl()); 2008 if (OldTD->isModed()) 2009 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2010 OldTD->getUnderlyingType()); 2011 else 2012 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2013 2014 // Make the old tag definition visible. 2015 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 2016 2017 // If this was an unscoped enumeration, yank all of its enumerators 2018 // out of the scope. 2019 if (isa<EnumDecl>(NewTag)) { 2020 Scope *EnumScope = getNonFieldDeclScope(S); 2021 for (auto *D : NewTag->decls()) { 2022 auto *ED = cast<EnumConstantDecl>(D); 2023 assert(EnumScope->isDeclScope(ED)); 2024 EnumScope->RemoveDecl(ED); 2025 IdResolver.RemoveDecl(ED); 2026 ED->getLexicalDeclContext()->removeDecl(ED); 2027 } 2028 } 2029 } 2030 } 2031 2032 // If the typedef types are not identical, reject them in all languages and 2033 // with any extensions enabled. 2034 if (isIncompatibleTypedef(Old, New)) 2035 return; 2036 2037 // The types match. Link up the redeclaration chain and merge attributes if 2038 // the old declaration was a typedef. 2039 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2040 New->setPreviousDecl(Typedef); 2041 mergeDeclAttributes(New, Old); 2042 } 2043 2044 if (getLangOpts().MicrosoftExt) 2045 return; 2046 2047 if (getLangOpts().CPlusPlus) { 2048 // C++ [dcl.typedef]p2: 2049 // In a given non-class scope, a typedef specifier can be used to 2050 // redefine the name of any type declared in that scope to refer 2051 // to the type to which it already refers. 2052 if (!isa<CXXRecordDecl>(CurContext)) 2053 return; 2054 2055 // C++0x [dcl.typedef]p4: 2056 // In a given class scope, a typedef specifier can be used to redefine 2057 // any class-name declared in that scope that is not also a typedef-name 2058 // to refer to the type to which it already refers. 2059 // 2060 // This wording came in via DR424, which was a correction to the 2061 // wording in DR56, which accidentally banned code like: 2062 // 2063 // struct S { 2064 // typedef struct A { } A; 2065 // }; 2066 // 2067 // in the C++03 standard. We implement the C++0x semantics, which 2068 // allow the above but disallow 2069 // 2070 // struct S { 2071 // typedef int I; 2072 // typedef int I; 2073 // }; 2074 // 2075 // since that was the intent of DR56. 2076 if (!isa<TypedefNameDecl>(Old)) 2077 return; 2078 2079 Diag(New->getLocation(), diag::err_redefinition) 2080 << New->getDeclName(); 2081 Diag(Old->getLocation(), diag::note_previous_definition); 2082 return New->setInvalidDecl(); 2083 } 2084 2085 // Modules always permit redefinition of typedefs, as does C11. 2086 if (getLangOpts().Modules || getLangOpts().C11) 2087 return; 2088 2089 // If we have a redefinition of a typedef in C, emit a warning. This warning 2090 // is normally mapped to an error, but can be controlled with 2091 // -Wtypedef-redefinition. If either the original or the redefinition is 2092 // in a system header, don't emit this for compatibility with GCC. 2093 if (getDiagnostics().getSuppressSystemWarnings() && 2094 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2095 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2096 return; 2097 2098 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2099 << New->getDeclName(); 2100 Diag(Old->getLocation(), diag::note_previous_definition); 2101 } 2102 2103 /// DeclhasAttr - returns true if decl Declaration already has the target 2104 /// attribute. 2105 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2106 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2107 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2108 for (const auto *i : D->attrs()) 2109 if (i->getKind() == A->getKind()) { 2110 if (Ann) { 2111 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2112 return true; 2113 continue; 2114 } 2115 // FIXME: Don't hardcode this check 2116 if (OA && isa<OwnershipAttr>(i)) 2117 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2118 return true; 2119 } 2120 2121 return false; 2122 } 2123 2124 static bool isAttributeTargetADefinition(Decl *D) { 2125 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2126 return VD->isThisDeclarationADefinition(); 2127 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2128 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2129 return true; 2130 } 2131 2132 /// Merge alignment attributes from \p Old to \p New, taking into account the 2133 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2134 /// 2135 /// \return \c true if any attributes were added to \p New. 2136 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2137 // Look for alignas attributes on Old, and pick out whichever attribute 2138 // specifies the strictest alignment requirement. 2139 AlignedAttr *OldAlignasAttr = nullptr; 2140 AlignedAttr *OldStrictestAlignAttr = nullptr; 2141 unsigned OldAlign = 0; 2142 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2143 // FIXME: We have no way of representing inherited dependent alignments 2144 // in a case like: 2145 // template<int A, int B> struct alignas(A) X; 2146 // template<int A, int B> struct alignas(B) X {}; 2147 // For now, we just ignore any alignas attributes which are not on the 2148 // definition in such a case. 2149 if (I->isAlignmentDependent()) 2150 return false; 2151 2152 if (I->isAlignas()) 2153 OldAlignasAttr = I; 2154 2155 unsigned Align = I->getAlignment(S.Context); 2156 if (Align > OldAlign) { 2157 OldAlign = Align; 2158 OldStrictestAlignAttr = I; 2159 } 2160 } 2161 2162 // Look for alignas attributes on New. 2163 AlignedAttr *NewAlignasAttr = nullptr; 2164 unsigned NewAlign = 0; 2165 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2166 if (I->isAlignmentDependent()) 2167 return false; 2168 2169 if (I->isAlignas()) 2170 NewAlignasAttr = I; 2171 2172 unsigned Align = I->getAlignment(S.Context); 2173 if (Align > NewAlign) 2174 NewAlign = Align; 2175 } 2176 2177 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2178 // Both declarations have 'alignas' attributes. We require them to match. 2179 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2180 // fall short. (If two declarations both have alignas, they must both match 2181 // every definition, and so must match each other if there is a definition.) 2182 2183 // If either declaration only contains 'alignas(0)' specifiers, then it 2184 // specifies the natural alignment for the type. 2185 if (OldAlign == 0 || NewAlign == 0) { 2186 QualType Ty; 2187 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2188 Ty = VD->getType(); 2189 else 2190 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2191 2192 if (OldAlign == 0) 2193 OldAlign = S.Context.getTypeAlign(Ty); 2194 if (NewAlign == 0) 2195 NewAlign = S.Context.getTypeAlign(Ty); 2196 } 2197 2198 if (OldAlign != NewAlign) { 2199 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2200 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2201 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2202 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2203 } 2204 } 2205 2206 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2207 // C++11 [dcl.align]p6: 2208 // if any declaration of an entity has an alignment-specifier, 2209 // every defining declaration of that entity shall specify an 2210 // equivalent alignment. 2211 // C11 6.7.5/7: 2212 // If the definition of an object does not have an alignment 2213 // specifier, any other declaration of that object shall also 2214 // have no alignment specifier. 2215 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2216 << OldAlignasAttr; 2217 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2218 << OldAlignasAttr; 2219 } 2220 2221 bool AnyAdded = false; 2222 2223 // Ensure we have an attribute representing the strictest alignment. 2224 if (OldAlign > NewAlign) { 2225 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2226 Clone->setInherited(true); 2227 New->addAttr(Clone); 2228 AnyAdded = true; 2229 } 2230 2231 // Ensure we have an alignas attribute if the old declaration had one. 2232 if (OldAlignasAttr && !NewAlignasAttr && 2233 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2234 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2235 Clone->setInherited(true); 2236 New->addAttr(Clone); 2237 AnyAdded = true; 2238 } 2239 2240 return AnyAdded; 2241 } 2242 2243 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2244 const InheritableAttr *Attr, 2245 Sema::AvailabilityMergeKind AMK) { 2246 InheritableAttr *NewAttr = nullptr; 2247 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2248 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2249 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2250 AA->isImplicit(), AA->getIntroduced(), 2251 AA->getDeprecated(), 2252 AA->getObsoleted(), AA->getUnavailable(), 2253 AA->getMessage(), AA->getStrict(), 2254 AA->getReplacement(), AMK, 2255 AttrSpellingListIndex); 2256 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2257 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2258 AttrSpellingListIndex); 2259 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2260 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2261 AttrSpellingListIndex); 2262 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2263 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2264 AttrSpellingListIndex); 2265 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2266 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2267 AttrSpellingListIndex); 2268 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2269 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2270 FA->getFormatIdx(), FA->getFirstArg(), 2271 AttrSpellingListIndex); 2272 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2273 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2274 AttrSpellingListIndex); 2275 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2276 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2277 AttrSpellingListIndex, 2278 IA->getSemanticSpelling()); 2279 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2280 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2281 &S.Context.Idents.get(AA->getSpelling()), 2282 AttrSpellingListIndex); 2283 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2284 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2285 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2286 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2287 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2288 NewAttr = S.mergeInternalLinkageAttr( 2289 D, InternalLinkageA->getRange(), 2290 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2291 AttrSpellingListIndex); 2292 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2293 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2294 &S.Context.Idents.get(CommonA->getSpelling()), 2295 AttrSpellingListIndex); 2296 else if (isa<AlignedAttr>(Attr)) 2297 // AlignedAttrs are handled separately, because we need to handle all 2298 // such attributes on a declaration at the same time. 2299 NewAttr = nullptr; 2300 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2301 (AMK == Sema::AMK_Override || 2302 AMK == Sema::AMK_ProtocolImplementation)) 2303 NewAttr = nullptr; 2304 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2305 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2306 2307 if (NewAttr) { 2308 NewAttr->setInherited(true); 2309 D->addAttr(NewAttr); 2310 if (isa<MSInheritanceAttr>(NewAttr)) 2311 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2312 return true; 2313 } 2314 2315 return false; 2316 } 2317 2318 static const Decl *getDefinition(const Decl *D) { 2319 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2320 return TD->getDefinition(); 2321 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2322 const VarDecl *Def = VD->getDefinition(); 2323 if (Def) 2324 return Def; 2325 return VD->getActingDefinition(); 2326 } 2327 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2328 const FunctionDecl* Def; 2329 if (FD->isDefined(Def)) 2330 return Def; 2331 } 2332 return nullptr; 2333 } 2334 2335 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2336 for (const auto *Attribute : D->attrs()) 2337 if (Attribute->getKind() == Kind) 2338 return true; 2339 return false; 2340 } 2341 2342 /// checkNewAttributesAfterDef - If we already have a definition, check that 2343 /// there are no new attributes in this declaration. 2344 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2345 if (!New->hasAttrs()) 2346 return; 2347 2348 const Decl *Def = getDefinition(Old); 2349 if (!Def || Def == New) 2350 return; 2351 2352 AttrVec &NewAttributes = New->getAttrs(); 2353 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2354 const Attr *NewAttribute = NewAttributes[I]; 2355 2356 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2357 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2358 Sema::SkipBodyInfo SkipBody; 2359 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2360 2361 // If we're skipping this definition, drop the "alias" attribute. 2362 if (SkipBody.ShouldSkip) { 2363 NewAttributes.erase(NewAttributes.begin() + I); 2364 --E; 2365 continue; 2366 } 2367 } else { 2368 VarDecl *VD = cast<VarDecl>(New); 2369 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2370 VarDecl::TentativeDefinition 2371 ? diag::err_alias_after_tentative 2372 : diag::err_redefinition; 2373 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2374 S.Diag(Def->getLocation(), diag::note_previous_definition); 2375 VD->setInvalidDecl(); 2376 } 2377 ++I; 2378 continue; 2379 } 2380 2381 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2382 // Tentative definitions are only interesting for the alias check above. 2383 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2384 ++I; 2385 continue; 2386 } 2387 } 2388 2389 if (hasAttribute(Def, NewAttribute->getKind())) { 2390 ++I; 2391 continue; // regular attr merging will take care of validating this. 2392 } 2393 2394 if (isa<C11NoReturnAttr>(NewAttribute)) { 2395 // C's _Noreturn is allowed to be added to a function after it is defined. 2396 ++I; 2397 continue; 2398 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2399 if (AA->isAlignas()) { 2400 // C++11 [dcl.align]p6: 2401 // if any declaration of an entity has an alignment-specifier, 2402 // every defining declaration of that entity shall specify an 2403 // equivalent alignment. 2404 // C11 6.7.5/7: 2405 // If the definition of an object does not have an alignment 2406 // specifier, any other declaration of that object shall also 2407 // have no alignment specifier. 2408 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2409 << AA; 2410 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2411 << AA; 2412 NewAttributes.erase(NewAttributes.begin() + I); 2413 --E; 2414 continue; 2415 } 2416 } 2417 2418 S.Diag(NewAttribute->getLocation(), 2419 diag::warn_attribute_precede_definition); 2420 S.Diag(Def->getLocation(), diag::note_previous_definition); 2421 NewAttributes.erase(NewAttributes.begin() + I); 2422 --E; 2423 } 2424 } 2425 2426 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2427 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2428 AvailabilityMergeKind AMK) { 2429 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2430 UsedAttr *NewAttr = OldAttr->clone(Context); 2431 NewAttr->setInherited(true); 2432 New->addAttr(NewAttr); 2433 } 2434 2435 if (!Old->hasAttrs() && !New->hasAttrs()) 2436 return; 2437 2438 // Attributes declared post-definition are currently ignored. 2439 checkNewAttributesAfterDef(*this, New, Old); 2440 2441 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2442 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2443 if (OldA->getLabel() != NewA->getLabel()) { 2444 // This redeclaration changes __asm__ label. 2445 Diag(New->getLocation(), diag::err_different_asm_label); 2446 Diag(OldA->getLocation(), diag::note_previous_declaration); 2447 } 2448 } else if (Old->isUsed()) { 2449 // This redeclaration adds an __asm__ label to a declaration that has 2450 // already been ODR-used. 2451 Diag(New->getLocation(), diag::err_late_asm_label_name) 2452 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2453 } 2454 } 2455 2456 // Re-declaration cannot add abi_tag's. 2457 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2458 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2459 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2460 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2461 NewTag) == OldAbiTagAttr->tags_end()) { 2462 Diag(NewAbiTagAttr->getLocation(), 2463 diag::err_new_abi_tag_on_redeclaration) 2464 << NewTag; 2465 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2466 } 2467 } 2468 } else { 2469 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2470 Diag(Old->getLocation(), diag::note_previous_declaration); 2471 } 2472 } 2473 2474 if (!Old->hasAttrs()) 2475 return; 2476 2477 bool foundAny = New->hasAttrs(); 2478 2479 // Ensure that any moving of objects within the allocated map is done before 2480 // we process them. 2481 if (!foundAny) New->setAttrs(AttrVec()); 2482 2483 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2484 // Ignore deprecated/unavailable/availability attributes if requested. 2485 AvailabilityMergeKind LocalAMK = AMK_None; 2486 if (isa<DeprecatedAttr>(I) || 2487 isa<UnavailableAttr>(I) || 2488 isa<AvailabilityAttr>(I)) { 2489 switch (AMK) { 2490 case AMK_None: 2491 continue; 2492 2493 case AMK_Redeclaration: 2494 case AMK_Override: 2495 case AMK_ProtocolImplementation: 2496 LocalAMK = AMK; 2497 break; 2498 } 2499 } 2500 2501 // Already handled. 2502 if (isa<UsedAttr>(I)) 2503 continue; 2504 2505 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2506 foundAny = true; 2507 } 2508 2509 if (mergeAlignedAttrs(*this, New, Old)) 2510 foundAny = true; 2511 2512 if (!foundAny) New->dropAttrs(); 2513 } 2514 2515 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2516 /// to the new one. 2517 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2518 const ParmVarDecl *oldDecl, 2519 Sema &S) { 2520 // C++11 [dcl.attr.depend]p2: 2521 // The first declaration of a function shall specify the 2522 // carries_dependency attribute for its declarator-id if any declaration 2523 // of the function specifies the carries_dependency attribute. 2524 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2525 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2526 S.Diag(CDA->getLocation(), 2527 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2528 // Find the first declaration of the parameter. 2529 // FIXME: Should we build redeclaration chains for function parameters? 2530 const FunctionDecl *FirstFD = 2531 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2532 const ParmVarDecl *FirstVD = 2533 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2534 S.Diag(FirstVD->getLocation(), 2535 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2536 } 2537 2538 if (!oldDecl->hasAttrs()) 2539 return; 2540 2541 bool foundAny = newDecl->hasAttrs(); 2542 2543 // Ensure that any moving of objects within the allocated map is 2544 // done before we process them. 2545 if (!foundAny) newDecl->setAttrs(AttrVec()); 2546 2547 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2548 if (!DeclHasAttr(newDecl, I)) { 2549 InheritableAttr *newAttr = 2550 cast<InheritableParamAttr>(I->clone(S.Context)); 2551 newAttr->setInherited(true); 2552 newDecl->addAttr(newAttr); 2553 foundAny = true; 2554 } 2555 } 2556 2557 if (!foundAny) newDecl->dropAttrs(); 2558 } 2559 2560 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2561 const ParmVarDecl *OldParam, 2562 Sema &S) { 2563 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2564 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2565 if (*Oldnullability != *Newnullability) { 2566 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2567 << DiagNullabilityKind( 2568 *Newnullability, 2569 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2570 != 0)) 2571 << DiagNullabilityKind( 2572 *Oldnullability, 2573 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2574 != 0)); 2575 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2576 } 2577 } else { 2578 QualType NewT = NewParam->getType(); 2579 NewT = S.Context.getAttributedType( 2580 AttributedType::getNullabilityAttrKind(*Oldnullability), 2581 NewT, NewT); 2582 NewParam->setType(NewT); 2583 } 2584 } 2585 } 2586 2587 namespace { 2588 2589 /// Used in MergeFunctionDecl to keep track of function parameters in 2590 /// C. 2591 struct GNUCompatibleParamWarning { 2592 ParmVarDecl *OldParm; 2593 ParmVarDecl *NewParm; 2594 QualType PromotedType; 2595 }; 2596 2597 } // end anonymous namespace 2598 2599 /// getSpecialMember - get the special member enum for a method. 2600 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2601 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2602 if (Ctor->isDefaultConstructor()) 2603 return Sema::CXXDefaultConstructor; 2604 2605 if (Ctor->isCopyConstructor()) 2606 return Sema::CXXCopyConstructor; 2607 2608 if (Ctor->isMoveConstructor()) 2609 return Sema::CXXMoveConstructor; 2610 } else if (isa<CXXDestructorDecl>(MD)) { 2611 return Sema::CXXDestructor; 2612 } else if (MD->isCopyAssignmentOperator()) { 2613 return Sema::CXXCopyAssignment; 2614 } else if (MD->isMoveAssignmentOperator()) { 2615 return Sema::CXXMoveAssignment; 2616 } 2617 2618 return Sema::CXXInvalid; 2619 } 2620 2621 // Determine whether the previous declaration was a definition, implicit 2622 // declaration, or a declaration. 2623 template <typename T> 2624 static std::pair<diag::kind, SourceLocation> 2625 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2626 diag::kind PrevDiag; 2627 SourceLocation OldLocation = Old->getLocation(); 2628 if (Old->isThisDeclarationADefinition()) 2629 PrevDiag = diag::note_previous_definition; 2630 else if (Old->isImplicit()) { 2631 PrevDiag = diag::note_previous_implicit_declaration; 2632 if (OldLocation.isInvalid()) 2633 OldLocation = New->getLocation(); 2634 } else 2635 PrevDiag = diag::note_previous_declaration; 2636 return std::make_pair(PrevDiag, OldLocation); 2637 } 2638 2639 /// canRedefineFunction - checks if a function can be redefined. Currently, 2640 /// only extern inline functions can be redefined, and even then only in 2641 /// GNU89 mode. 2642 static bool canRedefineFunction(const FunctionDecl *FD, 2643 const LangOptions& LangOpts) { 2644 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2645 !LangOpts.CPlusPlus && 2646 FD->isInlineSpecified() && 2647 FD->getStorageClass() == SC_Extern); 2648 } 2649 2650 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2651 const AttributedType *AT = T->getAs<AttributedType>(); 2652 while (AT && !AT->isCallingConv()) 2653 AT = AT->getModifiedType()->getAs<AttributedType>(); 2654 return AT; 2655 } 2656 2657 template <typename T> 2658 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2659 const DeclContext *DC = Old->getDeclContext(); 2660 if (DC->isRecord()) 2661 return false; 2662 2663 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2664 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2665 return true; 2666 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2667 return true; 2668 return false; 2669 } 2670 2671 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2672 static bool isExternC(VarTemplateDecl *) { return false; } 2673 2674 /// \brief Check whether a redeclaration of an entity introduced by a 2675 /// using-declaration is valid, given that we know it's not an overload 2676 /// (nor a hidden tag declaration). 2677 template<typename ExpectedDecl> 2678 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2679 ExpectedDecl *New) { 2680 // C++11 [basic.scope.declarative]p4: 2681 // Given a set of declarations in a single declarative region, each of 2682 // which specifies the same unqualified name, 2683 // -- they shall all refer to the same entity, or all refer to functions 2684 // and function templates; or 2685 // -- exactly one declaration shall declare a class name or enumeration 2686 // name that is not a typedef name and the other declarations shall all 2687 // refer to the same variable or enumerator, or all refer to functions 2688 // and function templates; in this case the class name or enumeration 2689 // name is hidden (3.3.10). 2690 2691 // C++11 [namespace.udecl]p14: 2692 // If a function declaration in namespace scope or block scope has the 2693 // same name and the same parameter-type-list as a function introduced 2694 // by a using-declaration, and the declarations do not declare the same 2695 // function, the program is ill-formed. 2696 2697 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2698 if (Old && 2699 !Old->getDeclContext()->getRedeclContext()->Equals( 2700 New->getDeclContext()->getRedeclContext()) && 2701 !(isExternC(Old) && isExternC(New))) 2702 Old = nullptr; 2703 2704 if (!Old) { 2705 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2706 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2707 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2708 return true; 2709 } 2710 return false; 2711 } 2712 2713 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2714 const FunctionDecl *B) { 2715 assert(A->getNumParams() == B->getNumParams()); 2716 2717 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2718 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2719 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2720 if (AttrA == AttrB) 2721 return true; 2722 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2723 }; 2724 2725 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2726 } 2727 2728 /// MergeFunctionDecl - We just parsed a function 'New' from 2729 /// declarator D which has the same name and scope as a previous 2730 /// declaration 'Old'. Figure out how to resolve this situation, 2731 /// merging decls or emitting diagnostics as appropriate. 2732 /// 2733 /// In C++, New and Old must be declarations that are not 2734 /// overloaded. Use IsOverload to determine whether New and Old are 2735 /// overloaded, and to select the Old declaration that New should be 2736 /// merged with. 2737 /// 2738 /// Returns true if there was an error, false otherwise. 2739 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2740 Scope *S, bool MergeTypeWithOld) { 2741 // Verify the old decl was also a function. 2742 FunctionDecl *Old = OldD->getAsFunction(); 2743 if (!Old) { 2744 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2745 if (New->getFriendObjectKind()) { 2746 Diag(New->getLocation(), diag::err_using_decl_friend); 2747 Diag(Shadow->getTargetDecl()->getLocation(), 2748 diag::note_using_decl_target); 2749 Diag(Shadow->getUsingDecl()->getLocation(), 2750 diag::note_using_decl) << 0; 2751 return true; 2752 } 2753 2754 // Check whether the two declarations might declare the same function. 2755 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2756 return true; 2757 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2758 } else { 2759 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2760 << New->getDeclName(); 2761 Diag(OldD->getLocation(), diag::note_previous_definition); 2762 return true; 2763 } 2764 } 2765 2766 // If the old declaration is invalid, just give up here. 2767 if (Old->isInvalidDecl()) 2768 return true; 2769 2770 diag::kind PrevDiag; 2771 SourceLocation OldLocation; 2772 std::tie(PrevDiag, OldLocation) = 2773 getNoteDiagForInvalidRedeclaration(Old, New); 2774 2775 // Don't complain about this if we're in GNU89 mode and the old function 2776 // is an extern inline function. 2777 // Don't complain about specializations. They are not supposed to have 2778 // storage classes. 2779 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2780 New->getStorageClass() == SC_Static && 2781 Old->hasExternalFormalLinkage() && 2782 !New->getTemplateSpecializationInfo() && 2783 !canRedefineFunction(Old, getLangOpts())) { 2784 if (getLangOpts().MicrosoftExt) { 2785 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2786 Diag(OldLocation, PrevDiag); 2787 } else { 2788 Diag(New->getLocation(), diag::err_static_non_static) << New; 2789 Diag(OldLocation, PrevDiag); 2790 return true; 2791 } 2792 } 2793 2794 if (New->hasAttr<InternalLinkageAttr>() && 2795 !Old->hasAttr<InternalLinkageAttr>()) { 2796 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2797 << New->getDeclName(); 2798 Diag(Old->getLocation(), diag::note_previous_definition); 2799 New->dropAttr<InternalLinkageAttr>(); 2800 } 2801 2802 // If a function is first declared with a calling convention, but is later 2803 // declared or defined without one, all following decls assume the calling 2804 // convention of the first. 2805 // 2806 // It's OK if a function is first declared without a calling convention, 2807 // but is later declared or defined with the default calling convention. 2808 // 2809 // To test if either decl has an explicit calling convention, we look for 2810 // AttributedType sugar nodes on the type as written. If they are missing or 2811 // were canonicalized away, we assume the calling convention was implicit. 2812 // 2813 // Note also that we DO NOT return at this point, because we still have 2814 // other tests to run. 2815 QualType OldQType = Context.getCanonicalType(Old->getType()); 2816 QualType NewQType = Context.getCanonicalType(New->getType()); 2817 const FunctionType *OldType = cast<FunctionType>(OldQType); 2818 const FunctionType *NewType = cast<FunctionType>(NewQType); 2819 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2820 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2821 bool RequiresAdjustment = false; 2822 2823 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2824 FunctionDecl *First = Old->getFirstDecl(); 2825 const FunctionType *FT = 2826 First->getType().getCanonicalType()->castAs<FunctionType>(); 2827 FunctionType::ExtInfo FI = FT->getExtInfo(); 2828 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2829 if (!NewCCExplicit) { 2830 // Inherit the CC from the previous declaration if it was specified 2831 // there but not here. 2832 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2833 RequiresAdjustment = true; 2834 } else { 2835 // Calling conventions aren't compatible, so complain. 2836 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2837 Diag(New->getLocation(), diag::err_cconv_change) 2838 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2839 << !FirstCCExplicit 2840 << (!FirstCCExplicit ? "" : 2841 FunctionType::getNameForCallConv(FI.getCC())); 2842 2843 // Put the note on the first decl, since it is the one that matters. 2844 Diag(First->getLocation(), diag::note_previous_declaration); 2845 return true; 2846 } 2847 } 2848 2849 // FIXME: diagnose the other way around? 2850 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2851 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2852 RequiresAdjustment = true; 2853 } 2854 2855 // Merge regparm attribute. 2856 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2857 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2858 if (NewTypeInfo.getHasRegParm()) { 2859 Diag(New->getLocation(), diag::err_regparm_mismatch) 2860 << NewType->getRegParmType() 2861 << OldType->getRegParmType(); 2862 Diag(OldLocation, diag::note_previous_declaration); 2863 return true; 2864 } 2865 2866 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2867 RequiresAdjustment = true; 2868 } 2869 2870 // Merge ns_returns_retained attribute. 2871 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2872 if (NewTypeInfo.getProducesResult()) { 2873 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2874 Diag(OldLocation, diag::note_previous_declaration); 2875 return true; 2876 } 2877 2878 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2879 RequiresAdjustment = true; 2880 } 2881 2882 if (RequiresAdjustment) { 2883 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2884 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2885 New->setType(QualType(AdjustedType, 0)); 2886 NewQType = Context.getCanonicalType(New->getType()); 2887 NewType = cast<FunctionType>(NewQType); 2888 } 2889 2890 // If this redeclaration makes the function inline, we may need to add it to 2891 // UndefinedButUsed. 2892 if (!Old->isInlined() && New->isInlined() && 2893 !New->hasAttr<GNUInlineAttr>() && 2894 !getLangOpts().GNUInline && 2895 Old->isUsed(false) && 2896 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2897 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2898 SourceLocation())); 2899 2900 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2901 // about it. 2902 if (New->hasAttr<GNUInlineAttr>() && 2903 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2904 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2905 } 2906 2907 // If pass_object_size params don't match up perfectly, this isn't a valid 2908 // redeclaration. 2909 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 2910 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 2911 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 2912 << New->getDeclName(); 2913 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2914 return true; 2915 } 2916 2917 if (getLangOpts().CPlusPlus) { 2918 // (C++98 13.1p2): 2919 // Certain function declarations cannot be overloaded: 2920 // -- Function declarations that differ only in the return type 2921 // cannot be overloaded. 2922 2923 // Go back to the type source info to compare the declared return types, 2924 // per C++1y [dcl.type.auto]p13: 2925 // Redeclarations or specializations of a function or function template 2926 // with a declared return type that uses a placeholder type shall also 2927 // use that placeholder, not a deduced type. 2928 QualType OldDeclaredReturnType = 2929 (Old->getTypeSourceInfo() 2930 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2931 : OldType)->getReturnType(); 2932 QualType NewDeclaredReturnType = 2933 (New->getTypeSourceInfo() 2934 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2935 : NewType)->getReturnType(); 2936 QualType ResQT; 2937 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2938 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2939 New->isLocalExternDecl())) { 2940 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2941 OldDeclaredReturnType->isObjCObjectPointerType()) 2942 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2943 if (ResQT.isNull()) { 2944 if (New->isCXXClassMember() && New->isOutOfLine()) 2945 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2946 << New << New->getReturnTypeSourceRange(); 2947 else 2948 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2949 << New->getReturnTypeSourceRange(); 2950 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2951 << Old->getReturnTypeSourceRange(); 2952 return true; 2953 } 2954 else 2955 NewQType = ResQT; 2956 } 2957 2958 QualType OldReturnType = OldType->getReturnType(); 2959 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2960 if (OldReturnType != NewReturnType) { 2961 // If this function has a deduced return type and has already been 2962 // defined, copy the deduced value from the old declaration. 2963 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2964 if (OldAT && OldAT->isDeduced()) { 2965 New->setType( 2966 SubstAutoType(New->getType(), 2967 OldAT->isDependentType() ? Context.DependentTy 2968 : OldAT->getDeducedType())); 2969 NewQType = Context.getCanonicalType( 2970 SubstAutoType(NewQType, 2971 OldAT->isDependentType() ? Context.DependentTy 2972 : OldAT->getDeducedType())); 2973 } 2974 } 2975 2976 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2977 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2978 if (OldMethod && NewMethod) { 2979 // Preserve triviality. 2980 NewMethod->setTrivial(OldMethod->isTrivial()); 2981 2982 // MSVC allows explicit template specialization at class scope: 2983 // 2 CXXMethodDecls referring to the same function will be injected. 2984 // We don't want a redeclaration error. 2985 bool IsClassScopeExplicitSpecialization = 2986 OldMethod->isFunctionTemplateSpecialization() && 2987 NewMethod->isFunctionTemplateSpecialization(); 2988 bool isFriend = NewMethod->getFriendObjectKind(); 2989 2990 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2991 !IsClassScopeExplicitSpecialization) { 2992 // -- Member function declarations with the same name and the 2993 // same parameter types cannot be overloaded if any of them 2994 // is a static member function declaration. 2995 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2996 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2997 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2998 return true; 2999 } 3000 3001 // C++ [class.mem]p1: 3002 // [...] A member shall not be declared twice in the 3003 // member-specification, except that a nested class or member 3004 // class template can be declared and then later defined. 3005 if (ActiveTemplateInstantiations.empty()) { 3006 unsigned NewDiag; 3007 if (isa<CXXConstructorDecl>(OldMethod)) 3008 NewDiag = diag::err_constructor_redeclared; 3009 else if (isa<CXXDestructorDecl>(NewMethod)) 3010 NewDiag = diag::err_destructor_redeclared; 3011 else if (isa<CXXConversionDecl>(NewMethod)) 3012 NewDiag = diag::err_conv_function_redeclared; 3013 else 3014 NewDiag = diag::err_member_redeclared; 3015 3016 Diag(New->getLocation(), NewDiag); 3017 } else { 3018 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3019 << New << New->getType(); 3020 } 3021 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3022 return true; 3023 3024 // Complain if this is an explicit declaration of a special 3025 // member that was initially declared implicitly. 3026 // 3027 // As an exception, it's okay to befriend such methods in order 3028 // to permit the implicit constructor/destructor/operator calls. 3029 } else if (OldMethod->isImplicit()) { 3030 if (isFriend) { 3031 NewMethod->setImplicit(); 3032 } else { 3033 Diag(NewMethod->getLocation(), 3034 diag::err_definition_of_implicitly_declared_member) 3035 << New << getSpecialMember(OldMethod); 3036 return true; 3037 } 3038 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3039 Diag(NewMethod->getLocation(), 3040 diag::err_definition_of_explicitly_defaulted_member) 3041 << getSpecialMember(OldMethod); 3042 return true; 3043 } 3044 } 3045 3046 // C++11 [dcl.attr.noreturn]p1: 3047 // The first declaration of a function shall specify the noreturn 3048 // attribute if any declaration of that function specifies the noreturn 3049 // attribute. 3050 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3051 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3052 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3053 Diag(Old->getFirstDecl()->getLocation(), 3054 diag::note_noreturn_missing_first_decl); 3055 } 3056 3057 // C++11 [dcl.attr.depend]p2: 3058 // The first declaration of a function shall specify the 3059 // carries_dependency attribute for its declarator-id if any declaration 3060 // of the function specifies the carries_dependency attribute. 3061 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3062 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3063 Diag(CDA->getLocation(), 3064 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3065 Diag(Old->getFirstDecl()->getLocation(), 3066 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3067 } 3068 3069 // (C++98 8.3.5p3): 3070 // All declarations for a function shall agree exactly in both the 3071 // return type and the parameter-type-list. 3072 // We also want to respect all the extended bits except noreturn. 3073 3074 // noreturn should now match unless the old type info didn't have it. 3075 QualType OldQTypeForComparison = OldQType; 3076 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3077 assert(OldQType == QualType(OldType, 0)); 3078 const FunctionType *OldTypeForComparison 3079 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3080 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3081 assert(OldQTypeForComparison.isCanonical()); 3082 } 3083 3084 if (haveIncompatibleLanguageLinkages(Old, New)) { 3085 // As a special case, retain the language linkage from previous 3086 // declarations of a friend function as an extension. 3087 // 3088 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3089 // and is useful because there's otherwise no way to specify language 3090 // linkage within class scope. 3091 // 3092 // Check cautiously as the friend object kind isn't yet complete. 3093 if (New->getFriendObjectKind() != Decl::FOK_None) { 3094 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3095 Diag(OldLocation, PrevDiag); 3096 } else { 3097 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3098 Diag(OldLocation, PrevDiag); 3099 return true; 3100 } 3101 } 3102 3103 if (OldQTypeForComparison == NewQType) 3104 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3105 3106 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3107 New->isLocalExternDecl()) { 3108 // It's OK if we couldn't merge types for a local function declaraton 3109 // if either the old or new type is dependent. We'll merge the types 3110 // when we instantiate the function. 3111 return false; 3112 } 3113 3114 // Fall through for conflicting redeclarations and redefinitions. 3115 } 3116 3117 // C: Function types need to be compatible, not identical. This handles 3118 // duplicate function decls like "void f(int); void f(enum X);" properly. 3119 if (!getLangOpts().CPlusPlus && 3120 Context.typesAreCompatible(OldQType, NewQType)) { 3121 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3122 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3123 const FunctionProtoType *OldProto = nullptr; 3124 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3125 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3126 // The old declaration provided a function prototype, but the 3127 // new declaration does not. Merge in the prototype. 3128 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3129 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3130 NewQType = 3131 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3132 OldProto->getExtProtoInfo()); 3133 New->setType(NewQType); 3134 New->setHasInheritedPrototype(); 3135 3136 // Synthesize parameters with the same types. 3137 SmallVector<ParmVarDecl*, 16> Params; 3138 for (const auto &ParamType : OldProto->param_types()) { 3139 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3140 SourceLocation(), nullptr, 3141 ParamType, /*TInfo=*/nullptr, 3142 SC_None, nullptr); 3143 Param->setScopeInfo(0, Params.size()); 3144 Param->setImplicit(); 3145 Params.push_back(Param); 3146 } 3147 3148 New->setParams(Params); 3149 } 3150 3151 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3152 } 3153 3154 // GNU C permits a K&R definition to follow a prototype declaration 3155 // if the declared types of the parameters in the K&R definition 3156 // match the types in the prototype declaration, even when the 3157 // promoted types of the parameters from the K&R definition differ 3158 // from the types in the prototype. GCC then keeps the types from 3159 // the prototype. 3160 // 3161 // If a variadic prototype is followed by a non-variadic K&R definition, 3162 // the K&R definition becomes variadic. This is sort of an edge case, but 3163 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3164 // C99 6.9.1p8. 3165 if (!getLangOpts().CPlusPlus && 3166 Old->hasPrototype() && !New->hasPrototype() && 3167 New->getType()->getAs<FunctionProtoType>() && 3168 Old->getNumParams() == New->getNumParams()) { 3169 SmallVector<QualType, 16> ArgTypes; 3170 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3171 const FunctionProtoType *OldProto 3172 = Old->getType()->getAs<FunctionProtoType>(); 3173 const FunctionProtoType *NewProto 3174 = New->getType()->getAs<FunctionProtoType>(); 3175 3176 // Determine whether this is the GNU C extension. 3177 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3178 NewProto->getReturnType()); 3179 bool LooseCompatible = !MergedReturn.isNull(); 3180 for (unsigned Idx = 0, End = Old->getNumParams(); 3181 LooseCompatible && Idx != End; ++Idx) { 3182 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3183 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3184 if (Context.typesAreCompatible(OldParm->getType(), 3185 NewProto->getParamType(Idx))) { 3186 ArgTypes.push_back(NewParm->getType()); 3187 } else if (Context.typesAreCompatible(OldParm->getType(), 3188 NewParm->getType(), 3189 /*CompareUnqualified=*/true)) { 3190 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3191 NewProto->getParamType(Idx) }; 3192 Warnings.push_back(Warn); 3193 ArgTypes.push_back(NewParm->getType()); 3194 } else 3195 LooseCompatible = false; 3196 } 3197 3198 if (LooseCompatible) { 3199 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3200 Diag(Warnings[Warn].NewParm->getLocation(), 3201 diag::ext_param_promoted_not_compatible_with_prototype) 3202 << Warnings[Warn].PromotedType 3203 << Warnings[Warn].OldParm->getType(); 3204 if (Warnings[Warn].OldParm->getLocation().isValid()) 3205 Diag(Warnings[Warn].OldParm->getLocation(), 3206 diag::note_previous_declaration); 3207 } 3208 3209 if (MergeTypeWithOld) 3210 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3211 OldProto->getExtProtoInfo())); 3212 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3213 } 3214 3215 // Fall through to diagnose conflicting types. 3216 } 3217 3218 // A function that has already been declared has been redeclared or 3219 // defined with a different type; show an appropriate diagnostic. 3220 3221 // If the previous declaration was an implicitly-generated builtin 3222 // declaration, then at the very least we should use a specialized note. 3223 unsigned BuiltinID; 3224 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3225 // If it's actually a library-defined builtin function like 'malloc' 3226 // or 'printf', just warn about the incompatible redeclaration. 3227 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3228 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3229 Diag(OldLocation, diag::note_previous_builtin_declaration) 3230 << Old << Old->getType(); 3231 3232 // If this is a global redeclaration, just forget hereafter 3233 // about the "builtin-ness" of the function. 3234 // 3235 // Doing this for local extern declarations is problematic. If 3236 // the builtin declaration remains visible, a second invalid 3237 // local declaration will produce a hard error; if it doesn't 3238 // remain visible, a single bogus local redeclaration (which is 3239 // actually only a warning) could break all the downstream code. 3240 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3241 New->getIdentifier()->revertBuiltin(); 3242 3243 return false; 3244 } 3245 3246 PrevDiag = diag::note_previous_builtin_declaration; 3247 } 3248 3249 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3250 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3251 return true; 3252 } 3253 3254 /// \brief Completes the merge of two function declarations that are 3255 /// known to be compatible. 3256 /// 3257 /// This routine handles the merging of attributes and other 3258 /// properties of function declarations from the old declaration to 3259 /// the new declaration, once we know that New is in fact a 3260 /// redeclaration of Old. 3261 /// 3262 /// \returns false 3263 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3264 Scope *S, bool MergeTypeWithOld) { 3265 // Merge the attributes 3266 mergeDeclAttributes(New, Old); 3267 3268 // Merge "pure" flag. 3269 if (Old->isPure()) 3270 New->setPure(); 3271 3272 // Merge "used" flag. 3273 if (Old->getMostRecentDecl()->isUsed(false)) 3274 New->setIsUsed(); 3275 3276 // Merge attributes from the parameters. These can mismatch with K&R 3277 // declarations. 3278 if (New->getNumParams() == Old->getNumParams()) 3279 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3280 ParmVarDecl *NewParam = New->getParamDecl(i); 3281 ParmVarDecl *OldParam = Old->getParamDecl(i); 3282 mergeParamDeclAttributes(NewParam, OldParam, *this); 3283 mergeParamDeclTypes(NewParam, OldParam, *this); 3284 } 3285 3286 if (getLangOpts().CPlusPlus) 3287 return MergeCXXFunctionDecl(New, Old, S); 3288 3289 // Merge the function types so the we get the composite types for the return 3290 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3291 // was visible. 3292 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3293 if (!Merged.isNull() && MergeTypeWithOld) 3294 New->setType(Merged); 3295 3296 return false; 3297 } 3298 3299 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3300 ObjCMethodDecl *oldMethod) { 3301 // Merge the attributes, including deprecated/unavailable 3302 AvailabilityMergeKind MergeKind = 3303 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3304 ? AMK_ProtocolImplementation 3305 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3306 : AMK_Override; 3307 3308 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3309 3310 // Merge attributes from the parameters. 3311 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3312 oe = oldMethod->param_end(); 3313 for (ObjCMethodDecl::param_iterator 3314 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3315 ni != ne && oi != oe; ++ni, ++oi) 3316 mergeParamDeclAttributes(*ni, *oi, *this); 3317 3318 CheckObjCMethodOverride(newMethod, oldMethod); 3319 } 3320 3321 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3322 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3323 3324 S.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 S.Diag(OldLocation, PrevDiag); 3334 New->setInvalidDecl(); 3335 } 3336 3337 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3338 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3339 /// emitting diagnostics as appropriate. 3340 /// 3341 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3342 /// to here in AddInitializerToDecl. We can't check them before the initializer 3343 /// is attached. 3344 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3345 bool MergeTypeWithOld) { 3346 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3347 return; 3348 3349 QualType MergedT; 3350 if (getLangOpts().CPlusPlus) { 3351 if (New->getType()->isUndeducedType()) { 3352 // We don't know what the new type is until the initializer is attached. 3353 return; 3354 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3355 // These could still be something that needs exception specs checked. 3356 return MergeVarDeclExceptionSpecs(New, Old); 3357 } 3358 // C++ [basic.link]p10: 3359 // [...] the types specified by all declarations referring to a given 3360 // object or function shall be identical, except that declarations for an 3361 // array object can specify array types that differ by the presence or 3362 // absence of a major array bound (8.3.4). 3363 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3364 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3365 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3366 3367 // We are merging a variable declaration New into Old. If it has an array 3368 // bound, and that bound differs from Old's bound, we should diagnose the 3369 // mismatch. 3370 if (!NewArray->isIncompleteArrayType()) { 3371 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3372 PrevVD = PrevVD->getPreviousDecl()) { 3373 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3374 if (PrevVDTy->isIncompleteArrayType()) 3375 continue; 3376 3377 if (!Context.hasSameType(NewArray, PrevVDTy)) 3378 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3379 } 3380 } 3381 3382 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3383 if (Context.hasSameType(OldArray->getElementType(), 3384 NewArray->getElementType())) 3385 MergedT = New->getType(); 3386 } 3387 // FIXME: Check visibility. New is hidden but has a complete type. If New 3388 // has no array bound, it should not inherit one from Old, if Old is not 3389 // visible. 3390 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3391 if (Context.hasSameType(OldArray->getElementType(), 3392 NewArray->getElementType())) 3393 MergedT = Old->getType(); 3394 } 3395 } 3396 else if (New->getType()->isObjCObjectPointerType() && 3397 Old->getType()->isObjCObjectPointerType()) { 3398 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3399 Old->getType()); 3400 } 3401 } else { 3402 // C 6.2.7p2: 3403 // All declarations that refer to the same object or function shall have 3404 // compatible type. 3405 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3406 } 3407 if (MergedT.isNull()) { 3408 // It's OK if we couldn't merge types if either type is dependent, for a 3409 // block-scope variable. In other cases (static data members of class 3410 // templates, variable templates, ...), we require the types to be 3411 // equivalent. 3412 // FIXME: The C++ standard doesn't say anything about this. 3413 if ((New->getType()->isDependentType() || 3414 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3415 // If the old type was dependent, we can't merge with it, so the new type 3416 // becomes dependent for now. We'll reproduce the original type when we 3417 // instantiate the TypeSourceInfo for the variable. 3418 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3419 New->setType(Context.DependentTy); 3420 return; 3421 } 3422 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3423 } 3424 3425 // Don't actually update the type on the new declaration if the old 3426 // declaration was an extern declaration in a different scope. 3427 if (MergeTypeWithOld) 3428 New->setType(MergedT); 3429 } 3430 3431 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3432 LookupResult &Previous) { 3433 // C11 6.2.7p4: 3434 // For an identifier with internal or external linkage declared 3435 // in a scope in which a prior declaration of that identifier is 3436 // visible, if the prior declaration specifies internal or 3437 // external linkage, the type of the identifier at the later 3438 // declaration becomes the composite type. 3439 // 3440 // If the variable isn't visible, we do not merge with its type. 3441 if (Previous.isShadowed()) 3442 return false; 3443 3444 if (S.getLangOpts().CPlusPlus) { 3445 // C++11 [dcl.array]p3: 3446 // If there is a preceding declaration of the entity in the same 3447 // scope in which the bound was specified, an omitted array bound 3448 // is taken to be the same as in that earlier declaration. 3449 return NewVD->isPreviousDeclInSameBlockScope() || 3450 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3451 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3452 } else { 3453 // If the old declaration was function-local, don't merge with its 3454 // type unless we're in the same function. 3455 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3456 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3457 } 3458 } 3459 3460 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3461 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3462 /// situation, merging decls or emitting diagnostics as appropriate. 3463 /// 3464 /// Tentative definition rules (C99 6.9.2p2) are checked by 3465 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3466 /// definitions here, since the initializer hasn't been attached. 3467 /// 3468 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3469 // If the new decl is already invalid, don't do any other checking. 3470 if (New->isInvalidDecl()) 3471 return; 3472 3473 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3474 return; 3475 3476 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3477 3478 // Verify the old decl was also a variable or variable template. 3479 VarDecl *Old = nullptr; 3480 VarTemplateDecl *OldTemplate = nullptr; 3481 if (Previous.isSingleResult()) { 3482 if (NewTemplate) { 3483 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3484 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3485 3486 if (auto *Shadow = 3487 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3488 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3489 return New->setInvalidDecl(); 3490 } else { 3491 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3492 3493 if (auto *Shadow = 3494 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3495 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3496 return New->setInvalidDecl(); 3497 } 3498 } 3499 if (!Old) { 3500 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3501 << New->getDeclName(); 3502 Diag(Previous.getRepresentativeDecl()->getLocation(), 3503 diag::note_previous_definition); 3504 return New->setInvalidDecl(); 3505 } 3506 3507 // Ensure the template parameters are compatible. 3508 if (NewTemplate && 3509 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3510 OldTemplate->getTemplateParameters(), 3511 /*Complain=*/true, TPL_TemplateMatch)) 3512 return New->setInvalidDecl(); 3513 3514 // C++ [class.mem]p1: 3515 // A member shall not be declared twice in the member-specification [...] 3516 // 3517 // Here, we need only consider static data members. 3518 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3519 Diag(New->getLocation(), diag::err_duplicate_member) 3520 << New->getIdentifier(); 3521 Diag(Old->getLocation(), diag::note_previous_declaration); 3522 New->setInvalidDecl(); 3523 } 3524 3525 mergeDeclAttributes(New, Old); 3526 // Warn if an already-declared variable is made a weak_import in a subsequent 3527 // declaration 3528 if (New->hasAttr<WeakImportAttr>() && 3529 Old->getStorageClass() == SC_None && 3530 !Old->hasAttr<WeakImportAttr>()) { 3531 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3532 Diag(Old->getLocation(), diag::note_previous_definition); 3533 // Remove weak_import attribute on new declaration. 3534 New->dropAttr<WeakImportAttr>(); 3535 } 3536 3537 if (New->hasAttr<InternalLinkageAttr>() && 3538 !Old->hasAttr<InternalLinkageAttr>()) { 3539 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3540 << New->getDeclName(); 3541 Diag(Old->getLocation(), diag::note_previous_definition); 3542 New->dropAttr<InternalLinkageAttr>(); 3543 } 3544 3545 // Merge the types. 3546 VarDecl *MostRecent = Old->getMostRecentDecl(); 3547 if (MostRecent != Old) { 3548 MergeVarDeclTypes(New, MostRecent, 3549 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3550 if (New->isInvalidDecl()) 3551 return; 3552 } 3553 3554 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3555 if (New->isInvalidDecl()) 3556 return; 3557 3558 diag::kind PrevDiag; 3559 SourceLocation OldLocation; 3560 std::tie(PrevDiag, OldLocation) = 3561 getNoteDiagForInvalidRedeclaration(Old, New); 3562 3563 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3564 if (New->getStorageClass() == SC_Static && 3565 !New->isStaticDataMember() && 3566 Old->hasExternalFormalLinkage()) { 3567 if (getLangOpts().MicrosoftExt) { 3568 Diag(New->getLocation(), diag::ext_static_non_static) 3569 << New->getDeclName(); 3570 Diag(OldLocation, PrevDiag); 3571 } else { 3572 Diag(New->getLocation(), diag::err_static_non_static) 3573 << New->getDeclName(); 3574 Diag(OldLocation, PrevDiag); 3575 return New->setInvalidDecl(); 3576 } 3577 } 3578 // C99 6.2.2p4: 3579 // For an identifier declared with the storage-class specifier 3580 // extern in a scope in which a prior declaration of that 3581 // identifier is visible,23) if the prior declaration specifies 3582 // internal or external linkage, the linkage of the identifier at 3583 // the later declaration is the same as the linkage specified at 3584 // the prior declaration. If no prior declaration is visible, or 3585 // if the prior declaration specifies no linkage, then the 3586 // identifier has external linkage. 3587 if (New->hasExternalStorage() && Old->hasLinkage()) 3588 /* Okay */; 3589 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3590 !New->isStaticDataMember() && 3591 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3592 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3593 Diag(OldLocation, PrevDiag); 3594 return New->setInvalidDecl(); 3595 } 3596 3597 // Check if extern is followed by non-extern and vice-versa. 3598 if (New->hasExternalStorage() && 3599 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3600 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3601 Diag(OldLocation, PrevDiag); 3602 return New->setInvalidDecl(); 3603 } 3604 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3605 !New->hasExternalStorage()) { 3606 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3607 Diag(OldLocation, PrevDiag); 3608 return New->setInvalidDecl(); 3609 } 3610 3611 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3612 3613 // FIXME: The test for external storage here seems wrong? We still 3614 // need to check for mismatches. 3615 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3616 // Don't complain about out-of-line definitions of static members. 3617 !(Old->getLexicalDeclContext()->isRecord() && 3618 !New->getLexicalDeclContext()->isRecord())) { 3619 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3620 Diag(OldLocation, PrevDiag); 3621 return New->setInvalidDecl(); 3622 } 3623 3624 if (New->getTLSKind() != Old->getTLSKind()) { 3625 if (!Old->getTLSKind()) { 3626 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3627 Diag(OldLocation, PrevDiag); 3628 } else if (!New->getTLSKind()) { 3629 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3630 Diag(OldLocation, PrevDiag); 3631 } else { 3632 // Do not allow redeclaration to change the variable between requiring 3633 // static and dynamic initialization. 3634 // FIXME: GCC allows this, but uses the TLS keyword on the first 3635 // declaration to determine the kind. Do we need to be compatible here? 3636 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3637 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3638 Diag(OldLocation, PrevDiag); 3639 } 3640 } 3641 3642 // C++ doesn't have tentative definitions, so go right ahead and check here. 3643 VarDecl *Def; 3644 if (getLangOpts().CPlusPlus && 3645 New->isThisDeclarationADefinition() == VarDecl::Definition && 3646 (Def = Old->getDefinition())) { 3647 NamedDecl *Hidden = nullptr; 3648 if (!hasVisibleDefinition(Def, &Hidden) && 3649 (New->getFormalLinkage() == InternalLinkage || 3650 New->getDescribedVarTemplate() || 3651 New->getNumTemplateParameterLists() || 3652 New->getDeclContext()->isDependentContext())) { 3653 // The previous definition is hidden, and multiple definitions are 3654 // permitted (in separate TUs). Form another definition of it. 3655 } else { 3656 Diag(New->getLocation(), diag::err_redefinition) << New; 3657 Diag(Def->getLocation(), diag::note_previous_definition); 3658 New->setInvalidDecl(); 3659 return; 3660 } 3661 } 3662 3663 if (haveIncompatibleLanguageLinkages(Old, New)) { 3664 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3665 Diag(OldLocation, PrevDiag); 3666 New->setInvalidDecl(); 3667 return; 3668 } 3669 3670 // Merge "used" flag. 3671 if (Old->getMostRecentDecl()->isUsed(false)) 3672 New->setIsUsed(); 3673 3674 // Keep a chain of previous declarations. 3675 New->setPreviousDecl(Old); 3676 if (NewTemplate) 3677 NewTemplate->setPreviousDecl(OldTemplate); 3678 3679 // Inherit access appropriately. 3680 New->setAccess(Old->getAccess()); 3681 if (NewTemplate) 3682 NewTemplate->setAccess(New->getAccess()); 3683 } 3684 3685 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3686 /// no declarator (e.g. "struct foo;") is parsed. 3687 Decl * 3688 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3689 RecordDecl *&AnonRecord) { 3690 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3691 AnonRecord); 3692 } 3693 3694 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3695 // disambiguate entities defined in different scopes. 3696 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3697 // compatibility. 3698 // We will pick our mangling number depending on which version of MSVC is being 3699 // targeted. 3700 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3701 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3702 ? S->getMSCurManglingNumber() 3703 : S->getMSLastManglingNumber(); 3704 } 3705 3706 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3707 if (!Context.getLangOpts().CPlusPlus) 3708 return; 3709 3710 if (isa<CXXRecordDecl>(Tag->getParent())) { 3711 // If this tag is the direct child of a class, number it if 3712 // it is anonymous. 3713 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3714 return; 3715 MangleNumberingContext &MCtx = 3716 Context.getManglingNumberContext(Tag->getParent()); 3717 Context.setManglingNumber( 3718 Tag, MCtx.getManglingNumber( 3719 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3720 return; 3721 } 3722 3723 // If this tag isn't a direct child of a class, number it if it is local. 3724 Decl *ManglingContextDecl; 3725 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3726 Tag->getDeclContext(), ManglingContextDecl)) { 3727 Context.setManglingNumber( 3728 Tag, MCtx->getManglingNumber( 3729 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3730 } 3731 } 3732 3733 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3734 TypedefNameDecl *NewTD) { 3735 if (TagFromDeclSpec->isInvalidDecl()) 3736 return; 3737 3738 // Do nothing if the tag already has a name for linkage purposes. 3739 if (TagFromDeclSpec->hasNameForLinkage()) 3740 return; 3741 3742 // A well-formed anonymous tag must always be a TUK_Definition. 3743 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3744 3745 // The type must match the tag exactly; no qualifiers allowed. 3746 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3747 Context.getTagDeclType(TagFromDeclSpec))) { 3748 if (getLangOpts().CPlusPlus) 3749 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3750 return; 3751 } 3752 3753 // If we've already computed linkage for the anonymous tag, then 3754 // adding a typedef name for the anonymous decl can change that 3755 // linkage, which might be a serious problem. Diagnose this as 3756 // unsupported and ignore the typedef name. TODO: we should 3757 // pursue this as a language defect and establish a formal rule 3758 // for how to handle it. 3759 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3760 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3761 3762 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3763 tagLoc = getLocForEndOfToken(tagLoc); 3764 3765 llvm::SmallString<40> textToInsert; 3766 textToInsert += ' '; 3767 textToInsert += NewTD->getIdentifier()->getName(); 3768 Diag(tagLoc, diag::note_typedef_changes_linkage) 3769 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3770 return; 3771 } 3772 3773 // Otherwise, set this is the anon-decl typedef for the tag. 3774 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3775 } 3776 3777 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3778 switch (T) { 3779 case DeclSpec::TST_class: 3780 return 0; 3781 case DeclSpec::TST_struct: 3782 return 1; 3783 case DeclSpec::TST_interface: 3784 return 2; 3785 case DeclSpec::TST_union: 3786 return 3; 3787 case DeclSpec::TST_enum: 3788 return 4; 3789 default: 3790 llvm_unreachable("unexpected type specifier"); 3791 } 3792 } 3793 3794 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3795 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3796 /// parameters to cope with template friend declarations. 3797 Decl * 3798 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3799 MultiTemplateParamsArg TemplateParams, 3800 bool IsExplicitInstantiation, 3801 RecordDecl *&AnonRecord) { 3802 Decl *TagD = nullptr; 3803 TagDecl *Tag = nullptr; 3804 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3805 DS.getTypeSpecType() == DeclSpec::TST_struct || 3806 DS.getTypeSpecType() == DeclSpec::TST_interface || 3807 DS.getTypeSpecType() == DeclSpec::TST_union || 3808 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3809 TagD = DS.getRepAsDecl(); 3810 3811 if (!TagD) // We probably had an error 3812 return nullptr; 3813 3814 // Note that the above type specs guarantee that the 3815 // type rep is a Decl, whereas in many of the others 3816 // it's a Type. 3817 if (isa<TagDecl>(TagD)) 3818 Tag = cast<TagDecl>(TagD); 3819 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3820 Tag = CTD->getTemplatedDecl(); 3821 } 3822 3823 if (Tag) { 3824 handleTagNumbering(Tag, S); 3825 Tag->setFreeStanding(); 3826 if (Tag->isInvalidDecl()) 3827 return Tag; 3828 } 3829 3830 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3831 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3832 // or incomplete types shall not be restrict-qualified." 3833 if (TypeQuals & DeclSpec::TQ_restrict) 3834 Diag(DS.getRestrictSpecLoc(), 3835 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3836 << DS.getSourceRange(); 3837 } 3838 3839 if (DS.isConstexprSpecified()) { 3840 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3841 // and definitions of functions and variables. 3842 if (Tag) 3843 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3844 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3845 else 3846 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3847 // Don't emit warnings after this error. 3848 return TagD; 3849 } 3850 3851 if (DS.isConceptSpecified()) { 3852 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3853 // either a function concept and its definition or a variable concept and 3854 // its initializer. 3855 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3856 return TagD; 3857 } 3858 3859 DiagnoseFunctionSpecifiers(DS); 3860 3861 if (DS.isFriendSpecified()) { 3862 // If we're dealing with a decl but not a TagDecl, assume that 3863 // whatever routines created it handled the friendship aspect. 3864 if (TagD && !Tag) 3865 return nullptr; 3866 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3867 } 3868 3869 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3870 bool IsExplicitSpecialization = 3871 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3872 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3873 !IsExplicitInstantiation && !IsExplicitSpecialization && 3874 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 3875 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3876 // nested-name-specifier unless it is an explicit instantiation 3877 // or an explicit specialization. 3878 // 3879 // FIXME: We allow class template partial specializations here too, per the 3880 // obvious intent of DR1819. 3881 // 3882 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3883 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3884 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 3885 return nullptr; 3886 } 3887 3888 // Track whether this decl-specifier declares anything. 3889 bool DeclaresAnything = true; 3890 3891 // Handle anonymous struct definitions. 3892 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3893 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3894 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3895 if (getLangOpts().CPlusPlus || 3896 Record->getDeclContext()->isRecord()) { 3897 // If CurContext is a DeclContext that can contain statements, 3898 // RecursiveASTVisitor won't visit the decls that 3899 // BuildAnonymousStructOrUnion() will put into CurContext. 3900 // Also store them here so that they can be part of the 3901 // DeclStmt that gets created in this case. 3902 // FIXME: Also return the IndirectFieldDecls created by 3903 // BuildAnonymousStructOr union, for the same reason? 3904 if (CurContext->isFunctionOrMethod()) 3905 AnonRecord = Record; 3906 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3907 Context.getPrintingPolicy()); 3908 } 3909 3910 DeclaresAnything = false; 3911 } 3912 } 3913 3914 // C11 6.7.2.1p2: 3915 // A struct-declaration that does not declare an anonymous structure or 3916 // anonymous union shall contain a struct-declarator-list. 3917 // 3918 // This rule also existed in C89 and C99; the grammar for struct-declaration 3919 // did not permit a struct-declaration without a struct-declarator-list. 3920 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3921 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3922 // Check for Microsoft C extension: anonymous struct/union member. 3923 // Handle 2 kinds of anonymous struct/union: 3924 // struct STRUCT; 3925 // union UNION; 3926 // and 3927 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3928 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3929 if ((Tag && Tag->getDeclName()) || 3930 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3931 RecordDecl *Record = nullptr; 3932 if (Tag) 3933 Record = dyn_cast<RecordDecl>(Tag); 3934 else if (const RecordType *RT = 3935 DS.getRepAsType().get()->getAsStructureType()) 3936 Record = RT->getDecl(); 3937 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3938 Record = UT->getDecl(); 3939 3940 if (Record && getLangOpts().MicrosoftExt) { 3941 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3942 << Record->isUnion() << DS.getSourceRange(); 3943 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3944 } 3945 3946 DeclaresAnything = false; 3947 } 3948 } 3949 3950 // Skip all the checks below if we have a type error. 3951 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3952 (TagD && TagD->isInvalidDecl())) 3953 return TagD; 3954 3955 if (getLangOpts().CPlusPlus && 3956 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3957 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3958 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3959 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3960 DeclaresAnything = false; 3961 3962 if (!DS.isMissingDeclaratorOk()) { 3963 // Customize diagnostic for a typedef missing a name. 3964 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3965 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3966 << DS.getSourceRange(); 3967 else 3968 DeclaresAnything = false; 3969 } 3970 3971 if (DS.isModulePrivateSpecified() && 3972 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3973 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3974 << Tag->getTagKind() 3975 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3976 3977 ActOnDocumentableDecl(TagD); 3978 3979 // C 6.7/2: 3980 // A declaration [...] shall declare at least a declarator [...], a tag, 3981 // or the members of an enumeration. 3982 // C++ [dcl.dcl]p3: 3983 // [If there are no declarators], and except for the declaration of an 3984 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3985 // names into the program, or shall redeclare a name introduced by a 3986 // previous declaration. 3987 if (!DeclaresAnything) { 3988 // In C, we allow this as a (popular) extension / bug. Don't bother 3989 // producing further diagnostics for redundant qualifiers after this. 3990 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3991 return TagD; 3992 } 3993 3994 // C++ [dcl.stc]p1: 3995 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3996 // init-declarator-list of the declaration shall not be empty. 3997 // C++ [dcl.fct.spec]p1: 3998 // If a cv-qualifier appears in a decl-specifier-seq, the 3999 // init-declarator-list of the declaration shall not be empty. 4000 // 4001 // Spurious qualifiers here appear to be valid in C. 4002 unsigned DiagID = diag::warn_standalone_specifier; 4003 if (getLangOpts().CPlusPlus) 4004 DiagID = diag::ext_standalone_specifier; 4005 4006 // Note that a linkage-specification sets a storage class, but 4007 // 'extern "C" struct foo;' is actually valid and not theoretically 4008 // useless. 4009 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4010 if (SCS == DeclSpec::SCS_mutable) 4011 // Since mutable is not a viable storage class specifier in C, there is 4012 // no reason to treat it as an extension. Instead, diagnose as an error. 4013 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4014 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4015 Diag(DS.getStorageClassSpecLoc(), DiagID) 4016 << DeclSpec::getSpecifierName(SCS); 4017 } 4018 4019 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4020 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4021 << DeclSpec::getSpecifierName(TSCS); 4022 if (DS.getTypeQualifiers()) { 4023 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4024 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4025 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4026 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4027 // Restrict is covered above. 4028 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4029 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4030 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4031 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4032 } 4033 4034 // Warn about ignored type attributes, for example: 4035 // __attribute__((aligned)) struct A; 4036 // Attributes should be placed after tag to apply to type declaration. 4037 if (!DS.getAttributes().empty()) { 4038 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4039 if (TypeSpecType == DeclSpec::TST_class || 4040 TypeSpecType == DeclSpec::TST_struct || 4041 TypeSpecType == DeclSpec::TST_interface || 4042 TypeSpecType == DeclSpec::TST_union || 4043 TypeSpecType == DeclSpec::TST_enum) { 4044 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4045 attrs = attrs->getNext()) 4046 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4047 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4048 } 4049 } 4050 4051 return TagD; 4052 } 4053 4054 /// We are trying to inject an anonymous member into the given scope; 4055 /// check if there's an existing declaration that can't be overloaded. 4056 /// 4057 /// \return true if this is a forbidden redeclaration 4058 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4059 Scope *S, 4060 DeclContext *Owner, 4061 DeclarationName Name, 4062 SourceLocation NameLoc, 4063 bool IsUnion) { 4064 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4065 Sema::ForRedeclaration); 4066 if (!SemaRef.LookupName(R, S)) return false; 4067 4068 // Pick a representative declaration. 4069 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4070 assert(PrevDecl && "Expected a non-null Decl"); 4071 4072 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4073 return false; 4074 4075 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4076 << IsUnion << Name; 4077 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4078 4079 return true; 4080 } 4081 4082 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4083 /// anonymous struct or union AnonRecord into the owning context Owner 4084 /// and scope S. This routine will be invoked just after we realize 4085 /// that an unnamed union or struct is actually an anonymous union or 4086 /// struct, e.g., 4087 /// 4088 /// @code 4089 /// union { 4090 /// int i; 4091 /// float f; 4092 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4093 /// // f into the surrounding scope.x 4094 /// @endcode 4095 /// 4096 /// This routine is recursive, injecting the names of nested anonymous 4097 /// structs/unions into the owning context and scope as well. 4098 static bool 4099 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4100 RecordDecl *AnonRecord, AccessSpecifier AS, 4101 SmallVectorImpl<NamedDecl *> &Chaining) { 4102 bool Invalid = false; 4103 4104 // Look every FieldDecl and IndirectFieldDecl with a name. 4105 for (auto *D : AnonRecord->decls()) { 4106 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4107 cast<NamedDecl>(D)->getDeclName()) { 4108 ValueDecl *VD = cast<ValueDecl>(D); 4109 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4110 VD->getLocation(), 4111 AnonRecord->isUnion())) { 4112 // C++ [class.union]p2: 4113 // The names of the members of an anonymous union shall be 4114 // distinct from the names of any other entity in the 4115 // scope in which the anonymous union is declared. 4116 Invalid = true; 4117 } else { 4118 // C++ [class.union]p2: 4119 // For the purpose of name lookup, after the anonymous union 4120 // definition, the members of the anonymous union are 4121 // considered to have been defined in the scope in which the 4122 // anonymous union is declared. 4123 unsigned OldChainingSize = Chaining.size(); 4124 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4125 Chaining.append(IF->chain_begin(), IF->chain_end()); 4126 else 4127 Chaining.push_back(VD); 4128 4129 assert(Chaining.size() >= 2); 4130 NamedDecl **NamedChain = 4131 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4132 for (unsigned i = 0; i < Chaining.size(); i++) 4133 NamedChain[i] = Chaining[i]; 4134 4135 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4136 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4137 VD->getType(), NamedChain, Chaining.size()); 4138 4139 for (const auto *Attr : VD->attrs()) 4140 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4141 4142 IndirectField->setAccess(AS); 4143 IndirectField->setImplicit(); 4144 SemaRef.PushOnScopeChains(IndirectField, S); 4145 4146 // That includes picking up the appropriate access specifier. 4147 if (AS != AS_none) IndirectField->setAccess(AS); 4148 4149 Chaining.resize(OldChainingSize); 4150 } 4151 } 4152 } 4153 4154 return Invalid; 4155 } 4156 4157 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4158 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4159 /// illegal input values are mapped to SC_None. 4160 static StorageClass 4161 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4162 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4163 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4164 "Parser allowed 'typedef' as storage class VarDecl."); 4165 switch (StorageClassSpec) { 4166 case DeclSpec::SCS_unspecified: return SC_None; 4167 case DeclSpec::SCS_extern: 4168 if (DS.isExternInLinkageSpec()) 4169 return SC_None; 4170 return SC_Extern; 4171 case DeclSpec::SCS_static: return SC_Static; 4172 case DeclSpec::SCS_auto: return SC_Auto; 4173 case DeclSpec::SCS_register: return SC_Register; 4174 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4175 // Illegal SCSs map to None: error reporting is up to the caller. 4176 case DeclSpec::SCS_mutable: // Fall through. 4177 case DeclSpec::SCS_typedef: return SC_None; 4178 } 4179 llvm_unreachable("unknown storage class specifier"); 4180 } 4181 4182 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4183 assert(Record->hasInClassInitializer()); 4184 4185 for (const auto *I : Record->decls()) { 4186 const auto *FD = dyn_cast<FieldDecl>(I); 4187 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4188 FD = IFD->getAnonField(); 4189 if (FD && FD->hasInClassInitializer()) 4190 return FD->getLocation(); 4191 } 4192 4193 llvm_unreachable("couldn't find in-class initializer"); 4194 } 4195 4196 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4197 SourceLocation DefaultInitLoc) { 4198 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4199 return; 4200 4201 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4202 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4203 } 4204 4205 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4206 CXXRecordDecl *AnonUnion) { 4207 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4208 return; 4209 4210 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4211 } 4212 4213 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4214 /// anonymous structure or union. Anonymous unions are a C++ feature 4215 /// (C++ [class.union]) and a C11 feature; anonymous structures 4216 /// are a C11 feature and GNU C++ extension. 4217 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4218 AccessSpecifier AS, 4219 RecordDecl *Record, 4220 const PrintingPolicy &Policy) { 4221 DeclContext *Owner = Record->getDeclContext(); 4222 4223 // Diagnose whether this anonymous struct/union is an extension. 4224 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4225 Diag(Record->getLocation(), diag::ext_anonymous_union); 4226 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4227 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4228 else if (!Record->isUnion() && !getLangOpts().C11) 4229 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4230 4231 // C and C++ require different kinds of checks for anonymous 4232 // structs/unions. 4233 bool Invalid = false; 4234 if (getLangOpts().CPlusPlus) { 4235 const char *PrevSpec = nullptr; 4236 unsigned DiagID; 4237 if (Record->isUnion()) { 4238 // C++ [class.union]p6: 4239 // Anonymous unions declared in a named namespace or in the 4240 // global namespace shall be declared static. 4241 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4242 (isa<TranslationUnitDecl>(Owner) || 4243 (isa<NamespaceDecl>(Owner) && 4244 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4245 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4246 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4247 4248 // Recover by adding 'static'. 4249 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4250 PrevSpec, DiagID, Policy); 4251 } 4252 // C++ [class.union]p6: 4253 // A storage class is not allowed in a declaration of an 4254 // anonymous union in a class scope. 4255 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4256 isa<RecordDecl>(Owner)) { 4257 Diag(DS.getStorageClassSpecLoc(), 4258 diag::err_anonymous_union_with_storage_spec) 4259 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4260 4261 // Recover by removing the storage specifier. 4262 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4263 SourceLocation(), 4264 PrevSpec, DiagID, Context.getPrintingPolicy()); 4265 } 4266 } 4267 4268 // Ignore const/volatile/restrict qualifiers. 4269 if (DS.getTypeQualifiers()) { 4270 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4271 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4272 << Record->isUnion() << "const" 4273 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4274 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4275 Diag(DS.getVolatileSpecLoc(), 4276 diag::ext_anonymous_struct_union_qualified) 4277 << Record->isUnion() << "volatile" 4278 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4279 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4280 Diag(DS.getRestrictSpecLoc(), 4281 diag::ext_anonymous_struct_union_qualified) 4282 << Record->isUnion() << "restrict" 4283 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4284 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4285 Diag(DS.getAtomicSpecLoc(), 4286 diag::ext_anonymous_struct_union_qualified) 4287 << Record->isUnion() << "_Atomic" 4288 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4289 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4290 Diag(DS.getUnalignedSpecLoc(), 4291 diag::ext_anonymous_struct_union_qualified) 4292 << Record->isUnion() << "__unaligned" 4293 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4294 4295 DS.ClearTypeQualifiers(); 4296 } 4297 4298 // C++ [class.union]p2: 4299 // The member-specification of an anonymous union shall only 4300 // define non-static data members. [Note: nested types and 4301 // functions cannot be declared within an anonymous union. ] 4302 for (auto *Mem : Record->decls()) { 4303 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4304 // C++ [class.union]p3: 4305 // An anonymous union shall not have private or protected 4306 // members (clause 11). 4307 assert(FD->getAccess() != AS_none); 4308 if (FD->getAccess() != AS_public) { 4309 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4310 << Record->isUnion() << (FD->getAccess() == AS_protected); 4311 Invalid = true; 4312 } 4313 4314 // C++ [class.union]p1 4315 // An object of a class with a non-trivial constructor, a non-trivial 4316 // copy constructor, a non-trivial destructor, or a non-trivial copy 4317 // assignment operator cannot be a member of a union, nor can an 4318 // array of such objects. 4319 if (CheckNontrivialField(FD)) 4320 Invalid = true; 4321 } else if (Mem->isImplicit()) { 4322 // Any implicit members are fine. 4323 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4324 // This is a type that showed up in an 4325 // elaborated-type-specifier inside the anonymous struct or 4326 // union, but which actually declares a type outside of the 4327 // anonymous struct or union. It's okay. 4328 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4329 if (!MemRecord->isAnonymousStructOrUnion() && 4330 MemRecord->getDeclName()) { 4331 // Visual C++ allows type definition in anonymous struct or union. 4332 if (getLangOpts().MicrosoftExt) 4333 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4334 << Record->isUnion(); 4335 else { 4336 // This is a nested type declaration. 4337 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4338 << Record->isUnion(); 4339 Invalid = true; 4340 } 4341 } else { 4342 // This is an anonymous type definition within another anonymous type. 4343 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4344 // not part of standard C++. 4345 Diag(MemRecord->getLocation(), 4346 diag::ext_anonymous_record_with_anonymous_type) 4347 << Record->isUnion(); 4348 } 4349 } else if (isa<AccessSpecDecl>(Mem)) { 4350 // Any access specifier is fine. 4351 } else if (isa<StaticAssertDecl>(Mem)) { 4352 // In C++1z, static_assert declarations are also fine. 4353 } else { 4354 // We have something that isn't a non-static data 4355 // member. Complain about it. 4356 unsigned DK = diag::err_anonymous_record_bad_member; 4357 if (isa<TypeDecl>(Mem)) 4358 DK = diag::err_anonymous_record_with_type; 4359 else if (isa<FunctionDecl>(Mem)) 4360 DK = diag::err_anonymous_record_with_function; 4361 else if (isa<VarDecl>(Mem)) 4362 DK = diag::err_anonymous_record_with_static; 4363 4364 // Visual C++ allows type definition in anonymous struct or union. 4365 if (getLangOpts().MicrosoftExt && 4366 DK == diag::err_anonymous_record_with_type) 4367 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4368 << Record->isUnion(); 4369 else { 4370 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4371 Invalid = true; 4372 } 4373 } 4374 } 4375 4376 // C++11 [class.union]p8 (DR1460): 4377 // At most one variant member of a union may have a 4378 // brace-or-equal-initializer. 4379 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4380 Owner->isRecord()) 4381 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4382 cast<CXXRecordDecl>(Record)); 4383 } 4384 4385 if (!Record->isUnion() && !Owner->isRecord()) { 4386 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4387 << getLangOpts().CPlusPlus; 4388 Invalid = true; 4389 } 4390 4391 // Mock up a declarator. 4392 Declarator Dc(DS, Declarator::MemberContext); 4393 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4394 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4395 4396 // Create a declaration for this anonymous struct/union. 4397 NamedDecl *Anon = nullptr; 4398 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4399 Anon = FieldDecl::Create(Context, OwningClass, 4400 DS.getLocStart(), 4401 Record->getLocation(), 4402 /*IdentifierInfo=*/nullptr, 4403 Context.getTypeDeclType(Record), 4404 TInfo, 4405 /*BitWidth=*/nullptr, /*Mutable=*/false, 4406 /*InitStyle=*/ICIS_NoInit); 4407 Anon->setAccess(AS); 4408 if (getLangOpts().CPlusPlus) 4409 FieldCollector->Add(cast<FieldDecl>(Anon)); 4410 } else { 4411 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4412 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4413 if (SCSpec == DeclSpec::SCS_mutable) { 4414 // mutable can only appear on non-static class members, so it's always 4415 // an error here 4416 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4417 Invalid = true; 4418 SC = SC_None; 4419 } 4420 4421 Anon = VarDecl::Create(Context, Owner, 4422 DS.getLocStart(), 4423 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4424 Context.getTypeDeclType(Record), 4425 TInfo, SC); 4426 4427 // Default-initialize the implicit variable. This initialization will be 4428 // trivial in almost all cases, except if a union member has an in-class 4429 // initializer: 4430 // union { int n = 0; }; 4431 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4432 } 4433 Anon->setImplicit(); 4434 4435 // Mark this as an anonymous struct/union type. 4436 Record->setAnonymousStructOrUnion(true); 4437 4438 // Add the anonymous struct/union object to the current 4439 // context. We'll be referencing this object when we refer to one of 4440 // its members. 4441 Owner->addDecl(Anon); 4442 4443 // Inject the members of the anonymous struct/union into the owning 4444 // context and into the identifier resolver chain for name lookup 4445 // purposes. 4446 SmallVector<NamedDecl*, 2> Chain; 4447 Chain.push_back(Anon); 4448 4449 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4450 Invalid = true; 4451 4452 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4453 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4454 Decl *ManglingContextDecl; 4455 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4456 NewVD->getDeclContext(), ManglingContextDecl)) { 4457 Context.setManglingNumber( 4458 NewVD, MCtx->getManglingNumber( 4459 NewVD, getMSManglingNumber(getLangOpts(), S))); 4460 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4461 } 4462 } 4463 } 4464 4465 if (Invalid) 4466 Anon->setInvalidDecl(); 4467 4468 return Anon; 4469 } 4470 4471 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4472 /// Microsoft C anonymous structure. 4473 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4474 /// Example: 4475 /// 4476 /// struct A { int a; }; 4477 /// struct B { struct A; int b; }; 4478 /// 4479 /// void foo() { 4480 /// B var; 4481 /// var.a = 3; 4482 /// } 4483 /// 4484 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4485 RecordDecl *Record) { 4486 assert(Record && "expected a record!"); 4487 4488 // Mock up a declarator. 4489 Declarator Dc(DS, Declarator::TypeNameContext); 4490 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4491 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4492 4493 auto *ParentDecl = cast<RecordDecl>(CurContext); 4494 QualType RecTy = Context.getTypeDeclType(Record); 4495 4496 // Create a declaration for this anonymous struct. 4497 NamedDecl *Anon = FieldDecl::Create(Context, 4498 ParentDecl, 4499 DS.getLocStart(), 4500 DS.getLocStart(), 4501 /*IdentifierInfo=*/nullptr, 4502 RecTy, 4503 TInfo, 4504 /*BitWidth=*/nullptr, /*Mutable=*/false, 4505 /*InitStyle=*/ICIS_NoInit); 4506 Anon->setImplicit(); 4507 4508 // Add the anonymous struct object to the current context. 4509 CurContext->addDecl(Anon); 4510 4511 // Inject the members of the anonymous struct into the current 4512 // context and into the identifier resolver chain for name lookup 4513 // purposes. 4514 SmallVector<NamedDecl*, 2> Chain; 4515 Chain.push_back(Anon); 4516 4517 RecordDecl *RecordDef = Record->getDefinition(); 4518 if (RequireCompleteType(Anon->getLocation(), RecTy, 4519 diag::err_field_incomplete) || 4520 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4521 AS_none, Chain)) { 4522 Anon->setInvalidDecl(); 4523 ParentDecl->setInvalidDecl(); 4524 } 4525 4526 return Anon; 4527 } 4528 4529 /// GetNameForDeclarator - Determine the full declaration name for the 4530 /// given Declarator. 4531 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4532 return GetNameFromUnqualifiedId(D.getName()); 4533 } 4534 4535 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4536 DeclarationNameInfo 4537 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4538 DeclarationNameInfo NameInfo; 4539 NameInfo.setLoc(Name.StartLocation); 4540 4541 switch (Name.getKind()) { 4542 4543 case UnqualifiedId::IK_ImplicitSelfParam: 4544 case UnqualifiedId::IK_Identifier: 4545 NameInfo.setName(Name.Identifier); 4546 NameInfo.setLoc(Name.StartLocation); 4547 return NameInfo; 4548 4549 case UnqualifiedId::IK_OperatorFunctionId: 4550 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4551 Name.OperatorFunctionId.Operator)); 4552 NameInfo.setLoc(Name.StartLocation); 4553 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4554 = Name.OperatorFunctionId.SymbolLocations[0]; 4555 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4556 = Name.EndLocation.getRawEncoding(); 4557 return NameInfo; 4558 4559 case UnqualifiedId::IK_LiteralOperatorId: 4560 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4561 Name.Identifier)); 4562 NameInfo.setLoc(Name.StartLocation); 4563 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4564 return NameInfo; 4565 4566 case UnqualifiedId::IK_ConversionFunctionId: { 4567 TypeSourceInfo *TInfo; 4568 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4569 if (Ty.isNull()) 4570 return DeclarationNameInfo(); 4571 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4572 Context.getCanonicalType(Ty))); 4573 NameInfo.setLoc(Name.StartLocation); 4574 NameInfo.setNamedTypeInfo(TInfo); 4575 return NameInfo; 4576 } 4577 4578 case UnqualifiedId::IK_ConstructorName: { 4579 TypeSourceInfo *TInfo; 4580 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4581 if (Ty.isNull()) 4582 return DeclarationNameInfo(); 4583 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4584 Context.getCanonicalType(Ty))); 4585 NameInfo.setLoc(Name.StartLocation); 4586 NameInfo.setNamedTypeInfo(TInfo); 4587 return NameInfo; 4588 } 4589 4590 case UnqualifiedId::IK_ConstructorTemplateId: { 4591 // In well-formed code, we can only have a constructor 4592 // template-id that refers to the current context, so go there 4593 // to find the actual type being constructed. 4594 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4595 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4596 return DeclarationNameInfo(); 4597 4598 // Determine the type of the class being constructed. 4599 QualType CurClassType = Context.getTypeDeclType(CurClass); 4600 4601 // FIXME: Check two things: that the template-id names the same type as 4602 // CurClassType, and that the template-id does not occur when the name 4603 // was qualified. 4604 4605 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4606 Context.getCanonicalType(CurClassType))); 4607 NameInfo.setLoc(Name.StartLocation); 4608 // FIXME: should we retrieve TypeSourceInfo? 4609 NameInfo.setNamedTypeInfo(nullptr); 4610 return NameInfo; 4611 } 4612 4613 case UnqualifiedId::IK_DestructorName: { 4614 TypeSourceInfo *TInfo; 4615 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4616 if (Ty.isNull()) 4617 return DeclarationNameInfo(); 4618 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4619 Context.getCanonicalType(Ty))); 4620 NameInfo.setLoc(Name.StartLocation); 4621 NameInfo.setNamedTypeInfo(TInfo); 4622 return NameInfo; 4623 } 4624 4625 case UnqualifiedId::IK_TemplateId: { 4626 TemplateName TName = Name.TemplateId->Template.get(); 4627 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4628 return Context.getNameForTemplate(TName, TNameLoc); 4629 } 4630 4631 } // switch (Name.getKind()) 4632 4633 llvm_unreachable("Unknown name kind"); 4634 } 4635 4636 static QualType getCoreType(QualType Ty) { 4637 do { 4638 if (Ty->isPointerType() || Ty->isReferenceType()) 4639 Ty = Ty->getPointeeType(); 4640 else if (Ty->isArrayType()) 4641 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4642 else 4643 return Ty.withoutLocalFastQualifiers(); 4644 } while (true); 4645 } 4646 4647 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4648 /// and Definition have "nearly" matching parameters. This heuristic is 4649 /// used to improve diagnostics in the case where an out-of-line function 4650 /// definition doesn't match any declaration within the class or namespace. 4651 /// Also sets Params to the list of indices to the parameters that differ 4652 /// between the declaration and the definition. If hasSimilarParameters 4653 /// returns true and Params is empty, then all of the parameters match. 4654 static bool hasSimilarParameters(ASTContext &Context, 4655 FunctionDecl *Declaration, 4656 FunctionDecl *Definition, 4657 SmallVectorImpl<unsigned> &Params) { 4658 Params.clear(); 4659 if (Declaration->param_size() != Definition->param_size()) 4660 return false; 4661 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4662 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4663 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4664 4665 // The parameter types are identical 4666 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4667 continue; 4668 4669 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4670 QualType DefParamBaseTy = getCoreType(DefParamTy); 4671 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4672 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4673 4674 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4675 (DeclTyName && DeclTyName == DefTyName)) 4676 Params.push_back(Idx); 4677 else // The two parameters aren't even close 4678 return false; 4679 } 4680 4681 return true; 4682 } 4683 4684 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4685 /// declarator needs to be rebuilt in the current instantiation. 4686 /// Any bits of declarator which appear before the name are valid for 4687 /// consideration here. That's specifically the type in the decl spec 4688 /// and the base type in any member-pointer chunks. 4689 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4690 DeclarationName Name) { 4691 // The types we specifically need to rebuild are: 4692 // - typenames, typeofs, and decltypes 4693 // - types which will become injected class names 4694 // Of course, we also need to rebuild any type referencing such a 4695 // type. It's safest to just say "dependent", but we call out a 4696 // few cases here. 4697 4698 DeclSpec &DS = D.getMutableDeclSpec(); 4699 switch (DS.getTypeSpecType()) { 4700 case DeclSpec::TST_typename: 4701 case DeclSpec::TST_typeofType: 4702 case DeclSpec::TST_underlyingType: 4703 case DeclSpec::TST_atomic: { 4704 // Grab the type from the parser. 4705 TypeSourceInfo *TSI = nullptr; 4706 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4707 if (T.isNull() || !T->isDependentType()) break; 4708 4709 // Make sure there's a type source info. This isn't really much 4710 // of a waste; most dependent types should have type source info 4711 // attached already. 4712 if (!TSI) 4713 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4714 4715 // Rebuild the type in the current instantiation. 4716 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4717 if (!TSI) return true; 4718 4719 // Store the new type back in the decl spec. 4720 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4721 DS.UpdateTypeRep(LocType); 4722 break; 4723 } 4724 4725 case DeclSpec::TST_decltype: 4726 case DeclSpec::TST_typeofExpr: { 4727 Expr *E = DS.getRepAsExpr(); 4728 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4729 if (Result.isInvalid()) return true; 4730 DS.UpdateExprRep(Result.get()); 4731 break; 4732 } 4733 4734 default: 4735 // Nothing to do for these decl specs. 4736 break; 4737 } 4738 4739 // It doesn't matter what order we do this in. 4740 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4741 DeclaratorChunk &Chunk = D.getTypeObject(I); 4742 4743 // The only type information in the declarator which can come 4744 // before the declaration name is the base type of a member 4745 // pointer. 4746 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4747 continue; 4748 4749 // Rebuild the scope specifier in-place. 4750 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4751 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4752 return true; 4753 } 4754 4755 return false; 4756 } 4757 4758 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4759 D.setFunctionDefinitionKind(FDK_Declaration); 4760 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4761 4762 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4763 Dcl && Dcl->getDeclContext()->isFileContext()) 4764 Dcl->setTopLevelDeclInObjCContainer(); 4765 4766 return Dcl; 4767 } 4768 4769 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4770 /// If T is the name of a class, then each of the following shall have a 4771 /// name different from T: 4772 /// - every static data member of class T; 4773 /// - every member function of class T 4774 /// - every member of class T that is itself a type; 4775 /// \returns true if the declaration name violates these rules. 4776 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4777 DeclarationNameInfo NameInfo) { 4778 DeclarationName Name = NameInfo.getName(); 4779 4780 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4781 while (Record && Record->isAnonymousStructOrUnion()) 4782 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4783 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4784 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4785 return true; 4786 } 4787 4788 return false; 4789 } 4790 4791 /// \brief Diagnose a declaration whose declarator-id has the given 4792 /// nested-name-specifier. 4793 /// 4794 /// \param SS The nested-name-specifier of the declarator-id. 4795 /// 4796 /// \param DC The declaration context to which the nested-name-specifier 4797 /// resolves. 4798 /// 4799 /// \param Name The name of the entity being declared. 4800 /// 4801 /// \param Loc The location of the name of the entity being declared. 4802 /// 4803 /// \returns true if we cannot safely recover from this error, false otherwise. 4804 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4805 DeclarationName Name, 4806 SourceLocation Loc) { 4807 DeclContext *Cur = CurContext; 4808 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4809 Cur = Cur->getParent(); 4810 4811 // If the user provided a superfluous scope specifier that refers back to the 4812 // class in which the entity is already declared, diagnose and ignore it. 4813 // 4814 // class X { 4815 // void X::f(); 4816 // }; 4817 // 4818 // Note, it was once ill-formed to give redundant qualification in all 4819 // contexts, but that rule was removed by DR482. 4820 if (Cur->Equals(DC)) { 4821 if (Cur->isRecord()) { 4822 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4823 : diag::err_member_extra_qualification) 4824 << Name << FixItHint::CreateRemoval(SS.getRange()); 4825 SS.clear(); 4826 } else { 4827 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4828 } 4829 return false; 4830 } 4831 4832 // Check whether the qualifying scope encloses the scope of the original 4833 // declaration. 4834 if (!Cur->Encloses(DC)) { 4835 if (Cur->isRecord()) 4836 Diag(Loc, diag::err_member_qualification) 4837 << Name << SS.getRange(); 4838 else if (isa<TranslationUnitDecl>(DC)) 4839 Diag(Loc, diag::err_invalid_declarator_global_scope) 4840 << Name << SS.getRange(); 4841 else if (isa<FunctionDecl>(Cur)) 4842 Diag(Loc, diag::err_invalid_declarator_in_function) 4843 << Name << SS.getRange(); 4844 else if (isa<BlockDecl>(Cur)) 4845 Diag(Loc, diag::err_invalid_declarator_in_block) 4846 << Name << SS.getRange(); 4847 else 4848 Diag(Loc, diag::err_invalid_declarator_scope) 4849 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4850 4851 return true; 4852 } 4853 4854 if (Cur->isRecord()) { 4855 // Cannot qualify members within a class. 4856 Diag(Loc, diag::err_member_qualification) 4857 << Name << SS.getRange(); 4858 SS.clear(); 4859 4860 // C++ constructors and destructors with incorrect scopes can break 4861 // our AST invariants by having the wrong underlying types. If 4862 // that's the case, then drop this declaration entirely. 4863 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4864 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4865 !Context.hasSameType(Name.getCXXNameType(), 4866 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4867 return true; 4868 4869 return false; 4870 } 4871 4872 // C++11 [dcl.meaning]p1: 4873 // [...] "The nested-name-specifier of the qualified declarator-id shall 4874 // not begin with a decltype-specifer" 4875 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4876 while (SpecLoc.getPrefix()) 4877 SpecLoc = SpecLoc.getPrefix(); 4878 if (dyn_cast_or_null<DecltypeType>( 4879 SpecLoc.getNestedNameSpecifier()->getAsType())) 4880 Diag(Loc, diag::err_decltype_in_declarator) 4881 << SpecLoc.getTypeLoc().getSourceRange(); 4882 4883 return false; 4884 } 4885 4886 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4887 MultiTemplateParamsArg TemplateParamLists) { 4888 // TODO: consider using NameInfo for diagnostic. 4889 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4890 DeclarationName Name = NameInfo.getName(); 4891 4892 // All of these full declarators require an identifier. If it doesn't have 4893 // one, the ParsedFreeStandingDeclSpec action should be used. 4894 if (!Name) { 4895 if (!D.isInvalidType()) // Reject this if we think it is valid. 4896 Diag(D.getDeclSpec().getLocStart(), 4897 diag::err_declarator_need_ident) 4898 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4899 return nullptr; 4900 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4901 return nullptr; 4902 4903 // The scope passed in may not be a decl scope. Zip up the scope tree until 4904 // we find one that is. 4905 while ((S->getFlags() & Scope::DeclScope) == 0 || 4906 (S->getFlags() & Scope::TemplateParamScope) != 0) 4907 S = S->getParent(); 4908 4909 DeclContext *DC = CurContext; 4910 if (D.getCXXScopeSpec().isInvalid()) 4911 D.setInvalidType(); 4912 else if (D.getCXXScopeSpec().isSet()) { 4913 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4914 UPPC_DeclarationQualifier)) 4915 return nullptr; 4916 4917 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4918 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4919 if (!DC || isa<EnumDecl>(DC)) { 4920 // If we could not compute the declaration context, it's because the 4921 // declaration context is dependent but does not refer to a class, 4922 // class template, or class template partial specialization. Complain 4923 // and return early, to avoid the coming semantic disaster. 4924 Diag(D.getIdentifierLoc(), 4925 diag::err_template_qualified_declarator_no_match) 4926 << D.getCXXScopeSpec().getScopeRep() 4927 << D.getCXXScopeSpec().getRange(); 4928 return nullptr; 4929 } 4930 bool IsDependentContext = DC->isDependentContext(); 4931 4932 if (!IsDependentContext && 4933 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4934 return nullptr; 4935 4936 // If a class is incomplete, do not parse entities inside it. 4937 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4938 Diag(D.getIdentifierLoc(), 4939 diag::err_member_def_undefined_record) 4940 << Name << DC << D.getCXXScopeSpec().getRange(); 4941 return nullptr; 4942 } 4943 if (!D.getDeclSpec().isFriendSpecified()) { 4944 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4945 Name, D.getIdentifierLoc())) { 4946 if (DC->isRecord()) 4947 return nullptr; 4948 4949 D.setInvalidType(); 4950 } 4951 } 4952 4953 // Check whether we need to rebuild the type of the given 4954 // declaration in the current instantiation. 4955 if (EnteringContext && IsDependentContext && 4956 TemplateParamLists.size() != 0) { 4957 ContextRAII SavedContext(*this, DC); 4958 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4959 D.setInvalidType(); 4960 } 4961 } 4962 4963 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4964 QualType R = TInfo->getType(); 4965 4966 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 4967 // If this is a typedef, we'll end up spewing multiple diagnostics. 4968 // Just return early; it's safer. If this is a function, let the 4969 // "constructor cannot have a return type" diagnostic handle it. 4970 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4971 return nullptr; 4972 4973 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4974 UPPC_DeclarationType)) 4975 D.setInvalidType(); 4976 4977 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4978 ForRedeclaration); 4979 4980 // See if this is a redefinition of a variable in the same scope. 4981 if (!D.getCXXScopeSpec().isSet()) { 4982 bool IsLinkageLookup = false; 4983 bool CreateBuiltins = false; 4984 4985 // If the declaration we're planning to build will be a function 4986 // or object with linkage, then look for another declaration with 4987 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4988 // 4989 // If the declaration we're planning to build will be declared with 4990 // external linkage in the translation unit, create any builtin with 4991 // the same name. 4992 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4993 /* Do nothing*/; 4994 else if (CurContext->isFunctionOrMethod() && 4995 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4996 R->isFunctionType())) { 4997 IsLinkageLookup = true; 4998 CreateBuiltins = 4999 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5000 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5001 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5002 CreateBuiltins = true; 5003 5004 if (IsLinkageLookup) 5005 Previous.clear(LookupRedeclarationWithLinkage); 5006 5007 LookupName(Previous, S, CreateBuiltins); 5008 } else { // Something like "int foo::x;" 5009 LookupQualifiedName(Previous, DC); 5010 5011 // C++ [dcl.meaning]p1: 5012 // When the declarator-id is qualified, the declaration shall refer to a 5013 // previously declared member of the class or namespace to which the 5014 // qualifier refers (or, in the case of a namespace, of an element of the 5015 // inline namespace set of that namespace (7.3.1)) or to a specialization 5016 // thereof; [...] 5017 // 5018 // Note that we already checked the context above, and that we do not have 5019 // enough information to make sure that Previous contains the declaration 5020 // we want to match. For example, given: 5021 // 5022 // class X { 5023 // void f(); 5024 // void f(float); 5025 // }; 5026 // 5027 // void X::f(int) { } // ill-formed 5028 // 5029 // In this case, Previous will point to the overload set 5030 // containing the two f's declared in X, but neither of them 5031 // matches. 5032 5033 // C++ [dcl.meaning]p1: 5034 // [...] the member shall not merely have been introduced by a 5035 // using-declaration in the scope of the class or namespace nominated by 5036 // the nested-name-specifier of the declarator-id. 5037 RemoveUsingDecls(Previous); 5038 } 5039 5040 if (Previous.isSingleResult() && 5041 Previous.getFoundDecl()->isTemplateParameter()) { 5042 // Maybe we will complain about the shadowed template parameter. 5043 if (!D.isInvalidType()) 5044 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5045 Previous.getFoundDecl()); 5046 5047 // Just pretend that we didn't see the previous declaration. 5048 Previous.clear(); 5049 } 5050 5051 // In C++, the previous declaration we find might be a tag type 5052 // (class or enum). In this case, the new declaration will hide the 5053 // tag type. Note that this does does not apply if we're declaring a 5054 // typedef (C++ [dcl.typedef]p4). 5055 if (Previous.isSingleTagDecl() && 5056 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5057 Previous.clear(); 5058 5059 // Check that there are no default arguments other than in the parameters 5060 // of a function declaration (C++ only). 5061 if (getLangOpts().CPlusPlus) 5062 CheckExtraCXXDefaultArguments(D); 5063 5064 if (D.getDeclSpec().isConceptSpecified()) { 5065 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5066 // applied only to the definition of a function template or variable 5067 // template, declared in namespace scope 5068 if (!TemplateParamLists.size()) { 5069 Diag(D.getDeclSpec().getConceptSpecLoc(), 5070 diag:: err_concept_wrong_decl_kind); 5071 return nullptr; 5072 } 5073 5074 if (!DC->getRedeclContext()->isFileContext()) { 5075 Diag(D.getIdentifierLoc(), 5076 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5077 return nullptr; 5078 } 5079 } 5080 5081 NamedDecl *New; 5082 5083 bool AddToScope = true; 5084 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5085 if (TemplateParamLists.size()) { 5086 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5087 return nullptr; 5088 } 5089 5090 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5091 } else if (R->isFunctionType()) { 5092 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5093 TemplateParamLists, 5094 AddToScope); 5095 } else { 5096 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5097 AddToScope); 5098 } 5099 5100 if (!New) 5101 return nullptr; 5102 5103 // If this has an identifier and is not an invalid redeclaration or 5104 // function template specialization, add it to the scope stack. 5105 if (New->getDeclName() && AddToScope && 5106 !(D.isRedeclaration() && New->isInvalidDecl())) { 5107 // Only make a locally-scoped extern declaration visible if it is the first 5108 // declaration of this entity. Qualified lookup for such an entity should 5109 // only find this declaration if there is no visible declaration of it. 5110 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5111 PushOnScopeChains(New, S, AddToContext); 5112 if (!AddToContext) 5113 CurContext->addHiddenDecl(New); 5114 } 5115 5116 if (isInOpenMPDeclareTargetContext()) 5117 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5118 5119 return New; 5120 } 5121 5122 /// Helper method to turn variable array types into constant array 5123 /// types in certain situations which would otherwise be errors (for 5124 /// GCC compatibility). 5125 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5126 ASTContext &Context, 5127 bool &SizeIsNegative, 5128 llvm::APSInt &Oversized) { 5129 // This method tries to turn a variable array into a constant 5130 // array even when the size isn't an ICE. This is necessary 5131 // for compatibility with code that depends on gcc's buggy 5132 // constant expression folding, like struct {char x[(int)(char*)2];} 5133 SizeIsNegative = false; 5134 Oversized = 0; 5135 5136 if (T->isDependentType()) 5137 return QualType(); 5138 5139 QualifierCollector Qs; 5140 const Type *Ty = Qs.strip(T); 5141 5142 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5143 QualType Pointee = PTy->getPointeeType(); 5144 QualType FixedType = 5145 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5146 Oversized); 5147 if (FixedType.isNull()) return FixedType; 5148 FixedType = Context.getPointerType(FixedType); 5149 return Qs.apply(Context, FixedType); 5150 } 5151 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5152 QualType Inner = PTy->getInnerType(); 5153 QualType FixedType = 5154 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5155 Oversized); 5156 if (FixedType.isNull()) return FixedType; 5157 FixedType = Context.getParenType(FixedType); 5158 return Qs.apply(Context, FixedType); 5159 } 5160 5161 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5162 if (!VLATy) 5163 return QualType(); 5164 // FIXME: We should probably handle this case 5165 if (VLATy->getElementType()->isVariablyModifiedType()) 5166 return QualType(); 5167 5168 llvm::APSInt Res; 5169 if (!VLATy->getSizeExpr() || 5170 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5171 return QualType(); 5172 5173 // Check whether the array size is negative. 5174 if (Res.isSigned() && Res.isNegative()) { 5175 SizeIsNegative = true; 5176 return QualType(); 5177 } 5178 5179 // Check whether the array is too large to be addressed. 5180 unsigned ActiveSizeBits 5181 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5182 Res); 5183 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5184 Oversized = Res; 5185 return QualType(); 5186 } 5187 5188 return Context.getConstantArrayType(VLATy->getElementType(), 5189 Res, ArrayType::Normal, 0); 5190 } 5191 5192 static void 5193 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5194 SrcTL = SrcTL.getUnqualifiedLoc(); 5195 DstTL = DstTL.getUnqualifiedLoc(); 5196 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5197 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5198 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5199 DstPTL.getPointeeLoc()); 5200 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5201 return; 5202 } 5203 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5204 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5205 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5206 DstPTL.getInnerLoc()); 5207 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5208 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5209 return; 5210 } 5211 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5212 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5213 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5214 TypeLoc DstElemTL = DstATL.getElementLoc(); 5215 DstElemTL.initializeFullCopy(SrcElemTL); 5216 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5217 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5218 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5219 } 5220 5221 /// Helper method to turn variable array types into constant array 5222 /// types in certain situations which would otherwise be errors (for 5223 /// GCC compatibility). 5224 static TypeSourceInfo* 5225 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5226 ASTContext &Context, 5227 bool &SizeIsNegative, 5228 llvm::APSInt &Oversized) { 5229 QualType FixedTy 5230 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5231 SizeIsNegative, Oversized); 5232 if (FixedTy.isNull()) 5233 return nullptr; 5234 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5235 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5236 FixedTInfo->getTypeLoc()); 5237 return FixedTInfo; 5238 } 5239 5240 /// \brief Register the given locally-scoped extern "C" declaration so 5241 /// that it can be found later for redeclarations. We include any extern "C" 5242 /// declaration that is not visible in the translation unit here, not just 5243 /// function-scope declarations. 5244 void 5245 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5246 if (!getLangOpts().CPlusPlus && 5247 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5248 // Don't need to track declarations in the TU in C. 5249 return; 5250 5251 // Note that we have a locally-scoped external with this name. 5252 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5253 } 5254 5255 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5256 // FIXME: We can have multiple results via __attribute__((overloadable)). 5257 auto Result = Context.getExternCContextDecl()->lookup(Name); 5258 return Result.empty() ? nullptr : *Result.begin(); 5259 } 5260 5261 /// \brief Diagnose function specifiers on a declaration of an identifier that 5262 /// does not identify a function. 5263 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5264 // FIXME: We should probably indicate the identifier in question to avoid 5265 // confusion for constructs like "inline int a(), b;" 5266 if (DS.isInlineSpecified()) 5267 Diag(DS.getInlineSpecLoc(), 5268 diag::err_inline_non_function); 5269 5270 if (DS.isVirtualSpecified()) 5271 Diag(DS.getVirtualSpecLoc(), 5272 diag::err_virtual_non_function); 5273 5274 if (DS.isExplicitSpecified()) 5275 Diag(DS.getExplicitSpecLoc(), 5276 diag::err_explicit_non_function); 5277 5278 if (DS.isNoreturnSpecified()) 5279 Diag(DS.getNoreturnSpecLoc(), 5280 diag::err_noreturn_non_function); 5281 } 5282 5283 NamedDecl* 5284 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5285 TypeSourceInfo *TInfo, LookupResult &Previous) { 5286 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5287 if (D.getCXXScopeSpec().isSet()) { 5288 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5289 << D.getCXXScopeSpec().getRange(); 5290 D.setInvalidType(); 5291 // Pretend we didn't see the scope specifier. 5292 DC = CurContext; 5293 Previous.clear(); 5294 } 5295 5296 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5297 5298 if (D.getDeclSpec().isConstexprSpecified()) 5299 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5300 << 1; 5301 if (D.getDeclSpec().isConceptSpecified()) 5302 Diag(D.getDeclSpec().getConceptSpecLoc(), 5303 diag::err_concept_wrong_decl_kind); 5304 5305 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5306 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5307 << D.getName().getSourceRange(); 5308 return nullptr; 5309 } 5310 5311 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5312 if (!NewTD) return nullptr; 5313 5314 // Handle attributes prior to checking for duplicates in MergeVarDecl 5315 ProcessDeclAttributes(S, NewTD, D); 5316 5317 CheckTypedefForVariablyModifiedType(S, NewTD); 5318 5319 bool Redeclaration = D.isRedeclaration(); 5320 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5321 D.setRedeclaration(Redeclaration); 5322 return ND; 5323 } 5324 5325 void 5326 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5327 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5328 // then it shall have block scope. 5329 // Note that variably modified types must be fixed before merging the decl so 5330 // that redeclarations will match. 5331 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5332 QualType T = TInfo->getType(); 5333 if (T->isVariablyModifiedType()) { 5334 getCurFunction()->setHasBranchProtectedScope(); 5335 5336 if (S->getFnParent() == nullptr) { 5337 bool SizeIsNegative; 5338 llvm::APSInt Oversized; 5339 TypeSourceInfo *FixedTInfo = 5340 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5341 SizeIsNegative, 5342 Oversized); 5343 if (FixedTInfo) { 5344 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5345 NewTD->setTypeSourceInfo(FixedTInfo); 5346 } else { 5347 if (SizeIsNegative) 5348 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5349 else if (T->isVariableArrayType()) 5350 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5351 else if (Oversized.getBoolValue()) 5352 Diag(NewTD->getLocation(), diag::err_array_too_large) 5353 << Oversized.toString(10); 5354 else 5355 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5356 NewTD->setInvalidDecl(); 5357 } 5358 } 5359 } 5360 } 5361 5362 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5363 /// declares a typedef-name, either using the 'typedef' type specifier or via 5364 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5365 NamedDecl* 5366 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5367 LookupResult &Previous, bool &Redeclaration) { 5368 // Merge the decl with the existing one if appropriate. If the decl is 5369 // in an outer scope, it isn't the same thing. 5370 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5371 /*AllowInlineNamespace*/false); 5372 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5373 if (!Previous.empty()) { 5374 Redeclaration = true; 5375 MergeTypedefNameDecl(S, NewTD, Previous); 5376 } 5377 5378 // If this is the C FILE type, notify the AST context. 5379 if (IdentifierInfo *II = NewTD->getIdentifier()) 5380 if (!NewTD->isInvalidDecl() && 5381 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5382 if (II->isStr("FILE")) 5383 Context.setFILEDecl(NewTD); 5384 else if (II->isStr("jmp_buf")) 5385 Context.setjmp_bufDecl(NewTD); 5386 else if (II->isStr("sigjmp_buf")) 5387 Context.setsigjmp_bufDecl(NewTD); 5388 else if (II->isStr("ucontext_t")) 5389 Context.setucontext_tDecl(NewTD); 5390 } 5391 5392 return NewTD; 5393 } 5394 5395 /// \brief Determines whether the given declaration is an out-of-scope 5396 /// previous declaration. 5397 /// 5398 /// This routine should be invoked when name lookup has found a 5399 /// previous declaration (PrevDecl) that is not in the scope where a 5400 /// new declaration by the same name is being introduced. If the new 5401 /// declaration occurs in a local scope, previous declarations with 5402 /// linkage may still be considered previous declarations (C99 5403 /// 6.2.2p4-5, C++ [basic.link]p6). 5404 /// 5405 /// \param PrevDecl the previous declaration found by name 5406 /// lookup 5407 /// 5408 /// \param DC the context in which the new declaration is being 5409 /// declared. 5410 /// 5411 /// \returns true if PrevDecl is an out-of-scope previous declaration 5412 /// for a new delcaration with the same name. 5413 static bool 5414 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5415 ASTContext &Context) { 5416 if (!PrevDecl) 5417 return false; 5418 5419 if (!PrevDecl->hasLinkage()) 5420 return false; 5421 5422 if (Context.getLangOpts().CPlusPlus) { 5423 // C++ [basic.link]p6: 5424 // If there is a visible declaration of an entity with linkage 5425 // having the same name and type, ignoring entities declared 5426 // outside the innermost enclosing namespace scope, the block 5427 // scope declaration declares that same entity and receives the 5428 // linkage of the previous declaration. 5429 DeclContext *OuterContext = DC->getRedeclContext(); 5430 if (!OuterContext->isFunctionOrMethod()) 5431 // This rule only applies to block-scope declarations. 5432 return false; 5433 5434 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5435 if (PrevOuterContext->isRecord()) 5436 // We found a member function: ignore it. 5437 return false; 5438 5439 // Find the innermost enclosing namespace for the new and 5440 // previous declarations. 5441 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5442 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5443 5444 // The previous declaration is in a different namespace, so it 5445 // isn't the same function. 5446 if (!OuterContext->Equals(PrevOuterContext)) 5447 return false; 5448 } 5449 5450 return true; 5451 } 5452 5453 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5454 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5455 if (!SS.isSet()) return; 5456 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5457 } 5458 5459 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5460 QualType type = decl->getType(); 5461 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5462 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5463 // Various kinds of declaration aren't allowed to be __autoreleasing. 5464 unsigned kind = -1U; 5465 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5466 if (var->hasAttr<BlocksAttr>()) 5467 kind = 0; // __block 5468 else if (!var->hasLocalStorage()) 5469 kind = 1; // global 5470 } else if (isa<ObjCIvarDecl>(decl)) { 5471 kind = 3; // ivar 5472 } else if (isa<FieldDecl>(decl)) { 5473 kind = 2; // field 5474 } 5475 5476 if (kind != -1U) { 5477 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5478 << kind; 5479 } 5480 } else if (lifetime == Qualifiers::OCL_None) { 5481 // Try to infer lifetime. 5482 if (!type->isObjCLifetimeType()) 5483 return false; 5484 5485 lifetime = type->getObjCARCImplicitLifetime(); 5486 type = Context.getLifetimeQualifiedType(type, lifetime); 5487 decl->setType(type); 5488 } 5489 5490 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5491 // Thread-local variables cannot have lifetime. 5492 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5493 var->getTLSKind()) { 5494 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5495 << var->getType(); 5496 return true; 5497 } 5498 } 5499 5500 return false; 5501 } 5502 5503 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5504 // Ensure that an auto decl is deduced otherwise the checks below might cache 5505 // the wrong linkage. 5506 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5507 5508 // 'weak' only applies to declarations with external linkage. 5509 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5510 if (!ND.isExternallyVisible()) { 5511 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5512 ND.dropAttr<WeakAttr>(); 5513 } 5514 } 5515 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5516 if (ND.isExternallyVisible()) { 5517 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5518 ND.dropAttr<WeakRefAttr>(); 5519 ND.dropAttr<AliasAttr>(); 5520 } 5521 } 5522 5523 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5524 if (VD->hasInit()) { 5525 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5526 assert(VD->isThisDeclarationADefinition() && 5527 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5528 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5529 VD->dropAttr<AliasAttr>(); 5530 } 5531 } 5532 } 5533 5534 // 'selectany' only applies to externally visible variable declarations. 5535 // It does not apply to functions. 5536 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5537 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5538 S.Diag(Attr->getLocation(), 5539 diag::err_attribute_selectany_non_extern_data); 5540 ND.dropAttr<SelectAnyAttr>(); 5541 } 5542 } 5543 5544 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5545 // dll attributes require external linkage. Static locals may have external 5546 // linkage but still cannot be explicitly imported or exported. 5547 auto *VD = dyn_cast<VarDecl>(&ND); 5548 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5549 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5550 << &ND << Attr; 5551 ND.setInvalidDecl(); 5552 } 5553 } 5554 5555 // Virtual functions cannot be marked as 'notail'. 5556 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5557 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5558 if (MD->isVirtual()) { 5559 S.Diag(ND.getLocation(), 5560 diag::err_invalid_attribute_on_virtual_function) 5561 << Attr; 5562 ND.dropAttr<NotTailCalledAttr>(); 5563 } 5564 } 5565 5566 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5567 NamedDecl *NewDecl, 5568 bool IsSpecialization, 5569 bool IsDefinition) { 5570 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5571 OldDecl = OldTD->getTemplatedDecl(); 5572 if (!IsSpecialization) 5573 IsDefinition = false; 5574 } 5575 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5576 NewDecl = NewTD->getTemplatedDecl(); 5577 5578 if (!OldDecl || !NewDecl) 5579 return; 5580 5581 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5582 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5583 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5584 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5585 5586 // dllimport and dllexport are inheritable attributes so we have to exclude 5587 // inherited attribute instances. 5588 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5589 (NewExportAttr && !NewExportAttr->isInherited()); 5590 5591 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5592 // the only exception being explicit specializations. 5593 // Implicitly generated declarations are also excluded for now because there 5594 // is no other way to switch these to use dllimport or dllexport. 5595 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5596 5597 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5598 // Allow with a warning for free functions and global variables. 5599 bool JustWarn = false; 5600 if (!OldDecl->isCXXClassMember()) { 5601 auto *VD = dyn_cast<VarDecl>(OldDecl); 5602 if (VD && !VD->getDescribedVarTemplate()) 5603 JustWarn = true; 5604 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5605 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5606 JustWarn = true; 5607 } 5608 5609 // We cannot change a declaration that's been used because IR has already 5610 // been emitted. Dllimported functions will still work though (modulo 5611 // address equality) as they can use the thunk. 5612 if (OldDecl->isUsed()) 5613 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5614 JustWarn = false; 5615 5616 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5617 : diag::err_attribute_dll_redeclaration; 5618 S.Diag(NewDecl->getLocation(), DiagID) 5619 << NewDecl 5620 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5621 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5622 if (!JustWarn) { 5623 NewDecl->setInvalidDecl(); 5624 return; 5625 } 5626 } 5627 5628 // A redeclaration is not allowed to drop a dllimport attribute, the only 5629 // exceptions being inline function definitions, local extern declarations, 5630 // qualified friend declarations or special MSVC extension: in the last case, 5631 // the declaration is treated as if it were marked dllexport. 5632 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5633 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5634 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5635 // Ignore static data because out-of-line definitions are diagnosed 5636 // separately. 5637 IsStaticDataMember = VD->isStaticDataMember(); 5638 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5639 VarDecl::DeclarationOnly; 5640 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5641 IsInline = FD->isInlined(); 5642 IsQualifiedFriend = FD->getQualifier() && 5643 FD->getFriendObjectKind() == Decl::FOK_Declared; 5644 } 5645 5646 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5647 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5648 if (IsMicrosoft && IsDefinition) { 5649 S.Diag(NewDecl->getLocation(), 5650 diag::warn_redeclaration_without_import_attribute) 5651 << NewDecl; 5652 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5653 NewDecl->dropAttr<DLLImportAttr>(); 5654 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5655 NewImportAttr->getRange(), S.Context, 5656 NewImportAttr->getSpellingListIndex())); 5657 } else { 5658 S.Diag(NewDecl->getLocation(), 5659 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5660 << NewDecl << OldImportAttr; 5661 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5662 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5663 OldDecl->dropAttr<DLLImportAttr>(); 5664 NewDecl->dropAttr<DLLImportAttr>(); 5665 } 5666 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5667 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5668 OldDecl->dropAttr<DLLImportAttr>(); 5669 NewDecl->dropAttr<DLLImportAttr>(); 5670 S.Diag(NewDecl->getLocation(), 5671 diag::warn_dllimport_dropped_from_inline_function) 5672 << NewDecl << OldImportAttr; 5673 } 5674 } 5675 5676 /// Given that we are within the definition of the given function, 5677 /// will that definition behave like C99's 'inline', where the 5678 /// definition is discarded except for optimization purposes? 5679 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5680 // Try to avoid calling GetGVALinkageForFunction. 5681 5682 // All cases of this require the 'inline' keyword. 5683 if (!FD->isInlined()) return false; 5684 5685 // This is only possible in C++ with the gnu_inline attribute. 5686 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5687 return false; 5688 5689 // Okay, go ahead and call the relatively-more-expensive function. 5690 5691 #ifndef NDEBUG 5692 // AST quite reasonably asserts that it's working on a function 5693 // definition. We don't really have a way to tell it that we're 5694 // currently defining the function, so just lie to it in +Asserts 5695 // builds. This is an awful hack. 5696 FD->setLazyBody(1); 5697 #endif 5698 5699 bool isC99Inline = 5700 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5701 5702 #ifndef NDEBUG 5703 FD->setLazyBody(0); 5704 #endif 5705 5706 return isC99Inline; 5707 } 5708 5709 /// Determine whether a variable is extern "C" prior to attaching 5710 /// an initializer. We can't just call isExternC() here, because that 5711 /// will also compute and cache whether the declaration is externally 5712 /// visible, which might change when we attach the initializer. 5713 /// 5714 /// This can only be used if the declaration is known to not be a 5715 /// redeclaration of an internal linkage declaration. 5716 /// 5717 /// For instance: 5718 /// 5719 /// auto x = []{}; 5720 /// 5721 /// Attaching the initializer here makes this declaration not externally 5722 /// visible, because its type has internal linkage. 5723 /// 5724 /// FIXME: This is a hack. 5725 template<typename T> 5726 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5727 if (S.getLangOpts().CPlusPlus) { 5728 // In C++, the overloadable attribute negates the effects of extern "C". 5729 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5730 return false; 5731 5732 // So do CUDA's host/device attributes. 5733 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 5734 D->template hasAttr<CUDAHostAttr>())) 5735 return false; 5736 } 5737 return D->isExternC(); 5738 } 5739 5740 static bool shouldConsiderLinkage(const VarDecl *VD) { 5741 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5742 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 5743 return VD->hasExternalStorage(); 5744 if (DC->isFileContext()) 5745 return true; 5746 if (DC->isRecord()) 5747 return false; 5748 llvm_unreachable("Unexpected context"); 5749 } 5750 5751 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5752 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5753 if (DC->isFileContext() || DC->isFunctionOrMethod() || 5754 isa<OMPDeclareReductionDecl>(DC)) 5755 return true; 5756 if (DC->isRecord()) 5757 return false; 5758 llvm_unreachable("Unexpected context"); 5759 } 5760 5761 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5762 AttributeList::Kind Kind) { 5763 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5764 if (L->getKind() == Kind) 5765 return true; 5766 return false; 5767 } 5768 5769 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5770 AttributeList::Kind Kind) { 5771 // Check decl attributes on the DeclSpec. 5772 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5773 return true; 5774 5775 // Walk the declarator structure, checking decl attributes that were in a type 5776 // position to the decl itself. 5777 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5778 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5779 return true; 5780 } 5781 5782 // Finally, check attributes on the decl itself. 5783 return hasParsedAttr(S, PD.getAttributes(), Kind); 5784 } 5785 5786 /// Adjust the \c DeclContext for a function or variable that might be a 5787 /// function-local external declaration. 5788 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5789 if (!DC->isFunctionOrMethod()) 5790 return false; 5791 5792 // If this is a local extern function or variable declared within a function 5793 // template, don't add it into the enclosing namespace scope until it is 5794 // instantiated; it might have a dependent type right now. 5795 if (DC->isDependentContext()) 5796 return true; 5797 5798 // C++11 [basic.link]p7: 5799 // When a block scope declaration of an entity with linkage is not found to 5800 // refer to some other declaration, then that entity is a member of the 5801 // innermost enclosing namespace. 5802 // 5803 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5804 // semantically-enclosing namespace, not a lexically-enclosing one. 5805 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5806 DC = DC->getParent(); 5807 return true; 5808 } 5809 5810 /// \brief Returns true if given declaration has external C language linkage. 5811 static bool isDeclExternC(const Decl *D) { 5812 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5813 return FD->isExternC(); 5814 if (const auto *VD = dyn_cast<VarDecl>(D)) 5815 return VD->isExternC(); 5816 5817 llvm_unreachable("Unknown type of decl!"); 5818 } 5819 5820 NamedDecl * 5821 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5822 TypeSourceInfo *TInfo, LookupResult &Previous, 5823 MultiTemplateParamsArg TemplateParamLists, 5824 bool &AddToScope) { 5825 QualType R = TInfo->getType(); 5826 DeclarationName Name = GetNameForDeclarator(D).getName(); 5827 5828 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 5829 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 5830 // argument. 5831 if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) { 5832 Diag(D.getIdentifierLoc(), 5833 diag::err_opencl_type_can_only_be_used_as_function_parameter) 5834 << R; 5835 D.setInvalidType(); 5836 return nullptr; 5837 } 5838 5839 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5840 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5841 5842 // dllimport globals without explicit storage class are treated as extern. We 5843 // have to change the storage class this early to get the right DeclContext. 5844 if (SC == SC_None && !DC->isRecord() && 5845 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5846 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5847 SC = SC_Extern; 5848 5849 DeclContext *OriginalDC = DC; 5850 bool IsLocalExternDecl = SC == SC_Extern && 5851 adjustContextForLocalExternDecl(DC); 5852 5853 if (getLangOpts().OpenCL) { 5854 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5855 QualType NR = R; 5856 while (NR->isPointerType()) { 5857 if (NR->isFunctionPointerType()) { 5858 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5859 D.setInvalidType(); 5860 break; 5861 } 5862 NR = NR->getPointeeType(); 5863 } 5864 5865 if (!getOpenCLOptions().cl_khr_fp16) { 5866 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5867 // half array type (unless the cl_khr_fp16 extension is enabled). 5868 if (Context.getBaseElementType(R)->isHalfType()) { 5869 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5870 D.setInvalidType(); 5871 } 5872 } 5873 } 5874 5875 if (SCSpec == DeclSpec::SCS_mutable) { 5876 // mutable can only appear on non-static class members, so it's always 5877 // an error here 5878 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5879 D.setInvalidType(); 5880 SC = SC_None; 5881 } 5882 5883 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5884 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5885 D.getDeclSpec().getStorageClassSpecLoc())) { 5886 // In C++11, the 'register' storage class specifier is deprecated. 5887 // Suppress the warning in system macros, it's used in macros in some 5888 // popular C system headers, such as in glibc's htonl() macro. 5889 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5890 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 5891 : diag::warn_deprecated_register) 5892 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5893 } 5894 5895 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5896 if (!II) { 5897 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5898 << Name; 5899 return nullptr; 5900 } 5901 5902 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5903 5904 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5905 // C99 6.9p2: The storage-class specifiers auto and register shall not 5906 // appear in the declaration specifiers in an external declaration. 5907 // Global Register+Asm is a GNU extension we support. 5908 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5909 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5910 D.setInvalidType(); 5911 } 5912 } 5913 5914 if (getLangOpts().OpenCL) { 5915 // OpenCL v1.2 s6.9.b p4: 5916 // The sampler type cannot be used with the __local and __global address 5917 // space qualifiers. 5918 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5919 R.getAddressSpace() == LangAS::opencl_global)) { 5920 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5921 } 5922 5923 // OpenCL 1.2 spec, p6.9 r: 5924 // The event type cannot be used to declare a program scope variable. 5925 // The event type cannot be used with the __local, __constant and __global 5926 // address space qualifiers. 5927 if (R->isEventT()) { 5928 if (S->getParent() == nullptr) { 5929 Diag(D.getLocStart(), diag::err_event_t_global_var); 5930 D.setInvalidType(); 5931 } 5932 5933 if (R.getAddressSpace()) { 5934 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5935 D.setInvalidType(); 5936 } 5937 } 5938 } 5939 5940 bool IsExplicitSpecialization = false; 5941 bool IsVariableTemplateSpecialization = false; 5942 bool IsPartialSpecialization = false; 5943 bool IsVariableTemplate = false; 5944 VarDecl *NewVD = nullptr; 5945 VarTemplateDecl *NewTemplate = nullptr; 5946 TemplateParameterList *TemplateParams = nullptr; 5947 if (!getLangOpts().CPlusPlus) { 5948 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5949 D.getIdentifierLoc(), II, 5950 R, TInfo, SC); 5951 5952 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5953 ParsingInitForAutoVars.insert(NewVD); 5954 5955 if (D.isInvalidType()) 5956 NewVD->setInvalidDecl(); 5957 } else { 5958 bool Invalid = false; 5959 5960 if (DC->isRecord() && !CurContext->isRecord()) { 5961 // This is an out-of-line definition of a static data member. 5962 switch (SC) { 5963 case SC_None: 5964 break; 5965 case SC_Static: 5966 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5967 diag::err_static_out_of_line) 5968 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5969 break; 5970 case SC_Auto: 5971 case SC_Register: 5972 case SC_Extern: 5973 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5974 // to names of variables declared in a block or to function parameters. 5975 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5976 // of class members 5977 5978 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5979 diag::err_storage_class_for_static_member) 5980 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5981 break; 5982 case SC_PrivateExtern: 5983 llvm_unreachable("C storage class in c++!"); 5984 } 5985 } 5986 5987 if (SC == SC_Static && CurContext->isRecord()) { 5988 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5989 if (RD->isLocalClass()) 5990 Diag(D.getIdentifierLoc(), 5991 diag::err_static_data_member_not_allowed_in_local_class) 5992 << Name << RD->getDeclName(); 5993 5994 // C++98 [class.union]p1: If a union contains a static data member, 5995 // the program is ill-formed. C++11 drops this restriction. 5996 if (RD->isUnion()) 5997 Diag(D.getIdentifierLoc(), 5998 getLangOpts().CPlusPlus11 5999 ? diag::warn_cxx98_compat_static_data_member_in_union 6000 : diag::ext_static_data_member_in_union) << Name; 6001 // We conservatively disallow static data members in anonymous structs. 6002 else if (!RD->getDeclName()) 6003 Diag(D.getIdentifierLoc(), 6004 diag::err_static_data_member_not_allowed_in_anon_struct) 6005 << Name << RD->isUnion(); 6006 } 6007 } 6008 6009 // Match up the template parameter lists with the scope specifier, then 6010 // determine whether we have a template or a template specialization. 6011 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6012 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6013 D.getCXXScopeSpec(), 6014 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6015 ? D.getName().TemplateId 6016 : nullptr, 6017 TemplateParamLists, 6018 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 6019 6020 if (TemplateParams) { 6021 if (!TemplateParams->size() && 6022 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6023 // There is an extraneous 'template<>' for this variable. Complain 6024 // about it, but allow the declaration of the variable. 6025 Diag(TemplateParams->getTemplateLoc(), 6026 diag::err_template_variable_noparams) 6027 << II 6028 << SourceRange(TemplateParams->getTemplateLoc(), 6029 TemplateParams->getRAngleLoc()); 6030 TemplateParams = nullptr; 6031 } else { 6032 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6033 // This is an explicit specialization or a partial specialization. 6034 // FIXME: Check that we can declare a specialization here. 6035 IsVariableTemplateSpecialization = true; 6036 IsPartialSpecialization = TemplateParams->size() > 0; 6037 } else { // if (TemplateParams->size() > 0) 6038 // This is a template declaration. 6039 IsVariableTemplate = true; 6040 6041 // Check that we can declare a template here. 6042 if (CheckTemplateDeclScope(S, TemplateParams)) 6043 return nullptr; 6044 6045 // Only C++1y supports variable templates (N3651). 6046 Diag(D.getIdentifierLoc(), 6047 getLangOpts().CPlusPlus14 6048 ? diag::warn_cxx11_compat_variable_template 6049 : diag::ext_variable_template); 6050 } 6051 } 6052 } else { 6053 assert( 6054 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6055 "should have a 'template<>' for this decl"); 6056 } 6057 6058 if (IsVariableTemplateSpecialization) { 6059 SourceLocation TemplateKWLoc = 6060 TemplateParamLists.size() > 0 6061 ? TemplateParamLists[0]->getTemplateLoc() 6062 : SourceLocation(); 6063 DeclResult Res = ActOnVarTemplateSpecialization( 6064 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6065 IsPartialSpecialization); 6066 if (Res.isInvalid()) 6067 return nullptr; 6068 NewVD = cast<VarDecl>(Res.get()); 6069 AddToScope = false; 6070 } else 6071 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6072 D.getIdentifierLoc(), II, R, TInfo, SC); 6073 6074 // If this is supposed to be a variable template, create it as such. 6075 if (IsVariableTemplate) { 6076 NewTemplate = 6077 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6078 TemplateParams, NewVD); 6079 NewVD->setDescribedVarTemplate(NewTemplate); 6080 } 6081 6082 // If this decl has an auto type in need of deduction, make a note of the 6083 // Decl so we can diagnose uses of it in its own initializer. 6084 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6085 ParsingInitForAutoVars.insert(NewVD); 6086 6087 if (D.isInvalidType() || Invalid) { 6088 NewVD->setInvalidDecl(); 6089 if (NewTemplate) 6090 NewTemplate->setInvalidDecl(); 6091 } 6092 6093 SetNestedNameSpecifier(NewVD, D); 6094 6095 // If we have any template parameter lists that don't directly belong to 6096 // the variable (matching the scope specifier), store them. 6097 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6098 if (TemplateParamLists.size() > VDTemplateParamLists) 6099 NewVD->setTemplateParameterListsInfo( 6100 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6101 6102 if (D.getDeclSpec().isConstexprSpecified()) 6103 NewVD->setConstexpr(true); 6104 6105 if (D.getDeclSpec().isConceptSpecified()) { 6106 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6107 VTD->setConcept(); 6108 6109 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6110 // be declared with the thread_local, inline, friend, or constexpr 6111 // specifiers, [...] 6112 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6113 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6114 diag::err_concept_decl_invalid_specifiers) 6115 << 0 << 0; 6116 NewVD->setInvalidDecl(true); 6117 } 6118 6119 if (D.getDeclSpec().isConstexprSpecified()) { 6120 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6121 diag::err_concept_decl_invalid_specifiers) 6122 << 0 << 3; 6123 NewVD->setInvalidDecl(true); 6124 } 6125 6126 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6127 // applied only to the definition of a function template or variable 6128 // template, declared in namespace scope. 6129 if (IsVariableTemplateSpecialization) { 6130 Diag(D.getDeclSpec().getConceptSpecLoc(), 6131 diag::err_concept_specified_specialization) 6132 << (IsPartialSpecialization ? 2 : 1); 6133 } 6134 6135 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6136 // following restrictions: 6137 // - The declared type shall have the type bool. 6138 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6139 !NewVD->isInvalidDecl()) { 6140 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6141 NewVD->setInvalidDecl(true); 6142 } 6143 } 6144 } 6145 6146 // Set the lexical context. If the declarator has a C++ scope specifier, the 6147 // lexical context will be different from the semantic context. 6148 NewVD->setLexicalDeclContext(CurContext); 6149 if (NewTemplate) 6150 NewTemplate->setLexicalDeclContext(CurContext); 6151 6152 if (IsLocalExternDecl) 6153 NewVD->setLocalExternDecl(); 6154 6155 bool EmitTLSUnsupportedError = false; 6156 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6157 // C++11 [dcl.stc]p4: 6158 // When thread_local is applied to a variable of block scope the 6159 // storage-class-specifier static is implied if it does not appear 6160 // explicitly. 6161 // Core issue: 'static' is not implied if the variable is declared 6162 // 'extern'. 6163 if (NewVD->hasLocalStorage() && 6164 (SCSpec != DeclSpec::SCS_unspecified || 6165 TSCS != DeclSpec::TSCS_thread_local || 6166 !DC->isFunctionOrMethod())) 6167 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6168 diag::err_thread_non_global) 6169 << DeclSpec::getSpecifierName(TSCS); 6170 else if (!Context.getTargetInfo().isTLSSupported()) { 6171 if (getLangOpts().CUDA) { 6172 // Postpone error emission until we've collected attributes required to 6173 // figure out whether it's a host or device variable and whether the 6174 // error should be ignored. 6175 EmitTLSUnsupportedError = true; 6176 // We still need to mark the variable as TLS so it shows up in AST with 6177 // proper storage class for other tools to use even if we're not going 6178 // to emit any code for it. 6179 NewVD->setTSCSpec(TSCS); 6180 } else 6181 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6182 diag::err_thread_unsupported); 6183 } else 6184 NewVD->setTSCSpec(TSCS); 6185 } 6186 6187 // C99 6.7.4p3 6188 // An inline definition of a function with external linkage shall 6189 // not contain a definition of a modifiable object with static or 6190 // thread storage duration... 6191 // We only apply this when the function is required to be defined 6192 // elsewhere, i.e. when the function is not 'extern inline'. Note 6193 // that a local variable with thread storage duration still has to 6194 // be marked 'static'. Also note that it's possible to get these 6195 // semantics in C++ using __attribute__((gnu_inline)). 6196 if (SC == SC_Static && S->getFnParent() != nullptr && 6197 !NewVD->getType().isConstQualified()) { 6198 FunctionDecl *CurFD = getCurFunctionDecl(); 6199 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6200 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6201 diag::warn_static_local_in_extern_inline); 6202 MaybeSuggestAddingStaticToDecl(CurFD); 6203 } 6204 } 6205 6206 if (D.getDeclSpec().isModulePrivateSpecified()) { 6207 if (IsVariableTemplateSpecialization) 6208 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6209 << (IsPartialSpecialization ? 1 : 0) 6210 << FixItHint::CreateRemoval( 6211 D.getDeclSpec().getModulePrivateSpecLoc()); 6212 else if (IsExplicitSpecialization) 6213 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6214 << 2 6215 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6216 else if (NewVD->hasLocalStorage()) 6217 Diag(NewVD->getLocation(), diag::err_module_private_local) 6218 << 0 << NewVD->getDeclName() 6219 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6220 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6221 else { 6222 NewVD->setModulePrivate(); 6223 if (NewTemplate) 6224 NewTemplate->setModulePrivate(); 6225 } 6226 } 6227 6228 // Handle attributes prior to checking for duplicates in MergeVarDecl 6229 ProcessDeclAttributes(S, NewVD, D); 6230 6231 if (getLangOpts().CUDA) { 6232 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6233 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6234 diag::err_thread_unsupported); 6235 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6236 // storage [duration]." 6237 if (SC == SC_None && S->getFnParent() != nullptr && 6238 (NewVD->hasAttr<CUDASharedAttr>() || 6239 NewVD->hasAttr<CUDAConstantAttr>())) { 6240 NewVD->setStorageClass(SC_Static); 6241 } 6242 } 6243 6244 // Ensure that dllimport globals without explicit storage class are treated as 6245 // extern. The storage class is set above using parsed attributes. Now we can 6246 // check the VarDecl itself. 6247 assert(!NewVD->hasAttr<DLLImportAttr>() || 6248 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6249 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6250 6251 // In auto-retain/release, infer strong retension for variables of 6252 // retainable type. 6253 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6254 NewVD->setInvalidDecl(); 6255 6256 // Handle GNU asm-label extension (encoded as an attribute). 6257 if (Expr *E = (Expr*)D.getAsmLabel()) { 6258 // The parser guarantees this is a string. 6259 StringLiteral *SE = cast<StringLiteral>(E); 6260 StringRef Label = SE->getString(); 6261 if (S->getFnParent() != nullptr) { 6262 switch (SC) { 6263 case SC_None: 6264 case SC_Auto: 6265 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6266 break; 6267 case SC_Register: 6268 // Local Named register 6269 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6270 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6271 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6272 break; 6273 case SC_Static: 6274 case SC_Extern: 6275 case SC_PrivateExtern: 6276 break; 6277 } 6278 } else if (SC == SC_Register) { 6279 // Global Named register 6280 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6281 const auto &TI = Context.getTargetInfo(); 6282 bool HasSizeMismatch; 6283 6284 if (!TI.isValidGCCRegisterName(Label)) 6285 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6286 else if (!TI.validateGlobalRegisterVariable(Label, 6287 Context.getTypeSize(R), 6288 HasSizeMismatch)) 6289 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6290 else if (HasSizeMismatch) 6291 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6292 } 6293 6294 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6295 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6296 NewVD->setInvalidDecl(true); 6297 } 6298 } 6299 6300 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6301 Context, Label, 0)); 6302 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6303 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6304 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6305 if (I != ExtnameUndeclaredIdentifiers.end()) { 6306 if (isDeclExternC(NewVD)) { 6307 NewVD->addAttr(I->second); 6308 ExtnameUndeclaredIdentifiers.erase(I); 6309 } else 6310 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6311 << /*Variable*/1 << NewVD; 6312 } 6313 } 6314 6315 // Diagnose shadowed variables before filtering for scope. 6316 if (D.getCXXScopeSpec().isEmpty()) 6317 CheckShadow(S, NewVD, Previous); 6318 6319 // Don't consider existing declarations that are in a different 6320 // scope and are out-of-semantic-context declarations (if the new 6321 // declaration has linkage). 6322 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6323 D.getCXXScopeSpec().isNotEmpty() || 6324 IsExplicitSpecialization || 6325 IsVariableTemplateSpecialization); 6326 6327 // Check whether the previous declaration is in the same block scope. This 6328 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6329 if (getLangOpts().CPlusPlus && 6330 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6331 NewVD->setPreviousDeclInSameBlockScope( 6332 Previous.isSingleResult() && !Previous.isShadowed() && 6333 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6334 6335 if (!getLangOpts().CPlusPlus) { 6336 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6337 } else { 6338 // If this is an explicit specialization of a static data member, check it. 6339 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6340 CheckMemberSpecialization(NewVD, Previous)) 6341 NewVD->setInvalidDecl(); 6342 6343 // Merge the decl with the existing one if appropriate. 6344 if (!Previous.empty()) { 6345 if (Previous.isSingleResult() && 6346 isa<FieldDecl>(Previous.getFoundDecl()) && 6347 D.getCXXScopeSpec().isSet()) { 6348 // The user tried to define a non-static data member 6349 // out-of-line (C++ [dcl.meaning]p1). 6350 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6351 << D.getCXXScopeSpec().getRange(); 6352 Previous.clear(); 6353 NewVD->setInvalidDecl(); 6354 } 6355 } else if (D.getCXXScopeSpec().isSet()) { 6356 // No previous declaration in the qualifying scope. 6357 Diag(D.getIdentifierLoc(), diag::err_no_member) 6358 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6359 << D.getCXXScopeSpec().getRange(); 6360 NewVD->setInvalidDecl(); 6361 } 6362 6363 if (!IsVariableTemplateSpecialization) 6364 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6365 6366 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6367 // an explicit specialization (14.8.3) or a partial specialization of a 6368 // concept definition. 6369 if (IsVariableTemplateSpecialization && 6370 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6371 Previous.isSingleResult()) { 6372 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6373 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6374 if (VarTmpl->isConcept()) { 6375 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6376 << 1 /*variable*/ 6377 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6378 : 1 /*explicitly specialized*/); 6379 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6380 NewVD->setInvalidDecl(); 6381 } 6382 } 6383 } 6384 6385 if (NewTemplate) { 6386 VarTemplateDecl *PrevVarTemplate = 6387 NewVD->getPreviousDecl() 6388 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6389 : nullptr; 6390 6391 // Check the template parameter list of this declaration, possibly 6392 // merging in the template parameter list from the previous variable 6393 // template declaration. 6394 if (CheckTemplateParameterList( 6395 TemplateParams, 6396 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6397 : nullptr, 6398 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6399 DC->isDependentContext()) 6400 ? TPC_ClassTemplateMember 6401 : TPC_VarTemplate)) 6402 NewVD->setInvalidDecl(); 6403 6404 // If we are providing an explicit specialization of a static variable 6405 // template, make a note of that. 6406 if (PrevVarTemplate && 6407 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6408 PrevVarTemplate->setMemberSpecialization(); 6409 } 6410 } 6411 6412 ProcessPragmaWeak(S, NewVD); 6413 6414 // If this is the first declaration of an extern C variable, update 6415 // the map of such variables. 6416 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6417 isIncompleteDeclExternC(*this, NewVD)) 6418 RegisterLocallyScopedExternCDecl(NewVD, S); 6419 6420 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6421 Decl *ManglingContextDecl; 6422 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6423 NewVD->getDeclContext(), ManglingContextDecl)) { 6424 Context.setManglingNumber( 6425 NewVD, MCtx->getManglingNumber( 6426 NewVD, getMSManglingNumber(getLangOpts(), S))); 6427 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6428 } 6429 } 6430 6431 // Special handling of variable named 'main'. 6432 if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") && 6433 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6434 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6435 6436 // C++ [basic.start.main]p3 6437 // A program that declares a variable main at global scope is ill-formed. 6438 if (getLangOpts().CPlusPlus) 6439 Diag(D.getLocStart(), diag::err_main_global_variable); 6440 6441 // In C, and external-linkage variable named main results in undefined 6442 // behavior. 6443 else if (NewVD->hasExternalFormalLinkage()) 6444 Diag(D.getLocStart(), diag::warn_main_redefined); 6445 } 6446 6447 if (D.isRedeclaration() && !Previous.empty()) { 6448 checkDLLAttributeRedeclaration( 6449 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6450 IsExplicitSpecialization, D.isFunctionDefinition()); 6451 } 6452 6453 if (NewTemplate) { 6454 if (NewVD->isInvalidDecl()) 6455 NewTemplate->setInvalidDecl(); 6456 ActOnDocumentableDecl(NewTemplate); 6457 return NewTemplate; 6458 } 6459 6460 return NewVD; 6461 } 6462 6463 /// Enum describing the %select options in diag::warn_decl_shadow. 6464 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field }; 6465 6466 /// Determine what kind of declaration we're shadowing. 6467 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6468 const DeclContext *OldDC) { 6469 if (isa<RecordDecl>(OldDC)) 6470 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6471 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6472 } 6473 6474 /// \brief Diagnose variable or built-in function shadowing. Implements 6475 /// -Wshadow. 6476 /// 6477 /// This method is called whenever a VarDecl is added to a "useful" 6478 /// scope. 6479 /// 6480 /// \param S the scope in which the shadowing name is being declared 6481 /// \param R the lookup of the name 6482 /// 6483 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6484 // Return if warning is ignored. 6485 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6486 return; 6487 6488 // Don't diagnose declarations at file scope. 6489 if (D->hasGlobalStorage()) 6490 return; 6491 6492 DeclContext *NewDC = D->getDeclContext(); 6493 6494 // Only diagnose if we're shadowing an unambiguous field or variable. 6495 if (R.getResultKind() != LookupResult::Found) 6496 return; 6497 6498 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6499 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6500 return; 6501 6502 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6503 // Fields are not shadowed by variables in C++ static methods. 6504 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6505 if (MD->isStatic()) 6506 return; 6507 6508 // Fields shadowed by constructor parameters are a special case. Usually 6509 // the constructor initializes the field with the parameter. 6510 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) { 6511 // Remember that this was shadowed so we can either warn about its 6512 // modification or its existence depending on warning settings. 6513 D = D->getCanonicalDecl(); 6514 ShadowingDecls.insert({D, FD}); 6515 return; 6516 } 6517 } 6518 6519 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6520 if (shadowedVar->isExternC()) { 6521 // For shadowing external vars, make sure that we point to the global 6522 // declaration, not a locally scoped extern declaration. 6523 for (auto I : shadowedVar->redecls()) 6524 if (I->isFileVarDecl()) { 6525 ShadowedDecl = I; 6526 break; 6527 } 6528 } 6529 6530 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6531 6532 // Only warn about certain kinds of shadowing for class members. 6533 if (NewDC && NewDC->isRecord()) { 6534 // In particular, don't warn about shadowing non-class members. 6535 if (!OldDC->isRecord()) 6536 return; 6537 6538 // TODO: should we warn about static data members shadowing 6539 // static data members from base classes? 6540 6541 // TODO: don't diagnose for inaccessible shadowed members. 6542 // This is hard to do perfectly because we might friend the 6543 // shadowing context, but that's just a false negative. 6544 } 6545 6546 6547 DeclarationName Name = R.getLookupName(); 6548 6549 // Emit warning and note. 6550 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6551 return; 6552 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6553 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6554 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6555 } 6556 6557 /// \brief Check -Wshadow without the advantage of a previous lookup. 6558 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6559 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6560 return; 6561 6562 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6563 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6564 LookupName(R, S); 6565 CheckShadow(S, D, R); 6566 } 6567 6568 /// Check if 'E', which is an expression that is about to be modified, refers 6569 /// to a constructor parameter that shadows a field. 6570 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 6571 // Quickly ignore expressions that can't be shadowing ctor parameters. 6572 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 6573 return; 6574 E = E->IgnoreParenImpCasts(); 6575 auto *DRE = dyn_cast<DeclRefExpr>(E); 6576 if (!DRE) 6577 return; 6578 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 6579 auto I = ShadowingDecls.find(D); 6580 if (I == ShadowingDecls.end()) 6581 return; 6582 const NamedDecl *ShadowedDecl = I->second; 6583 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6584 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 6585 Diag(D->getLocation(), diag::note_var_declared_here) << D; 6586 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6587 6588 // Avoid issuing multiple warnings about the same decl. 6589 ShadowingDecls.erase(I); 6590 } 6591 6592 /// Check for conflict between this global or extern "C" declaration and 6593 /// previous global or extern "C" declarations. This is only used in C++. 6594 template<typename T> 6595 static bool checkGlobalOrExternCConflict( 6596 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6597 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6598 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6599 6600 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6601 // The common case: this global doesn't conflict with any extern "C" 6602 // declaration. 6603 return false; 6604 } 6605 6606 if (Prev) { 6607 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6608 // Both the old and new declarations have C language linkage. This is a 6609 // redeclaration. 6610 Previous.clear(); 6611 Previous.addDecl(Prev); 6612 return true; 6613 } 6614 6615 // This is a global, non-extern "C" declaration, and there is a previous 6616 // non-global extern "C" declaration. Diagnose if this is a variable 6617 // declaration. 6618 if (!isa<VarDecl>(ND)) 6619 return false; 6620 } else { 6621 // The declaration is extern "C". Check for any declaration in the 6622 // translation unit which might conflict. 6623 if (IsGlobal) { 6624 // We have already performed the lookup into the translation unit. 6625 IsGlobal = false; 6626 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6627 I != E; ++I) { 6628 if (isa<VarDecl>(*I)) { 6629 Prev = *I; 6630 break; 6631 } 6632 } 6633 } else { 6634 DeclContext::lookup_result R = 6635 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6636 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6637 I != E; ++I) { 6638 if (isa<VarDecl>(*I)) { 6639 Prev = *I; 6640 break; 6641 } 6642 // FIXME: If we have any other entity with this name in global scope, 6643 // the declaration is ill-formed, but that is a defect: it breaks the 6644 // 'stat' hack, for instance. Only variables can have mangled name 6645 // clashes with extern "C" declarations, so only they deserve a 6646 // diagnostic. 6647 } 6648 } 6649 6650 if (!Prev) 6651 return false; 6652 } 6653 6654 // Use the first declaration's location to ensure we point at something which 6655 // is lexically inside an extern "C" linkage-spec. 6656 assert(Prev && "should have found a previous declaration to diagnose"); 6657 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6658 Prev = FD->getFirstDecl(); 6659 else 6660 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6661 6662 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6663 << IsGlobal << ND; 6664 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6665 << IsGlobal; 6666 return false; 6667 } 6668 6669 /// Apply special rules for handling extern "C" declarations. Returns \c true 6670 /// if we have found that this is a redeclaration of some prior entity. 6671 /// 6672 /// Per C++ [dcl.link]p6: 6673 /// Two declarations [for a function or variable] with C language linkage 6674 /// with the same name that appear in different scopes refer to the same 6675 /// [entity]. An entity with C language linkage shall not be declared with 6676 /// the same name as an entity in global scope. 6677 template<typename T> 6678 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6679 LookupResult &Previous) { 6680 if (!S.getLangOpts().CPlusPlus) { 6681 // In C, when declaring a global variable, look for a corresponding 'extern' 6682 // variable declared in function scope. We don't need this in C++, because 6683 // we find local extern decls in the surrounding file-scope DeclContext. 6684 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6685 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6686 Previous.clear(); 6687 Previous.addDecl(Prev); 6688 return true; 6689 } 6690 } 6691 return false; 6692 } 6693 6694 // A declaration in the translation unit can conflict with an extern "C" 6695 // declaration. 6696 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6697 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6698 6699 // An extern "C" declaration can conflict with a declaration in the 6700 // translation unit or can be a redeclaration of an extern "C" declaration 6701 // in another scope. 6702 if (isIncompleteDeclExternC(S,ND)) 6703 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6704 6705 // Neither global nor extern "C": nothing to do. 6706 return false; 6707 } 6708 6709 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6710 // If the decl is already known invalid, don't check it. 6711 if (NewVD->isInvalidDecl()) 6712 return; 6713 6714 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6715 QualType T = TInfo->getType(); 6716 6717 // Defer checking an 'auto' type until its initializer is attached. 6718 if (T->isUndeducedType()) 6719 return; 6720 6721 if (NewVD->hasAttrs()) 6722 CheckAlignasUnderalignment(NewVD); 6723 6724 if (T->isObjCObjectType()) { 6725 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6726 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6727 T = Context.getObjCObjectPointerType(T); 6728 NewVD->setType(T); 6729 } 6730 6731 // Emit an error if an address space was applied to decl with local storage. 6732 // This includes arrays of objects with address space qualifiers, but not 6733 // automatic variables that point to other address spaces. 6734 // ISO/IEC TR 18037 S5.1.2 6735 if (!getLangOpts().OpenCL 6736 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6737 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6738 NewVD->setInvalidDecl(); 6739 return; 6740 } 6741 6742 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 6743 // scope. 6744 if (getLangOpts().OpenCLVersion == 120 && 6745 !getOpenCLOptions().cl_clang_storage_class_specifiers && 6746 NewVD->isStaticLocal()) { 6747 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6748 NewVD->setInvalidDecl(); 6749 return; 6750 } 6751 6752 if (getLangOpts().OpenCL) { 6753 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 6754 if (NewVD->hasAttr<BlocksAttr>()) { 6755 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 6756 return; 6757 } 6758 6759 if (T->isBlockPointerType()) { 6760 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 6761 // can't use 'extern' storage class. 6762 if (!T.isConstQualified()) { 6763 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 6764 << 0 /*const*/; 6765 NewVD->setInvalidDecl(); 6766 return; 6767 } 6768 if (NewVD->hasExternalStorage()) { 6769 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 6770 NewVD->setInvalidDecl(); 6771 return; 6772 } 6773 // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported. 6774 // TODO: this check is not enough as it doesn't diagnose the typedef 6775 const BlockPointerType *BlkTy = T->getAs<BlockPointerType>(); 6776 const FunctionProtoType *FTy = 6777 BlkTy->getPointeeType()->getAs<FunctionProtoType>(); 6778 if (FTy && FTy->isVariadic()) { 6779 Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic) 6780 << T << NewVD->getSourceRange(); 6781 NewVD->setInvalidDecl(); 6782 return; 6783 } 6784 } 6785 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6786 // __constant address space. 6787 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6788 // variables inside a function can also be declared in the global 6789 // address space. 6790 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 6791 NewVD->hasExternalStorage()) { 6792 if (!T->isSamplerT() && 6793 !(T.getAddressSpace() == LangAS::opencl_constant || 6794 (T.getAddressSpace() == LangAS::opencl_global && 6795 getLangOpts().OpenCLVersion == 200))) { 6796 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 6797 if (getLangOpts().OpenCLVersion == 200) 6798 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6799 << Scope << "global or constant"; 6800 else 6801 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6802 << Scope << "constant"; 6803 NewVD->setInvalidDecl(); 6804 return; 6805 } 6806 } else { 6807 if (T.getAddressSpace() == LangAS::opencl_global) { 6808 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6809 << 1 /*is any function*/ << "global"; 6810 NewVD->setInvalidDecl(); 6811 return; 6812 } 6813 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 6814 // in functions. 6815 if (T.getAddressSpace() == LangAS::opencl_constant || 6816 T.getAddressSpace() == LangAS::opencl_local) { 6817 FunctionDecl *FD = getCurFunctionDecl(); 6818 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 6819 if (T.getAddressSpace() == LangAS::opencl_constant) 6820 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6821 << 0 /*non-kernel only*/ << "constant"; 6822 else 6823 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6824 << 0 /*non-kernel only*/ << "local"; 6825 NewVD->setInvalidDecl(); 6826 return; 6827 } 6828 } 6829 } 6830 } 6831 6832 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6833 && !NewVD->hasAttr<BlocksAttr>()) { 6834 if (getLangOpts().getGC() != LangOptions::NonGC) 6835 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6836 else { 6837 assert(!getLangOpts().ObjCAutoRefCount); 6838 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6839 } 6840 } 6841 6842 bool isVM = T->isVariablyModifiedType(); 6843 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6844 NewVD->hasAttr<BlocksAttr>()) 6845 getCurFunction()->setHasBranchProtectedScope(); 6846 6847 if ((isVM && NewVD->hasLinkage()) || 6848 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6849 bool SizeIsNegative; 6850 llvm::APSInt Oversized; 6851 TypeSourceInfo *FixedTInfo = 6852 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6853 SizeIsNegative, Oversized); 6854 if (!FixedTInfo && T->isVariableArrayType()) { 6855 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6856 // FIXME: This won't give the correct result for 6857 // int a[10][n]; 6858 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6859 6860 if (NewVD->isFileVarDecl()) 6861 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6862 << SizeRange; 6863 else if (NewVD->isStaticLocal()) 6864 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6865 << SizeRange; 6866 else 6867 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6868 << SizeRange; 6869 NewVD->setInvalidDecl(); 6870 return; 6871 } 6872 6873 if (!FixedTInfo) { 6874 if (NewVD->isFileVarDecl()) 6875 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6876 else 6877 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6878 NewVD->setInvalidDecl(); 6879 return; 6880 } 6881 6882 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6883 NewVD->setType(FixedTInfo->getType()); 6884 NewVD->setTypeSourceInfo(FixedTInfo); 6885 } 6886 6887 if (T->isVoidType()) { 6888 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6889 // of objects and functions. 6890 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6891 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6892 << T; 6893 NewVD->setInvalidDecl(); 6894 return; 6895 } 6896 } 6897 6898 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6899 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6900 NewVD->setInvalidDecl(); 6901 return; 6902 } 6903 6904 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6905 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6906 NewVD->setInvalidDecl(); 6907 return; 6908 } 6909 6910 if (NewVD->isConstexpr() && !T->isDependentType() && 6911 RequireLiteralType(NewVD->getLocation(), T, 6912 diag::err_constexpr_var_non_literal)) { 6913 NewVD->setInvalidDecl(); 6914 return; 6915 } 6916 } 6917 6918 /// \brief Perform semantic checking on a newly-created variable 6919 /// declaration. 6920 /// 6921 /// This routine performs all of the type-checking required for a 6922 /// variable declaration once it has been built. It is used both to 6923 /// check variables after they have been parsed and their declarators 6924 /// have been translated into a declaration, and to check variables 6925 /// that have been instantiated from a template. 6926 /// 6927 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6928 /// 6929 /// Returns true if the variable declaration is a redeclaration. 6930 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6931 CheckVariableDeclarationType(NewVD); 6932 6933 // If the decl is already known invalid, don't check it. 6934 if (NewVD->isInvalidDecl()) 6935 return false; 6936 6937 // If we did not find anything by this name, look for a non-visible 6938 // extern "C" declaration with the same name. 6939 if (Previous.empty() && 6940 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6941 Previous.setShadowed(); 6942 6943 if (!Previous.empty()) { 6944 MergeVarDecl(NewVD, Previous); 6945 return true; 6946 } 6947 return false; 6948 } 6949 6950 namespace { 6951 struct FindOverriddenMethod { 6952 Sema *S; 6953 CXXMethodDecl *Method; 6954 6955 /// Member lookup function that determines whether a given C++ 6956 /// method overrides a method in a base class, to be used with 6957 /// CXXRecordDecl::lookupInBases(). 6958 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 6959 RecordDecl *BaseRecord = 6960 Specifier->getType()->getAs<RecordType>()->getDecl(); 6961 6962 DeclarationName Name = Method->getDeclName(); 6963 6964 // FIXME: Do we care about other names here too? 6965 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6966 // We really want to find the base class destructor here. 6967 QualType T = S->Context.getTypeDeclType(BaseRecord); 6968 CanQualType CT = S->Context.getCanonicalType(T); 6969 6970 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 6971 } 6972 6973 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 6974 Path.Decls = Path.Decls.slice(1)) { 6975 NamedDecl *D = Path.Decls.front(); 6976 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6977 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 6978 return true; 6979 } 6980 } 6981 6982 return false; 6983 } 6984 }; 6985 6986 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6987 } // end anonymous namespace 6988 6989 /// \brief Report an error regarding overriding, along with any relevant 6990 /// overriden methods. 6991 /// 6992 /// \param DiagID the primary error to report. 6993 /// \param MD the overriding method. 6994 /// \param OEK which overrides to include as notes. 6995 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6996 OverrideErrorKind OEK = OEK_All) { 6997 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6998 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6999 E = MD->end_overridden_methods(); 7000 I != E; ++I) { 7001 // This check (& the OEK parameter) could be replaced by a predicate, but 7002 // without lambdas that would be overkill. This is still nicer than writing 7003 // out the diag loop 3 times. 7004 if ((OEK == OEK_All) || 7005 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7006 (OEK == OEK_Deleted && (*I)->isDeleted())) 7007 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7008 } 7009 } 7010 7011 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7012 /// and if so, check that it's a valid override and remember it. 7013 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7014 // Look for methods in base classes that this method might override. 7015 CXXBasePaths Paths; 7016 FindOverriddenMethod FOM; 7017 FOM.Method = MD; 7018 FOM.S = this; 7019 bool hasDeletedOverridenMethods = false; 7020 bool hasNonDeletedOverridenMethods = false; 7021 bool AddedAny = false; 7022 if (DC->lookupInBases(FOM, Paths)) { 7023 for (auto *I : Paths.found_decls()) { 7024 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7025 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7026 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7027 !CheckOverridingFunctionAttributes(MD, OldMD) && 7028 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7029 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7030 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7031 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7032 AddedAny = true; 7033 } 7034 } 7035 } 7036 } 7037 7038 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7039 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7040 } 7041 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7042 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7043 } 7044 7045 return AddedAny; 7046 } 7047 7048 namespace { 7049 // Struct for holding all of the extra arguments needed by 7050 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7051 struct ActOnFDArgs { 7052 Scope *S; 7053 Declarator &D; 7054 MultiTemplateParamsArg TemplateParamLists; 7055 bool AddToScope; 7056 }; 7057 } // end anonymous namespace 7058 7059 namespace { 7060 7061 // Callback to only accept typo corrections that have a non-zero edit distance. 7062 // Also only accept corrections that have the same parent decl. 7063 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7064 public: 7065 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7066 CXXRecordDecl *Parent) 7067 : Context(Context), OriginalFD(TypoFD), 7068 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7069 7070 bool ValidateCandidate(const TypoCorrection &candidate) override { 7071 if (candidate.getEditDistance() == 0) 7072 return false; 7073 7074 SmallVector<unsigned, 1> MismatchedParams; 7075 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7076 CDeclEnd = candidate.end(); 7077 CDecl != CDeclEnd; ++CDecl) { 7078 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7079 7080 if (FD && !FD->hasBody() && 7081 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7082 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7083 CXXRecordDecl *Parent = MD->getParent(); 7084 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7085 return true; 7086 } else if (!ExpectedParent) { 7087 return true; 7088 } 7089 } 7090 } 7091 7092 return false; 7093 } 7094 7095 private: 7096 ASTContext &Context; 7097 FunctionDecl *OriginalFD; 7098 CXXRecordDecl *ExpectedParent; 7099 }; 7100 7101 } // end anonymous namespace 7102 7103 /// \brief Generate diagnostics for an invalid function redeclaration. 7104 /// 7105 /// This routine handles generating the diagnostic messages for an invalid 7106 /// function redeclaration, including finding possible similar declarations 7107 /// or performing typo correction if there are no previous declarations with 7108 /// the same name. 7109 /// 7110 /// Returns a NamedDecl iff typo correction was performed and substituting in 7111 /// the new declaration name does not cause new errors. 7112 static NamedDecl *DiagnoseInvalidRedeclaration( 7113 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7114 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7115 DeclarationName Name = NewFD->getDeclName(); 7116 DeclContext *NewDC = NewFD->getDeclContext(); 7117 SmallVector<unsigned, 1> MismatchedParams; 7118 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7119 TypoCorrection Correction; 7120 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7121 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7122 : diag::err_member_decl_does_not_match; 7123 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7124 IsLocalFriend ? Sema::LookupLocalFriendName 7125 : Sema::LookupOrdinaryName, 7126 Sema::ForRedeclaration); 7127 7128 NewFD->setInvalidDecl(); 7129 if (IsLocalFriend) 7130 SemaRef.LookupName(Prev, S); 7131 else 7132 SemaRef.LookupQualifiedName(Prev, NewDC); 7133 assert(!Prev.isAmbiguous() && 7134 "Cannot have an ambiguity in previous-declaration lookup"); 7135 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7136 if (!Prev.empty()) { 7137 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7138 Func != FuncEnd; ++Func) { 7139 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7140 if (FD && 7141 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7142 // Add 1 to the index so that 0 can mean the mismatch didn't 7143 // involve a parameter 7144 unsigned ParamNum = 7145 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7146 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7147 } 7148 } 7149 // If the qualified name lookup yielded nothing, try typo correction 7150 } else if ((Correction = SemaRef.CorrectTypo( 7151 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7152 &ExtraArgs.D.getCXXScopeSpec(), 7153 llvm::make_unique<DifferentNameValidatorCCC>( 7154 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7155 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7156 // Set up everything for the call to ActOnFunctionDeclarator 7157 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7158 ExtraArgs.D.getIdentifierLoc()); 7159 Previous.clear(); 7160 Previous.setLookupName(Correction.getCorrection()); 7161 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7162 CDeclEnd = Correction.end(); 7163 CDecl != CDeclEnd; ++CDecl) { 7164 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7165 if (FD && !FD->hasBody() && 7166 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7167 Previous.addDecl(FD); 7168 } 7169 } 7170 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7171 7172 NamedDecl *Result; 7173 // Retry building the function declaration with the new previous 7174 // declarations, and with errors suppressed. 7175 { 7176 // Trap errors. 7177 Sema::SFINAETrap Trap(SemaRef); 7178 7179 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7180 // pieces need to verify the typo-corrected C++ declaration and hopefully 7181 // eliminate the need for the parameter pack ExtraArgs. 7182 Result = SemaRef.ActOnFunctionDeclarator( 7183 ExtraArgs.S, ExtraArgs.D, 7184 Correction.getCorrectionDecl()->getDeclContext(), 7185 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7186 ExtraArgs.AddToScope); 7187 7188 if (Trap.hasErrorOccurred()) 7189 Result = nullptr; 7190 } 7191 7192 if (Result) { 7193 // Determine which correction we picked. 7194 Decl *Canonical = Result->getCanonicalDecl(); 7195 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7196 I != E; ++I) 7197 if ((*I)->getCanonicalDecl() == Canonical) 7198 Correction.setCorrectionDecl(*I); 7199 7200 SemaRef.diagnoseTypo( 7201 Correction, 7202 SemaRef.PDiag(IsLocalFriend 7203 ? diag::err_no_matching_local_friend_suggest 7204 : diag::err_member_decl_does_not_match_suggest) 7205 << Name << NewDC << IsDefinition); 7206 return Result; 7207 } 7208 7209 // Pretend the typo correction never occurred 7210 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7211 ExtraArgs.D.getIdentifierLoc()); 7212 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7213 Previous.clear(); 7214 Previous.setLookupName(Name); 7215 } 7216 7217 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7218 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7219 7220 bool NewFDisConst = false; 7221 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7222 NewFDisConst = NewMD->isConst(); 7223 7224 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7225 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7226 NearMatch != NearMatchEnd; ++NearMatch) { 7227 FunctionDecl *FD = NearMatch->first; 7228 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7229 bool FDisConst = MD && MD->isConst(); 7230 bool IsMember = MD || !IsLocalFriend; 7231 7232 // FIXME: These notes are poorly worded for the local friend case. 7233 if (unsigned Idx = NearMatch->second) { 7234 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7235 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7236 if (Loc.isInvalid()) Loc = FD->getLocation(); 7237 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7238 : diag::note_local_decl_close_param_match) 7239 << Idx << FDParam->getType() 7240 << NewFD->getParamDecl(Idx - 1)->getType(); 7241 } else if (FDisConst != NewFDisConst) { 7242 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7243 << NewFDisConst << FD->getSourceRange().getEnd(); 7244 } else 7245 SemaRef.Diag(FD->getLocation(), 7246 IsMember ? diag::note_member_def_close_match 7247 : diag::note_local_decl_close_match); 7248 } 7249 return nullptr; 7250 } 7251 7252 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7253 switch (D.getDeclSpec().getStorageClassSpec()) { 7254 default: llvm_unreachable("Unknown storage class!"); 7255 case DeclSpec::SCS_auto: 7256 case DeclSpec::SCS_register: 7257 case DeclSpec::SCS_mutable: 7258 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7259 diag::err_typecheck_sclass_func); 7260 D.setInvalidType(); 7261 break; 7262 case DeclSpec::SCS_unspecified: break; 7263 case DeclSpec::SCS_extern: 7264 if (D.getDeclSpec().isExternInLinkageSpec()) 7265 return SC_None; 7266 return SC_Extern; 7267 case DeclSpec::SCS_static: { 7268 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7269 // C99 6.7.1p5: 7270 // The declaration of an identifier for a function that has 7271 // block scope shall have no explicit storage-class specifier 7272 // other than extern 7273 // See also (C++ [dcl.stc]p4). 7274 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7275 diag::err_static_block_func); 7276 break; 7277 } else 7278 return SC_Static; 7279 } 7280 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7281 } 7282 7283 // No explicit storage class has already been returned 7284 return SC_None; 7285 } 7286 7287 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7288 DeclContext *DC, QualType &R, 7289 TypeSourceInfo *TInfo, 7290 StorageClass SC, 7291 bool &IsVirtualOkay) { 7292 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7293 DeclarationName Name = NameInfo.getName(); 7294 7295 FunctionDecl *NewFD = nullptr; 7296 bool isInline = D.getDeclSpec().isInlineSpecified(); 7297 7298 if (!SemaRef.getLangOpts().CPlusPlus) { 7299 // Determine whether the function was written with a 7300 // prototype. This true when: 7301 // - there is a prototype in the declarator, or 7302 // - the type R of the function is some kind of typedef or other reference 7303 // to a type name (which eventually refers to a function type). 7304 bool HasPrototype = 7305 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7306 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7307 7308 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7309 D.getLocStart(), NameInfo, R, 7310 TInfo, SC, isInline, 7311 HasPrototype, false); 7312 if (D.isInvalidType()) 7313 NewFD->setInvalidDecl(); 7314 7315 return NewFD; 7316 } 7317 7318 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7319 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7320 7321 // Check that the return type is not an abstract class type. 7322 // For record types, this is done by the AbstractClassUsageDiagnoser once 7323 // the class has been completely parsed. 7324 if (!DC->isRecord() && 7325 SemaRef.RequireNonAbstractType( 7326 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7327 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7328 D.setInvalidType(); 7329 7330 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7331 // This is a C++ constructor declaration. 7332 assert(DC->isRecord() && 7333 "Constructors can only be declared in a member context"); 7334 7335 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7336 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7337 D.getLocStart(), NameInfo, 7338 R, TInfo, isExplicit, isInline, 7339 /*isImplicitlyDeclared=*/false, 7340 isConstexpr); 7341 7342 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7343 // This is a C++ destructor declaration. 7344 if (DC->isRecord()) { 7345 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7346 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7347 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7348 SemaRef.Context, Record, 7349 D.getLocStart(), 7350 NameInfo, R, TInfo, isInline, 7351 /*isImplicitlyDeclared=*/false); 7352 7353 // If the class is complete, then we now create the implicit exception 7354 // specification. If the class is incomplete or dependent, we can't do 7355 // it yet. 7356 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7357 Record->getDefinition() && !Record->isBeingDefined() && 7358 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7359 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7360 } 7361 7362 IsVirtualOkay = true; 7363 return NewDD; 7364 7365 } else { 7366 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7367 D.setInvalidType(); 7368 7369 // Create a FunctionDecl to satisfy the function definition parsing 7370 // code path. 7371 return FunctionDecl::Create(SemaRef.Context, DC, 7372 D.getLocStart(), 7373 D.getIdentifierLoc(), Name, R, TInfo, 7374 SC, isInline, 7375 /*hasPrototype=*/true, isConstexpr); 7376 } 7377 7378 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7379 if (!DC->isRecord()) { 7380 SemaRef.Diag(D.getIdentifierLoc(), 7381 diag::err_conv_function_not_member); 7382 return nullptr; 7383 } 7384 7385 SemaRef.CheckConversionDeclarator(D, R, SC); 7386 IsVirtualOkay = true; 7387 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7388 D.getLocStart(), NameInfo, 7389 R, TInfo, isInline, isExplicit, 7390 isConstexpr, SourceLocation()); 7391 7392 } else if (DC->isRecord()) { 7393 // If the name of the function is the same as the name of the record, 7394 // then this must be an invalid constructor that has a return type. 7395 // (The parser checks for a return type and makes the declarator a 7396 // constructor if it has no return type). 7397 if (Name.getAsIdentifierInfo() && 7398 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7399 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7400 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7401 << SourceRange(D.getIdentifierLoc()); 7402 return nullptr; 7403 } 7404 7405 // This is a C++ method declaration. 7406 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7407 cast<CXXRecordDecl>(DC), 7408 D.getLocStart(), NameInfo, R, 7409 TInfo, SC, isInline, 7410 isConstexpr, SourceLocation()); 7411 IsVirtualOkay = !Ret->isStatic(); 7412 return Ret; 7413 } else { 7414 bool isFriend = 7415 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7416 if (!isFriend && SemaRef.CurContext->isRecord()) 7417 return nullptr; 7418 7419 // Determine whether the function was written with a 7420 // prototype. This true when: 7421 // - we're in C++ (where every function has a prototype), 7422 return FunctionDecl::Create(SemaRef.Context, DC, 7423 D.getLocStart(), 7424 NameInfo, R, TInfo, SC, isInline, 7425 true/*HasPrototype*/, isConstexpr); 7426 } 7427 } 7428 7429 enum OpenCLParamType { 7430 ValidKernelParam, 7431 PtrPtrKernelParam, 7432 PtrKernelParam, 7433 PrivatePtrKernelParam, 7434 InvalidKernelParam, 7435 RecordKernelParam 7436 }; 7437 7438 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 7439 if (PT->isPointerType()) { 7440 QualType PointeeType = PT->getPointeeType(); 7441 if (PointeeType->isPointerType()) 7442 return PtrPtrKernelParam; 7443 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 7444 : PtrKernelParam; 7445 } 7446 7447 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7448 // be used as builtin types. 7449 7450 if (PT->isImageType()) 7451 return PtrKernelParam; 7452 7453 if (PT->isBooleanType()) 7454 return InvalidKernelParam; 7455 7456 if (PT->isEventT()) 7457 return InvalidKernelParam; 7458 7459 if (PT->isHalfType()) 7460 return InvalidKernelParam; 7461 7462 if (PT->isRecordType()) 7463 return RecordKernelParam; 7464 7465 return ValidKernelParam; 7466 } 7467 7468 static void checkIsValidOpenCLKernelParameter( 7469 Sema &S, 7470 Declarator &D, 7471 ParmVarDecl *Param, 7472 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7473 QualType PT = Param->getType(); 7474 7475 // Cache the valid types we encounter to avoid rechecking structs that are 7476 // used again 7477 if (ValidTypes.count(PT.getTypePtr())) 7478 return; 7479 7480 switch (getOpenCLKernelParameterType(PT)) { 7481 case PtrPtrKernelParam: 7482 // OpenCL v1.2 s6.9.a: 7483 // A kernel function argument cannot be declared as a 7484 // pointer to a pointer type. 7485 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7486 D.setInvalidType(); 7487 return; 7488 7489 case PrivatePtrKernelParam: 7490 // OpenCL v1.2 s6.9.a: 7491 // A kernel function argument cannot be declared as a 7492 // pointer to the private address space. 7493 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 7494 D.setInvalidType(); 7495 return; 7496 7497 // OpenCL v1.2 s6.9.k: 7498 // Arguments to kernel functions in a program cannot be declared with the 7499 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7500 // uintptr_t or a struct and/or union that contain fields declared to be 7501 // one of these built-in scalar types. 7502 7503 case InvalidKernelParam: 7504 // OpenCL v1.2 s6.8 n: 7505 // A kernel function argument cannot be declared 7506 // of event_t type. 7507 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7508 D.setInvalidType(); 7509 return; 7510 7511 case PtrKernelParam: 7512 case ValidKernelParam: 7513 ValidTypes.insert(PT.getTypePtr()); 7514 return; 7515 7516 case RecordKernelParam: 7517 break; 7518 } 7519 7520 // Track nested structs we will inspect 7521 SmallVector<const Decl *, 4> VisitStack; 7522 7523 // Track where we are in the nested structs. Items will migrate from 7524 // VisitStack to HistoryStack as we do the DFS for bad field. 7525 SmallVector<const FieldDecl *, 4> HistoryStack; 7526 HistoryStack.push_back(nullptr); 7527 7528 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7529 VisitStack.push_back(PD); 7530 7531 assert(VisitStack.back() && "First decl null?"); 7532 7533 do { 7534 const Decl *Next = VisitStack.pop_back_val(); 7535 if (!Next) { 7536 assert(!HistoryStack.empty()); 7537 // Found a marker, we have gone up a level 7538 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7539 ValidTypes.insert(Hist->getType().getTypePtr()); 7540 7541 continue; 7542 } 7543 7544 // Adds everything except the original parameter declaration (which is not a 7545 // field itself) to the history stack. 7546 const RecordDecl *RD; 7547 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7548 HistoryStack.push_back(Field); 7549 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7550 } else { 7551 RD = cast<RecordDecl>(Next); 7552 } 7553 7554 // Add a null marker so we know when we've gone back up a level 7555 VisitStack.push_back(nullptr); 7556 7557 for (const auto *FD : RD->fields()) { 7558 QualType QT = FD->getType(); 7559 7560 if (ValidTypes.count(QT.getTypePtr())) 7561 continue; 7562 7563 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 7564 if (ParamType == ValidKernelParam) 7565 continue; 7566 7567 if (ParamType == RecordKernelParam) { 7568 VisitStack.push_back(FD); 7569 continue; 7570 } 7571 7572 // OpenCL v1.2 s6.9.p: 7573 // Arguments to kernel functions that are declared to be a struct or union 7574 // do not allow OpenCL objects to be passed as elements of the struct or 7575 // union. 7576 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7577 ParamType == PrivatePtrKernelParam) { 7578 S.Diag(Param->getLocation(), 7579 diag::err_record_with_pointers_kernel_param) 7580 << PT->isUnionType() 7581 << PT; 7582 } else { 7583 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7584 } 7585 7586 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7587 << PD->getDeclName(); 7588 7589 // We have an error, now let's go back up through history and show where 7590 // the offending field came from 7591 for (ArrayRef<const FieldDecl *>::const_iterator 7592 I = HistoryStack.begin() + 1, 7593 E = HistoryStack.end(); 7594 I != E; ++I) { 7595 const FieldDecl *OuterField = *I; 7596 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7597 << OuterField->getType(); 7598 } 7599 7600 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7601 << QT->isPointerType() 7602 << QT; 7603 D.setInvalidType(); 7604 return; 7605 } 7606 } while (!VisitStack.empty()); 7607 } 7608 7609 NamedDecl* 7610 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7611 TypeSourceInfo *TInfo, LookupResult &Previous, 7612 MultiTemplateParamsArg TemplateParamLists, 7613 bool &AddToScope) { 7614 QualType R = TInfo->getType(); 7615 7616 assert(R.getTypePtr()->isFunctionType()); 7617 7618 // TODO: consider using NameInfo for diagnostic. 7619 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7620 DeclarationName Name = NameInfo.getName(); 7621 StorageClass SC = getFunctionStorageClass(*this, D); 7622 7623 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7624 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7625 diag::err_invalid_thread) 7626 << DeclSpec::getSpecifierName(TSCS); 7627 7628 if (D.isFirstDeclarationOfMember()) 7629 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7630 D.getIdentifierLoc()); 7631 7632 bool isFriend = false; 7633 FunctionTemplateDecl *FunctionTemplate = nullptr; 7634 bool isExplicitSpecialization = false; 7635 bool isFunctionTemplateSpecialization = false; 7636 7637 bool isDependentClassScopeExplicitSpecialization = false; 7638 bool HasExplicitTemplateArgs = false; 7639 TemplateArgumentListInfo TemplateArgs; 7640 7641 bool isVirtualOkay = false; 7642 7643 DeclContext *OriginalDC = DC; 7644 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7645 7646 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7647 isVirtualOkay); 7648 if (!NewFD) return nullptr; 7649 7650 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7651 NewFD->setTopLevelDeclInObjCContainer(); 7652 7653 // Set the lexical context. If this is a function-scope declaration, or has a 7654 // C++ scope specifier, or is the object of a friend declaration, the lexical 7655 // context will be different from the semantic context. 7656 NewFD->setLexicalDeclContext(CurContext); 7657 7658 if (IsLocalExternDecl) 7659 NewFD->setLocalExternDecl(); 7660 7661 if (getLangOpts().CPlusPlus) { 7662 bool isInline = D.getDeclSpec().isInlineSpecified(); 7663 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7664 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7665 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7666 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7667 isFriend = D.getDeclSpec().isFriendSpecified(); 7668 if (isFriend && !isInline && D.isFunctionDefinition()) { 7669 // C++ [class.friend]p5 7670 // A function can be defined in a friend declaration of a 7671 // class . . . . Such a function is implicitly inline. 7672 NewFD->setImplicitlyInline(); 7673 } 7674 7675 // If this is a method defined in an __interface, and is not a constructor 7676 // or an overloaded operator, then set the pure flag (isVirtual will already 7677 // return true). 7678 if (const CXXRecordDecl *Parent = 7679 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7680 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7681 NewFD->setPure(true); 7682 7683 // C++ [class.union]p2 7684 // A union can have member functions, but not virtual functions. 7685 if (isVirtual && Parent->isUnion()) 7686 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7687 } 7688 7689 SetNestedNameSpecifier(NewFD, D); 7690 isExplicitSpecialization = false; 7691 isFunctionTemplateSpecialization = false; 7692 if (D.isInvalidType()) 7693 NewFD->setInvalidDecl(); 7694 7695 // Match up the template parameter lists with the scope specifier, then 7696 // determine whether we have a template or a template specialization. 7697 bool Invalid = false; 7698 if (TemplateParameterList *TemplateParams = 7699 MatchTemplateParametersToScopeSpecifier( 7700 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7701 D.getCXXScopeSpec(), 7702 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7703 ? D.getName().TemplateId 7704 : nullptr, 7705 TemplateParamLists, isFriend, isExplicitSpecialization, 7706 Invalid)) { 7707 if (TemplateParams->size() > 0) { 7708 // This is a function template 7709 7710 // Check that we can declare a template here. 7711 if (CheckTemplateDeclScope(S, TemplateParams)) 7712 NewFD->setInvalidDecl(); 7713 7714 // A destructor cannot be a template. 7715 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7716 Diag(NewFD->getLocation(), diag::err_destructor_template); 7717 NewFD->setInvalidDecl(); 7718 } 7719 7720 // If we're adding a template to a dependent context, we may need to 7721 // rebuilding some of the types used within the template parameter list, 7722 // now that we know what the current instantiation is. 7723 if (DC->isDependentContext()) { 7724 ContextRAII SavedContext(*this, DC); 7725 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7726 Invalid = true; 7727 } 7728 7729 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7730 NewFD->getLocation(), 7731 Name, TemplateParams, 7732 NewFD); 7733 FunctionTemplate->setLexicalDeclContext(CurContext); 7734 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7735 7736 // For source fidelity, store the other template param lists. 7737 if (TemplateParamLists.size() > 1) { 7738 NewFD->setTemplateParameterListsInfo(Context, 7739 TemplateParamLists.drop_back(1)); 7740 } 7741 } else { 7742 // This is a function template specialization. 7743 isFunctionTemplateSpecialization = true; 7744 // For source fidelity, store all the template param lists. 7745 if (TemplateParamLists.size() > 0) 7746 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7747 7748 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7749 if (isFriend) { 7750 // We want to remove the "template<>", found here. 7751 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7752 7753 // If we remove the template<> and the name is not a 7754 // template-id, we're actually silently creating a problem: 7755 // the friend declaration will refer to an untemplated decl, 7756 // and clearly the user wants a template specialization. So 7757 // we need to insert '<>' after the name. 7758 SourceLocation InsertLoc; 7759 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7760 InsertLoc = D.getName().getSourceRange().getEnd(); 7761 InsertLoc = getLocForEndOfToken(InsertLoc); 7762 } 7763 7764 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7765 << Name << RemoveRange 7766 << FixItHint::CreateRemoval(RemoveRange) 7767 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7768 } 7769 } 7770 } 7771 else { 7772 // All template param lists were matched against the scope specifier: 7773 // this is NOT (an explicit specialization of) a template. 7774 if (TemplateParamLists.size() > 0) 7775 // For source fidelity, store all the template param lists. 7776 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7777 } 7778 7779 if (Invalid) { 7780 NewFD->setInvalidDecl(); 7781 if (FunctionTemplate) 7782 FunctionTemplate->setInvalidDecl(); 7783 } 7784 7785 // C++ [dcl.fct.spec]p5: 7786 // The virtual specifier shall only be used in declarations of 7787 // nonstatic class member functions that appear within a 7788 // member-specification of a class declaration; see 10.3. 7789 // 7790 if (isVirtual && !NewFD->isInvalidDecl()) { 7791 if (!isVirtualOkay) { 7792 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7793 diag::err_virtual_non_function); 7794 } else if (!CurContext->isRecord()) { 7795 // 'virtual' was specified outside of the class. 7796 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7797 diag::err_virtual_out_of_class) 7798 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7799 } else if (NewFD->getDescribedFunctionTemplate()) { 7800 // C++ [temp.mem]p3: 7801 // A member function template shall not be virtual. 7802 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7803 diag::err_virtual_member_function_template) 7804 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7805 } else { 7806 // Okay: Add virtual to the method. 7807 NewFD->setVirtualAsWritten(true); 7808 } 7809 7810 if (getLangOpts().CPlusPlus14 && 7811 NewFD->getReturnType()->isUndeducedType()) 7812 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7813 } 7814 7815 if (getLangOpts().CPlusPlus14 && 7816 (NewFD->isDependentContext() || 7817 (isFriend && CurContext->isDependentContext())) && 7818 NewFD->getReturnType()->isUndeducedType()) { 7819 // If the function template is referenced directly (for instance, as a 7820 // member of the current instantiation), pretend it has a dependent type. 7821 // This is not really justified by the standard, but is the only sane 7822 // thing to do. 7823 // FIXME: For a friend function, we have not marked the function as being 7824 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7825 const FunctionProtoType *FPT = 7826 NewFD->getType()->castAs<FunctionProtoType>(); 7827 QualType Result = 7828 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7829 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7830 FPT->getExtProtoInfo())); 7831 } 7832 7833 // C++ [dcl.fct.spec]p3: 7834 // The inline specifier shall not appear on a block scope function 7835 // declaration. 7836 if (isInline && !NewFD->isInvalidDecl()) { 7837 if (CurContext->isFunctionOrMethod()) { 7838 // 'inline' is not allowed on block scope function declaration. 7839 Diag(D.getDeclSpec().getInlineSpecLoc(), 7840 diag::err_inline_declaration_block_scope) << Name 7841 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7842 } 7843 } 7844 7845 // C++ [dcl.fct.spec]p6: 7846 // The explicit specifier shall be used only in the declaration of a 7847 // constructor or conversion function within its class definition; 7848 // see 12.3.1 and 12.3.2. 7849 if (isExplicit && !NewFD->isInvalidDecl()) { 7850 if (!CurContext->isRecord()) { 7851 // 'explicit' was specified outside of the class. 7852 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7853 diag::err_explicit_out_of_class) 7854 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7855 } else if (!isa<CXXConstructorDecl>(NewFD) && 7856 !isa<CXXConversionDecl>(NewFD)) { 7857 // 'explicit' was specified on a function that wasn't a constructor 7858 // or conversion function. 7859 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7860 diag::err_explicit_non_ctor_or_conv_function) 7861 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7862 } 7863 } 7864 7865 if (isConstexpr) { 7866 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7867 // are implicitly inline. 7868 NewFD->setImplicitlyInline(); 7869 7870 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7871 // be either constructors or to return a literal type. Therefore, 7872 // destructors cannot be declared constexpr. 7873 if (isa<CXXDestructorDecl>(NewFD)) 7874 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7875 } 7876 7877 if (isConcept) { 7878 // This is a function concept. 7879 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 7880 FTD->setConcept(); 7881 7882 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7883 // applied only to the definition of a function template [...] 7884 if (!D.isFunctionDefinition()) { 7885 Diag(D.getDeclSpec().getConceptSpecLoc(), 7886 diag::err_function_concept_not_defined); 7887 NewFD->setInvalidDecl(); 7888 } 7889 7890 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 7891 // have no exception-specification and is treated as if it were specified 7892 // with noexcept(true) (15.4). [...] 7893 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 7894 if (FPT->hasExceptionSpec()) { 7895 SourceRange Range; 7896 if (D.isFunctionDeclarator()) 7897 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 7898 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 7899 << FixItHint::CreateRemoval(Range); 7900 NewFD->setInvalidDecl(); 7901 } else { 7902 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 7903 } 7904 7905 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 7906 // following restrictions: 7907 // - The declared return type shall have the type bool. 7908 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 7909 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 7910 NewFD->setInvalidDecl(); 7911 } 7912 7913 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 7914 // following restrictions: 7915 // - The declaration's parameter list shall be equivalent to an empty 7916 // parameter list. 7917 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 7918 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 7919 } 7920 7921 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 7922 // implicity defined to be a constexpr declaration (implicitly inline) 7923 NewFD->setImplicitlyInline(); 7924 7925 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 7926 // be declared with the thread_local, inline, friend, or constexpr 7927 // specifiers, [...] 7928 if (isInline) { 7929 Diag(D.getDeclSpec().getInlineSpecLoc(), 7930 diag::err_concept_decl_invalid_specifiers) 7931 << 1 << 1; 7932 NewFD->setInvalidDecl(true); 7933 } 7934 7935 if (isFriend) { 7936 Diag(D.getDeclSpec().getFriendSpecLoc(), 7937 diag::err_concept_decl_invalid_specifiers) 7938 << 1 << 2; 7939 NewFD->setInvalidDecl(true); 7940 } 7941 7942 if (isConstexpr) { 7943 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7944 diag::err_concept_decl_invalid_specifiers) 7945 << 1 << 3; 7946 NewFD->setInvalidDecl(true); 7947 } 7948 7949 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7950 // applied only to the definition of a function template or variable 7951 // template, declared in namespace scope. 7952 if (isFunctionTemplateSpecialization) { 7953 Diag(D.getDeclSpec().getConceptSpecLoc(), 7954 diag::err_concept_specified_specialization) << 1; 7955 NewFD->setInvalidDecl(true); 7956 return NewFD; 7957 } 7958 } 7959 7960 // If __module_private__ was specified, mark the function accordingly. 7961 if (D.getDeclSpec().isModulePrivateSpecified()) { 7962 if (isFunctionTemplateSpecialization) { 7963 SourceLocation ModulePrivateLoc 7964 = D.getDeclSpec().getModulePrivateSpecLoc(); 7965 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7966 << 0 7967 << FixItHint::CreateRemoval(ModulePrivateLoc); 7968 } else { 7969 NewFD->setModulePrivate(); 7970 if (FunctionTemplate) 7971 FunctionTemplate->setModulePrivate(); 7972 } 7973 } 7974 7975 if (isFriend) { 7976 if (FunctionTemplate) { 7977 FunctionTemplate->setObjectOfFriendDecl(); 7978 FunctionTemplate->setAccess(AS_public); 7979 } 7980 NewFD->setObjectOfFriendDecl(); 7981 NewFD->setAccess(AS_public); 7982 } 7983 7984 // If a function is defined as defaulted or deleted, mark it as such now. 7985 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7986 // definition kind to FDK_Definition. 7987 switch (D.getFunctionDefinitionKind()) { 7988 case FDK_Declaration: 7989 case FDK_Definition: 7990 break; 7991 7992 case FDK_Defaulted: 7993 NewFD->setDefaulted(); 7994 break; 7995 7996 case FDK_Deleted: 7997 NewFD->setDeletedAsWritten(); 7998 break; 7999 } 8000 8001 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8002 D.isFunctionDefinition()) { 8003 // C++ [class.mfct]p2: 8004 // A member function may be defined (8.4) in its class definition, in 8005 // which case it is an inline member function (7.1.2) 8006 NewFD->setImplicitlyInline(); 8007 } 8008 8009 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8010 !CurContext->isRecord()) { 8011 // C++ [class.static]p1: 8012 // A data or function member of a class may be declared static 8013 // in a class definition, in which case it is a static member of 8014 // the class. 8015 8016 // Complain about the 'static' specifier if it's on an out-of-line 8017 // member function definition. 8018 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8019 diag::err_static_out_of_line) 8020 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8021 } 8022 8023 // C++11 [except.spec]p15: 8024 // A deallocation function with no exception-specification is treated 8025 // as if it were specified with noexcept(true). 8026 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8027 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8028 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8029 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8030 NewFD->setType(Context.getFunctionType( 8031 FPT->getReturnType(), FPT->getParamTypes(), 8032 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8033 } 8034 8035 // Filter out previous declarations that don't match the scope. 8036 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8037 D.getCXXScopeSpec().isNotEmpty() || 8038 isExplicitSpecialization || 8039 isFunctionTemplateSpecialization); 8040 8041 // Handle GNU asm-label extension (encoded as an attribute). 8042 if (Expr *E = (Expr*) D.getAsmLabel()) { 8043 // The parser guarantees this is a string. 8044 StringLiteral *SE = cast<StringLiteral>(E); 8045 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8046 SE->getString(), 0)); 8047 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8048 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8049 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8050 if (I != ExtnameUndeclaredIdentifiers.end()) { 8051 if (isDeclExternC(NewFD)) { 8052 NewFD->addAttr(I->second); 8053 ExtnameUndeclaredIdentifiers.erase(I); 8054 } else 8055 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8056 << /*Variable*/0 << NewFD; 8057 } 8058 } 8059 8060 // Copy the parameter declarations from the declarator D to the function 8061 // declaration NewFD, if they are available. First scavenge them into Params. 8062 SmallVector<ParmVarDecl*, 16> Params; 8063 if (D.isFunctionDeclarator()) { 8064 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8065 8066 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8067 // function that takes no arguments, not a function that takes a 8068 // single void argument. 8069 // We let through "const void" here because Sema::GetTypeForDeclarator 8070 // already checks for that case. 8071 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8072 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8073 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8074 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8075 Param->setDeclContext(NewFD); 8076 Params.push_back(Param); 8077 8078 if (Param->isInvalidDecl()) 8079 NewFD->setInvalidDecl(); 8080 } 8081 } 8082 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8083 // When we're declaring a function with a typedef, typeof, etc as in the 8084 // following example, we'll need to synthesize (unnamed) 8085 // parameters for use in the declaration. 8086 // 8087 // @code 8088 // typedef void fn(int); 8089 // fn f; 8090 // @endcode 8091 8092 // Synthesize a parameter for each argument type. 8093 for (const auto &AI : FT->param_types()) { 8094 ParmVarDecl *Param = 8095 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8096 Param->setScopeInfo(0, Params.size()); 8097 Params.push_back(Param); 8098 } 8099 } else { 8100 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8101 "Should not need args for typedef of non-prototype fn"); 8102 } 8103 8104 // Finally, we know we have the right number of parameters, install them. 8105 NewFD->setParams(Params); 8106 8107 // Find all anonymous symbols defined during the declaration of this function 8108 // and add to NewFD. This lets us track decls such 'enum Y' in: 8109 // 8110 // void f(enum Y {AA} x) {} 8111 // 8112 // which would otherwise incorrectly end up in the translation unit scope. 8113 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 8114 DeclsInPrototypeScope.clear(); 8115 8116 if (D.getDeclSpec().isNoreturnSpecified()) 8117 NewFD->addAttr( 8118 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8119 Context, 0)); 8120 8121 // Functions returning a variably modified type violate C99 6.7.5.2p2 8122 // because all functions have linkage. 8123 if (!NewFD->isInvalidDecl() && 8124 NewFD->getReturnType()->isVariablyModifiedType()) { 8125 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8126 NewFD->setInvalidDecl(); 8127 } 8128 8129 // Apply an implicit SectionAttr if #pragma code_seg is active. 8130 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8131 !NewFD->hasAttr<SectionAttr>()) { 8132 NewFD->addAttr( 8133 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8134 CodeSegStack.CurrentValue->getString(), 8135 CodeSegStack.CurrentPragmaLocation)); 8136 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8137 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8138 ASTContext::PSF_Read, 8139 NewFD)) 8140 NewFD->dropAttr<SectionAttr>(); 8141 } 8142 8143 // Handle attributes. 8144 ProcessDeclAttributes(S, NewFD, D); 8145 8146 if (getLangOpts().CUDA) 8147 maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous); 8148 8149 if (getLangOpts().OpenCL) { 8150 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8151 // type declaration will generate a compilation error. 8152 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8153 if (AddressSpace == LangAS::opencl_local || 8154 AddressSpace == LangAS::opencl_global || 8155 AddressSpace == LangAS::opencl_constant) { 8156 Diag(NewFD->getLocation(), 8157 diag::err_opencl_return_value_with_address_space); 8158 NewFD->setInvalidDecl(); 8159 } 8160 } 8161 8162 if (!getLangOpts().CPlusPlus) { 8163 // Perform semantic checking on the function declaration. 8164 bool isExplicitSpecialization=false; 8165 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8166 CheckMain(NewFD, D.getDeclSpec()); 8167 8168 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8169 CheckMSVCRTEntryPoint(NewFD); 8170 8171 if (!NewFD->isInvalidDecl()) 8172 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8173 isExplicitSpecialization)); 8174 else if (!Previous.empty()) 8175 // Recover gracefully from an invalid redeclaration. 8176 D.setRedeclaration(true); 8177 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8178 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8179 "previous declaration set still overloaded"); 8180 8181 // Diagnose no-prototype function declarations with calling conventions that 8182 // don't support variadic calls. Only do this in C and do it after merging 8183 // possibly prototyped redeclarations. 8184 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8185 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8186 CallingConv CC = FT->getExtInfo().getCC(); 8187 if (!supportsVariadicCall(CC)) { 8188 // Windows system headers sometimes accidentally use stdcall without 8189 // (void) parameters, so we relax this to a warning. 8190 int DiagID = 8191 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8192 Diag(NewFD->getLocation(), DiagID) 8193 << FunctionType::getNameForCallConv(CC); 8194 } 8195 } 8196 } else { 8197 // C++11 [replacement.functions]p3: 8198 // The program's definitions shall not be specified as inline. 8199 // 8200 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8201 // 8202 // Suppress the diagnostic if the function is __attribute__((used)), since 8203 // that forces an external definition to be emitted. 8204 if (D.getDeclSpec().isInlineSpecified() && 8205 NewFD->isReplaceableGlobalAllocationFunction() && 8206 !NewFD->hasAttr<UsedAttr>()) 8207 Diag(D.getDeclSpec().getInlineSpecLoc(), 8208 diag::ext_operator_new_delete_declared_inline) 8209 << NewFD->getDeclName(); 8210 8211 // If the declarator is a template-id, translate the parser's template 8212 // argument list into our AST format. 8213 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8214 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8215 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8216 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8217 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8218 TemplateId->NumArgs); 8219 translateTemplateArguments(TemplateArgsPtr, 8220 TemplateArgs); 8221 8222 HasExplicitTemplateArgs = true; 8223 8224 if (NewFD->isInvalidDecl()) { 8225 HasExplicitTemplateArgs = false; 8226 } else if (FunctionTemplate) { 8227 // Function template with explicit template arguments. 8228 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8229 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8230 8231 HasExplicitTemplateArgs = false; 8232 } else { 8233 assert((isFunctionTemplateSpecialization || 8234 D.getDeclSpec().isFriendSpecified()) && 8235 "should have a 'template<>' for this decl"); 8236 // "friend void foo<>(int);" is an implicit specialization decl. 8237 isFunctionTemplateSpecialization = true; 8238 } 8239 } else if (isFriend && isFunctionTemplateSpecialization) { 8240 // This combination is only possible in a recovery case; the user 8241 // wrote something like: 8242 // template <> friend void foo(int); 8243 // which we're recovering from as if the user had written: 8244 // friend void foo<>(int); 8245 // Go ahead and fake up a template id. 8246 HasExplicitTemplateArgs = true; 8247 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8248 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8249 } 8250 8251 // If it's a friend (and only if it's a friend), it's possible 8252 // that either the specialized function type or the specialized 8253 // template is dependent, and therefore matching will fail. In 8254 // this case, don't check the specialization yet. 8255 bool InstantiationDependent = false; 8256 if (isFunctionTemplateSpecialization && isFriend && 8257 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8258 TemplateSpecializationType::anyDependentTemplateArguments( 8259 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 8260 InstantiationDependent))) { 8261 assert(HasExplicitTemplateArgs && 8262 "friend function specialization without template args"); 8263 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8264 Previous)) 8265 NewFD->setInvalidDecl(); 8266 } else if (isFunctionTemplateSpecialization) { 8267 if (CurContext->isDependentContext() && CurContext->isRecord() 8268 && !isFriend) { 8269 isDependentClassScopeExplicitSpecialization = true; 8270 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8271 diag::ext_function_specialization_in_class : 8272 diag::err_function_specialization_in_class) 8273 << NewFD->getDeclName(); 8274 } else if (CheckFunctionTemplateSpecialization(NewFD, 8275 (HasExplicitTemplateArgs ? &TemplateArgs 8276 : nullptr), 8277 Previous)) 8278 NewFD->setInvalidDecl(); 8279 8280 // C++ [dcl.stc]p1: 8281 // A storage-class-specifier shall not be specified in an explicit 8282 // specialization (14.7.3) 8283 FunctionTemplateSpecializationInfo *Info = 8284 NewFD->getTemplateSpecializationInfo(); 8285 if (Info && SC != SC_None) { 8286 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8287 Diag(NewFD->getLocation(), 8288 diag::err_explicit_specialization_inconsistent_storage_class) 8289 << SC 8290 << FixItHint::CreateRemoval( 8291 D.getDeclSpec().getStorageClassSpecLoc()); 8292 8293 else 8294 Diag(NewFD->getLocation(), 8295 diag::ext_explicit_specialization_storage_class) 8296 << FixItHint::CreateRemoval( 8297 D.getDeclSpec().getStorageClassSpecLoc()); 8298 } 8299 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 8300 if (CheckMemberSpecialization(NewFD, Previous)) 8301 NewFD->setInvalidDecl(); 8302 } 8303 8304 // Perform semantic checking on the function declaration. 8305 if (!isDependentClassScopeExplicitSpecialization) { 8306 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8307 CheckMain(NewFD, D.getDeclSpec()); 8308 8309 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8310 CheckMSVCRTEntryPoint(NewFD); 8311 8312 if (!NewFD->isInvalidDecl()) 8313 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8314 isExplicitSpecialization)); 8315 else if (!Previous.empty()) 8316 // Recover gracefully from an invalid redeclaration. 8317 D.setRedeclaration(true); 8318 } 8319 8320 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8321 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8322 "previous declaration set still overloaded"); 8323 8324 NamedDecl *PrincipalDecl = (FunctionTemplate 8325 ? cast<NamedDecl>(FunctionTemplate) 8326 : NewFD); 8327 8328 if (isFriend && D.isRedeclaration()) { 8329 AccessSpecifier Access = AS_public; 8330 if (!NewFD->isInvalidDecl()) 8331 Access = NewFD->getPreviousDecl()->getAccess(); 8332 8333 NewFD->setAccess(Access); 8334 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8335 } 8336 8337 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8338 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8339 PrincipalDecl->setNonMemberOperator(); 8340 8341 // If we have a function template, check the template parameter 8342 // list. This will check and merge default template arguments. 8343 if (FunctionTemplate) { 8344 FunctionTemplateDecl *PrevTemplate = 8345 FunctionTemplate->getPreviousDecl(); 8346 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8347 PrevTemplate ? PrevTemplate->getTemplateParameters() 8348 : nullptr, 8349 D.getDeclSpec().isFriendSpecified() 8350 ? (D.isFunctionDefinition() 8351 ? TPC_FriendFunctionTemplateDefinition 8352 : TPC_FriendFunctionTemplate) 8353 : (D.getCXXScopeSpec().isSet() && 8354 DC && DC->isRecord() && 8355 DC->isDependentContext()) 8356 ? TPC_ClassTemplateMember 8357 : TPC_FunctionTemplate); 8358 } 8359 8360 if (NewFD->isInvalidDecl()) { 8361 // Ignore all the rest of this. 8362 } else if (!D.isRedeclaration()) { 8363 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8364 AddToScope }; 8365 // Fake up an access specifier if it's supposed to be a class member. 8366 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8367 NewFD->setAccess(AS_public); 8368 8369 // Qualified decls generally require a previous declaration. 8370 if (D.getCXXScopeSpec().isSet()) { 8371 // ...with the major exception of templated-scope or 8372 // dependent-scope friend declarations. 8373 8374 // TODO: we currently also suppress this check in dependent 8375 // contexts because (1) the parameter depth will be off when 8376 // matching friend templates and (2) we might actually be 8377 // selecting a friend based on a dependent factor. But there 8378 // are situations where these conditions don't apply and we 8379 // can actually do this check immediately. 8380 if (isFriend && 8381 (TemplateParamLists.size() || 8382 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8383 CurContext->isDependentContext())) { 8384 // ignore these 8385 } else { 8386 // The user tried to provide an out-of-line definition for a 8387 // function that is a member of a class or namespace, but there 8388 // was no such member function declared (C++ [class.mfct]p2, 8389 // C++ [namespace.memdef]p2). For example: 8390 // 8391 // class X { 8392 // void f() const; 8393 // }; 8394 // 8395 // void X::f() { } // ill-formed 8396 // 8397 // Complain about this problem, and attempt to suggest close 8398 // matches (e.g., those that differ only in cv-qualifiers and 8399 // whether the parameter types are references). 8400 8401 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8402 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8403 AddToScope = ExtraArgs.AddToScope; 8404 return Result; 8405 } 8406 } 8407 8408 // Unqualified local friend declarations are required to resolve 8409 // to something. 8410 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8411 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8412 *this, Previous, NewFD, ExtraArgs, true, S)) { 8413 AddToScope = ExtraArgs.AddToScope; 8414 return Result; 8415 } 8416 } 8417 } else if (!D.isFunctionDefinition() && 8418 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8419 !isFriend && !isFunctionTemplateSpecialization && 8420 !isExplicitSpecialization) { 8421 // An out-of-line member function declaration must also be a 8422 // definition (C++ [class.mfct]p2). 8423 // Note that this is not the case for explicit specializations of 8424 // function templates or member functions of class templates, per 8425 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8426 // extension for compatibility with old SWIG code which likes to 8427 // generate them. 8428 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8429 << D.getCXXScopeSpec().getRange(); 8430 } 8431 } 8432 8433 ProcessPragmaWeak(S, NewFD); 8434 checkAttributesAfterMerging(*this, *NewFD); 8435 8436 AddKnownFunctionAttributes(NewFD); 8437 8438 if (NewFD->hasAttr<OverloadableAttr>() && 8439 !NewFD->getType()->getAs<FunctionProtoType>()) { 8440 Diag(NewFD->getLocation(), 8441 diag::err_attribute_overloadable_no_prototype) 8442 << NewFD; 8443 8444 // Turn this into a variadic function with no parameters. 8445 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8446 FunctionProtoType::ExtProtoInfo EPI( 8447 Context.getDefaultCallingConvention(true, false)); 8448 EPI.Variadic = true; 8449 EPI.ExtInfo = FT->getExtInfo(); 8450 8451 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8452 NewFD->setType(R); 8453 } 8454 8455 // If there's a #pragma GCC visibility in scope, and this isn't a class 8456 // member, set the visibility of this function. 8457 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8458 AddPushedVisibilityAttribute(NewFD); 8459 8460 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8461 // marking the function. 8462 AddCFAuditedAttribute(NewFD); 8463 8464 // If this is a function definition, check if we have to apply optnone due to 8465 // a pragma. 8466 if(D.isFunctionDefinition()) 8467 AddRangeBasedOptnone(NewFD); 8468 8469 // If this is the first declaration of an extern C variable, update 8470 // the map of such variables. 8471 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8472 isIncompleteDeclExternC(*this, NewFD)) 8473 RegisterLocallyScopedExternCDecl(NewFD, S); 8474 8475 // Set this FunctionDecl's range up to the right paren. 8476 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8477 8478 if (D.isRedeclaration() && !Previous.empty()) { 8479 checkDLLAttributeRedeclaration( 8480 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8481 isExplicitSpecialization || isFunctionTemplateSpecialization, 8482 D.isFunctionDefinition()); 8483 } 8484 8485 if (getLangOpts().CUDA) { 8486 IdentifierInfo *II = NewFD->getIdentifier(); 8487 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8488 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8489 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8490 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8491 8492 Context.setcudaConfigureCallDecl(NewFD); 8493 } 8494 8495 // Variadic functions, other than a *declaration* of printf, are not allowed 8496 // in device-side CUDA code, unless someone passed 8497 // -fcuda-allow-variadic-functions. 8498 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8499 (NewFD->hasAttr<CUDADeviceAttr>() || 8500 NewFD->hasAttr<CUDAGlobalAttr>()) && 8501 !(II && II->isStr("printf") && NewFD->isExternC() && 8502 !D.isFunctionDefinition())) { 8503 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8504 } 8505 } 8506 8507 if (getLangOpts().CPlusPlus) { 8508 if (FunctionTemplate) { 8509 if (NewFD->isInvalidDecl()) 8510 FunctionTemplate->setInvalidDecl(); 8511 return FunctionTemplate; 8512 } 8513 } 8514 8515 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8516 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8517 if ((getLangOpts().OpenCLVersion >= 120) 8518 && (SC == SC_Static)) { 8519 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8520 D.setInvalidType(); 8521 } 8522 8523 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8524 if (!NewFD->getReturnType()->isVoidType()) { 8525 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8526 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8527 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8528 : FixItHint()); 8529 D.setInvalidType(); 8530 } 8531 8532 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8533 for (auto Param : NewFD->params()) 8534 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8535 } 8536 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 8537 PE = NewFD->param_end(); PI != PE; ++PI) { 8538 ParmVarDecl *Param = *PI; 8539 QualType PT = Param->getType(); 8540 8541 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8542 // types. 8543 if (getLangOpts().OpenCLVersion >= 200) { 8544 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8545 QualType ElemTy = PipeTy->getElementType(); 8546 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8547 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8548 D.setInvalidType(); 8549 } 8550 } 8551 } 8552 } 8553 8554 MarkUnusedFileScopedDecl(NewFD); 8555 8556 // Here we have an function template explicit specialization at class scope. 8557 // The actually specialization will be postponed to template instatiation 8558 // time via the ClassScopeFunctionSpecializationDecl node. 8559 if (isDependentClassScopeExplicitSpecialization) { 8560 ClassScopeFunctionSpecializationDecl *NewSpec = 8561 ClassScopeFunctionSpecializationDecl::Create( 8562 Context, CurContext, SourceLocation(), 8563 cast<CXXMethodDecl>(NewFD), 8564 HasExplicitTemplateArgs, TemplateArgs); 8565 CurContext->addDecl(NewSpec); 8566 AddToScope = false; 8567 } 8568 8569 return NewFD; 8570 } 8571 8572 /// \brief Perform semantic checking of a new function declaration. 8573 /// 8574 /// Performs semantic analysis of the new function declaration 8575 /// NewFD. This routine performs all semantic checking that does not 8576 /// require the actual declarator involved in the declaration, and is 8577 /// used both for the declaration of functions as they are parsed 8578 /// (called via ActOnDeclarator) and for the declaration of functions 8579 /// that have been instantiated via C++ template instantiation (called 8580 /// via InstantiateDecl). 8581 /// 8582 /// \param IsExplicitSpecialization whether this new function declaration is 8583 /// an explicit specialization of the previous declaration. 8584 /// 8585 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8586 /// 8587 /// \returns true if the function declaration is a redeclaration. 8588 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8589 LookupResult &Previous, 8590 bool IsExplicitSpecialization) { 8591 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8592 "Variably modified return types are not handled here"); 8593 8594 // Determine whether the type of this function should be merged with 8595 // a previous visible declaration. This never happens for functions in C++, 8596 // and always happens in C if the previous declaration was visible. 8597 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8598 !Previous.isShadowed(); 8599 8600 bool Redeclaration = false; 8601 NamedDecl *OldDecl = nullptr; 8602 8603 // Merge or overload the declaration with an existing declaration of 8604 // the same name, if appropriate. 8605 if (!Previous.empty()) { 8606 // Determine whether NewFD is an overload of PrevDecl or 8607 // a declaration that requires merging. If it's an overload, 8608 // there's no more work to do here; we'll just add the new 8609 // function to the scope. 8610 if (!AllowOverloadingOfFunction(Previous, Context)) { 8611 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8612 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8613 Redeclaration = true; 8614 OldDecl = Candidate; 8615 } 8616 } else { 8617 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8618 /*NewIsUsingDecl*/ false)) { 8619 case Ovl_Match: 8620 Redeclaration = true; 8621 break; 8622 8623 case Ovl_NonFunction: 8624 Redeclaration = true; 8625 break; 8626 8627 case Ovl_Overload: 8628 Redeclaration = false; 8629 break; 8630 } 8631 8632 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8633 // If a function name is overloadable in C, then every function 8634 // with that name must be marked "overloadable". 8635 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8636 << Redeclaration << NewFD; 8637 NamedDecl *OverloadedDecl = nullptr; 8638 if (Redeclaration) 8639 OverloadedDecl = OldDecl; 8640 else if (!Previous.empty()) 8641 OverloadedDecl = Previous.getRepresentativeDecl(); 8642 if (OverloadedDecl) 8643 Diag(OverloadedDecl->getLocation(), 8644 diag::note_attribute_overloadable_prev_overload); 8645 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8646 } 8647 } 8648 } 8649 8650 // Check for a previous extern "C" declaration with this name. 8651 if (!Redeclaration && 8652 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8653 if (!Previous.empty()) { 8654 // This is an extern "C" declaration with the same name as a previous 8655 // declaration, and thus redeclares that entity... 8656 Redeclaration = true; 8657 OldDecl = Previous.getFoundDecl(); 8658 MergeTypeWithPrevious = false; 8659 8660 // ... except in the presence of __attribute__((overloadable)). 8661 if (OldDecl->hasAttr<OverloadableAttr>()) { 8662 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8663 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8664 << Redeclaration << NewFD; 8665 Diag(Previous.getFoundDecl()->getLocation(), 8666 diag::note_attribute_overloadable_prev_overload); 8667 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8668 } 8669 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8670 Redeclaration = false; 8671 OldDecl = nullptr; 8672 } 8673 } 8674 } 8675 } 8676 8677 // C++11 [dcl.constexpr]p8: 8678 // A constexpr specifier for a non-static member function that is not 8679 // a constructor declares that member function to be const. 8680 // 8681 // This needs to be delayed until we know whether this is an out-of-line 8682 // definition of a static member function. 8683 // 8684 // This rule is not present in C++1y, so we produce a backwards 8685 // compatibility warning whenever it happens in C++11. 8686 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8687 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8688 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8689 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8690 CXXMethodDecl *OldMD = nullptr; 8691 if (OldDecl) 8692 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8693 if (!OldMD || !OldMD->isStatic()) { 8694 const FunctionProtoType *FPT = 8695 MD->getType()->castAs<FunctionProtoType>(); 8696 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8697 EPI.TypeQuals |= Qualifiers::Const; 8698 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8699 FPT->getParamTypes(), EPI)); 8700 8701 // Warn that we did this, if we're not performing template instantiation. 8702 // In that case, we'll have warned already when the template was defined. 8703 if (ActiveTemplateInstantiations.empty()) { 8704 SourceLocation AddConstLoc; 8705 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8706 .IgnoreParens().getAs<FunctionTypeLoc>()) 8707 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8708 8709 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8710 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8711 } 8712 } 8713 } 8714 8715 if (Redeclaration) { 8716 // NewFD and OldDecl represent declarations that need to be 8717 // merged. 8718 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8719 NewFD->setInvalidDecl(); 8720 return Redeclaration; 8721 } 8722 8723 Previous.clear(); 8724 Previous.addDecl(OldDecl); 8725 8726 if (FunctionTemplateDecl *OldTemplateDecl 8727 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8728 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8729 FunctionTemplateDecl *NewTemplateDecl 8730 = NewFD->getDescribedFunctionTemplate(); 8731 assert(NewTemplateDecl && "Template/non-template mismatch"); 8732 if (CXXMethodDecl *Method 8733 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8734 Method->setAccess(OldTemplateDecl->getAccess()); 8735 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8736 } 8737 8738 // If this is an explicit specialization of a member that is a function 8739 // template, mark it as a member specialization. 8740 if (IsExplicitSpecialization && 8741 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8742 NewTemplateDecl->setMemberSpecialization(); 8743 assert(OldTemplateDecl->isMemberSpecialization()); 8744 // Explicit specializations of a member template do not inherit deleted 8745 // status from the parent member template that they are specializing. 8746 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 8747 FunctionDecl *const OldTemplatedDecl = 8748 OldTemplateDecl->getTemplatedDecl(); 8749 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 8750 OldTemplatedDecl->setDeletedAsWritten(false); 8751 } 8752 } 8753 8754 } else { 8755 // This needs to happen first so that 'inline' propagates. 8756 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8757 8758 if (isa<CXXMethodDecl>(NewFD)) 8759 NewFD->setAccess(OldDecl->getAccess()); 8760 } 8761 } 8762 8763 // Semantic checking for this function declaration (in isolation). 8764 8765 if (getLangOpts().CPlusPlus) { 8766 // C++-specific checks. 8767 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8768 CheckConstructor(Constructor); 8769 } else if (CXXDestructorDecl *Destructor = 8770 dyn_cast<CXXDestructorDecl>(NewFD)) { 8771 CXXRecordDecl *Record = Destructor->getParent(); 8772 QualType ClassType = Context.getTypeDeclType(Record); 8773 8774 // FIXME: Shouldn't we be able to perform this check even when the class 8775 // type is dependent? Both gcc and edg can handle that. 8776 if (!ClassType->isDependentType()) { 8777 DeclarationName Name 8778 = Context.DeclarationNames.getCXXDestructorName( 8779 Context.getCanonicalType(ClassType)); 8780 if (NewFD->getDeclName() != Name) { 8781 Diag(NewFD->getLocation(), diag::err_destructor_name); 8782 NewFD->setInvalidDecl(); 8783 return Redeclaration; 8784 } 8785 } 8786 } else if (CXXConversionDecl *Conversion 8787 = dyn_cast<CXXConversionDecl>(NewFD)) { 8788 ActOnConversionDeclarator(Conversion); 8789 } 8790 8791 // Find any virtual functions that this function overrides. 8792 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8793 if (!Method->isFunctionTemplateSpecialization() && 8794 !Method->getDescribedFunctionTemplate() && 8795 Method->isCanonicalDecl()) { 8796 if (AddOverriddenMethods(Method->getParent(), Method)) { 8797 // If the function was marked as "static", we have a problem. 8798 if (NewFD->getStorageClass() == SC_Static) { 8799 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8800 } 8801 } 8802 } 8803 8804 if (Method->isStatic()) 8805 checkThisInStaticMemberFunctionType(Method); 8806 } 8807 8808 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8809 if (NewFD->isOverloadedOperator() && 8810 CheckOverloadedOperatorDeclaration(NewFD)) { 8811 NewFD->setInvalidDecl(); 8812 return Redeclaration; 8813 } 8814 8815 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8816 if (NewFD->getLiteralIdentifier() && 8817 CheckLiteralOperatorDeclaration(NewFD)) { 8818 NewFD->setInvalidDecl(); 8819 return Redeclaration; 8820 } 8821 8822 // In C++, check default arguments now that we have merged decls. Unless 8823 // the lexical context is the class, because in this case this is done 8824 // during delayed parsing anyway. 8825 if (!CurContext->isRecord()) 8826 CheckCXXDefaultArguments(NewFD); 8827 8828 // If this function declares a builtin function, check the type of this 8829 // declaration against the expected type for the builtin. 8830 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8831 ASTContext::GetBuiltinTypeError Error; 8832 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8833 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8834 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8835 // The type of this function differs from the type of the builtin, 8836 // so forget about the builtin entirely. 8837 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 8838 } 8839 } 8840 8841 // If this function is declared as being extern "C", then check to see if 8842 // the function returns a UDT (class, struct, or union type) that is not C 8843 // compatible, and if it does, warn the user. 8844 // But, issue any diagnostic on the first declaration only. 8845 if (Previous.empty() && NewFD->isExternC()) { 8846 QualType R = NewFD->getReturnType(); 8847 if (R->isIncompleteType() && !R->isVoidType()) 8848 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8849 << NewFD << R; 8850 else if (!R.isPODType(Context) && !R->isVoidType() && 8851 !R->isObjCObjectPointerType()) 8852 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8853 } 8854 } 8855 return Redeclaration; 8856 } 8857 8858 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8859 // C++11 [basic.start.main]p3: 8860 // A program that [...] declares main to be inline, static or 8861 // constexpr is ill-formed. 8862 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8863 // appear in a declaration of main. 8864 // static main is not an error under C99, but we should warn about it. 8865 // We accept _Noreturn main as an extension. 8866 if (FD->getStorageClass() == SC_Static) 8867 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8868 ? diag::err_static_main : diag::warn_static_main) 8869 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8870 if (FD->isInlineSpecified()) 8871 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8872 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8873 if (DS.isNoreturnSpecified()) { 8874 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8875 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8876 Diag(NoreturnLoc, diag::ext_noreturn_main); 8877 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8878 << FixItHint::CreateRemoval(NoreturnRange); 8879 } 8880 if (FD->isConstexpr()) { 8881 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8882 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8883 FD->setConstexpr(false); 8884 } 8885 8886 if (getLangOpts().OpenCL) { 8887 Diag(FD->getLocation(), diag::err_opencl_no_main) 8888 << FD->hasAttr<OpenCLKernelAttr>(); 8889 FD->setInvalidDecl(); 8890 return; 8891 } 8892 8893 QualType T = FD->getType(); 8894 assert(T->isFunctionType() && "function decl is not of function type"); 8895 const FunctionType* FT = T->castAs<FunctionType>(); 8896 8897 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8898 // In C with GNU extensions we allow main() to have non-integer return 8899 // type, but we should warn about the extension, and we disable the 8900 // implicit-return-zero rule. 8901 8902 // GCC in C mode accepts qualified 'int'. 8903 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8904 FD->setHasImplicitReturnZero(true); 8905 else { 8906 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8907 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8908 if (RTRange.isValid()) 8909 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8910 << FixItHint::CreateReplacement(RTRange, "int"); 8911 } 8912 } else { 8913 // In C and C++, main magically returns 0 if you fall off the end; 8914 // set the flag which tells us that. 8915 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8916 8917 // All the standards say that main() should return 'int'. 8918 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8919 FD->setHasImplicitReturnZero(true); 8920 else { 8921 // Otherwise, this is just a flat-out error. 8922 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8923 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8924 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8925 : FixItHint()); 8926 FD->setInvalidDecl(true); 8927 } 8928 } 8929 8930 // Treat protoless main() as nullary. 8931 if (isa<FunctionNoProtoType>(FT)) return; 8932 8933 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8934 unsigned nparams = FTP->getNumParams(); 8935 assert(FD->getNumParams() == nparams); 8936 8937 bool HasExtraParameters = (nparams > 3); 8938 8939 if (FTP->isVariadic()) { 8940 Diag(FD->getLocation(), diag::ext_variadic_main); 8941 // FIXME: if we had information about the location of the ellipsis, we 8942 // could add a FixIt hint to remove it as a parameter. 8943 } 8944 8945 // Darwin passes an undocumented fourth argument of type char**. If 8946 // other platforms start sprouting these, the logic below will start 8947 // getting shifty. 8948 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8949 HasExtraParameters = false; 8950 8951 if (HasExtraParameters) { 8952 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8953 FD->setInvalidDecl(true); 8954 nparams = 3; 8955 } 8956 8957 // FIXME: a lot of the following diagnostics would be improved 8958 // if we had some location information about types. 8959 8960 QualType CharPP = 8961 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8962 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8963 8964 for (unsigned i = 0; i < nparams; ++i) { 8965 QualType AT = FTP->getParamType(i); 8966 8967 bool mismatch = true; 8968 8969 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8970 mismatch = false; 8971 else if (Expected[i] == CharPP) { 8972 // As an extension, the following forms are okay: 8973 // char const ** 8974 // char const * const * 8975 // char * const * 8976 8977 QualifierCollector qs; 8978 const PointerType* PT; 8979 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8980 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8981 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8982 Context.CharTy)) { 8983 qs.removeConst(); 8984 mismatch = !qs.empty(); 8985 } 8986 } 8987 8988 if (mismatch) { 8989 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8990 // TODO: suggest replacing given type with expected type 8991 FD->setInvalidDecl(true); 8992 } 8993 } 8994 8995 if (nparams == 1 && !FD->isInvalidDecl()) { 8996 Diag(FD->getLocation(), diag::warn_main_one_arg); 8997 } 8998 8999 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9000 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9001 FD->setInvalidDecl(); 9002 } 9003 } 9004 9005 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9006 QualType T = FD->getType(); 9007 assert(T->isFunctionType() && "function decl is not of function type"); 9008 const FunctionType *FT = T->castAs<FunctionType>(); 9009 9010 // Set an implicit return of 'zero' if the function can return some integral, 9011 // enumeration, pointer or nullptr type. 9012 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9013 FT->getReturnType()->isAnyPointerType() || 9014 FT->getReturnType()->isNullPtrType()) 9015 // DllMain is exempt because a return value of zero means it failed. 9016 if (FD->getName() != "DllMain") 9017 FD->setHasImplicitReturnZero(true); 9018 9019 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9020 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9021 FD->setInvalidDecl(); 9022 } 9023 } 9024 9025 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9026 // FIXME: Need strict checking. In C89, we need to check for 9027 // any assignment, increment, decrement, function-calls, or 9028 // commas outside of a sizeof. In C99, it's the same list, 9029 // except that the aforementioned are allowed in unevaluated 9030 // expressions. Everything else falls under the 9031 // "may accept other forms of constant expressions" exception. 9032 // (We never end up here for C++, so the constant expression 9033 // rules there don't matter.) 9034 const Expr *Culprit; 9035 if (Init->isConstantInitializer(Context, false, &Culprit)) 9036 return false; 9037 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9038 << Culprit->getSourceRange(); 9039 return true; 9040 } 9041 9042 namespace { 9043 // Visits an initialization expression to see if OrigDecl is evaluated in 9044 // its own initialization and throws a warning if it does. 9045 class SelfReferenceChecker 9046 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9047 Sema &S; 9048 Decl *OrigDecl; 9049 bool isRecordType; 9050 bool isPODType; 9051 bool isReferenceType; 9052 9053 bool isInitList; 9054 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9055 9056 public: 9057 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9058 9059 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9060 S(S), OrigDecl(OrigDecl) { 9061 isPODType = false; 9062 isRecordType = false; 9063 isReferenceType = false; 9064 isInitList = false; 9065 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9066 isPODType = VD->getType().isPODType(S.Context); 9067 isRecordType = VD->getType()->isRecordType(); 9068 isReferenceType = VD->getType()->isReferenceType(); 9069 } 9070 } 9071 9072 // For most expressions, just call the visitor. For initializer lists, 9073 // track the index of the field being initialized since fields are 9074 // initialized in order allowing use of previously initialized fields. 9075 void CheckExpr(Expr *E) { 9076 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9077 if (!InitList) { 9078 Visit(E); 9079 return; 9080 } 9081 9082 // Track and increment the index here. 9083 isInitList = true; 9084 InitFieldIndex.push_back(0); 9085 for (auto Child : InitList->children()) { 9086 CheckExpr(cast<Expr>(Child)); 9087 ++InitFieldIndex.back(); 9088 } 9089 InitFieldIndex.pop_back(); 9090 } 9091 9092 // Returns true if MemberExpr is checked and no futher checking is needed. 9093 // Returns false if additional checking is required. 9094 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9095 llvm::SmallVector<FieldDecl*, 4> Fields; 9096 Expr *Base = E; 9097 bool ReferenceField = false; 9098 9099 // Get the field memebers used. 9100 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9101 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9102 if (!FD) 9103 return false; 9104 Fields.push_back(FD); 9105 if (FD->getType()->isReferenceType()) 9106 ReferenceField = true; 9107 Base = ME->getBase()->IgnoreParenImpCasts(); 9108 } 9109 9110 // Keep checking only if the base Decl is the same. 9111 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9112 if (!DRE || DRE->getDecl() != OrigDecl) 9113 return false; 9114 9115 // A reference field can be bound to an unininitialized field. 9116 if (CheckReference && !ReferenceField) 9117 return true; 9118 9119 // Convert FieldDecls to their index number. 9120 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9121 for (const FieldDecl *I : llvm::reverse(Fields)) 9122 UsedFieldIndex.push_back(I->getFieldIndex()); 9123 9124 // See if a warning is needed by checking the first difference in index 9125 // numbers. If field being used has index less than the field being 9126 // initialized, then the use is safe. 9127 for (auto UsedIter = UsedFieldIndex.begin(), 9128 UsedEnd = UsedFieldIndex.end(), 9129 OrigIter = InitFieldIndex.begin(), 9130 OrigEnd = InitFieldIndex.end(); 9131 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9132 if (*UsedIter < *OrigIter) 9133 return true; 9134 if (*UsedIter > *OrigIter) 9135 break; 9136 } 9137 9138 // TODO: Add a different warning which will print the field names. 9139 HandleDeclRefExpr(DRE); 9140 return true; 9141 } 9142 9143 // For most expressions, the cast is directly above the DeclRefExpr. 9144 // For conditional operators, the cast can be outside the conditional 9145 // operator if both expressions are DeclRefExpr's. 9146 void HandleValue(Expr *E) { 9147 E = E->IgnoreParens(); 9148 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9149 HandleDeclRefExpr(DRE); 9150 return; 9151 } 9152 9153 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9154 Visit(CO->getCond()); 9155 HandleValue(CO->getTrueExpr()); 9156 HandleValue(CO->getFalseExpr()); 9157 return; 9158 } 9159 9160 if (BinaryConditionalOperator *BCO = 9161 dyn_cast<BinaryConditionalOperator>(E)) { 9162 Visit(BCO->getCond()); 9163 HandleValue(BCO->getFalseExpr()); 9164 return; 9165 } 9166 9167 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9168 HandleValue(OVE->getSourceExpr()); 9169 return; 9170 } 9171 9172 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9173 if (BO->getOpcode() == BO_Comma) { 9174 Visit(BO->getLHS()); 9175 HandleValue(BO->getRHS()); 9176 return; 9177 } 9178 } 9179 9180 if (isa<MemberExpr>(E)) { 9181 if (isInitList) { 9182 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9183 false /*CheckReference*/)) 9184 return; 9185 } 9186 9187 Expr *Base = E->IgnoreParenImpCasts(); 9188 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9189 // Check for static member variables and don't warn on them. 9190 if (!isa<FieldDecl>(ME->getMemberDecl())) 9191 return; 9192 Base = ME->getBase()->IgnoreParenImpCasts(); 9193 } 9194 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9195 HandleDeclRefExpr(DRE); 9196 return; 9197 } 9198 9199 Visit(E); 9200 } 9201 9202 // Reference types not handled in HandleValue are handled here since all 9203 // uses of references are bad, not just r-value uses. 9204 void VisitDeclRefExpr(DeclRefExpr *E) { 9205 if (isReferenceType) 9206 HandleDeclRefExpr(E); 9207 } 9208 9209 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9210 if (E->getCastKind() == CK_LValueToRValue) { 9211 HandleValue(E->getSubExpr()); 9212 return; 9213 } 9214 9215 Inherited::VisitImplicitCastExpr(E); 9216 } 9217 9218 void VisitMemberExpr(MemberExpr *E) { 9219 if (isInitList) { 9220 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9221 return; 9222 } 9223 9224 // Don't warn on arrays since they can be treated as pointers. 9225 if (E->getType()->canDecayToPointerType()) return; 9226 9227 // Warn when a non-static method call is followed by non-static member 9228 // field accesses, which is followed by a DeclRefExpr. 9229 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9230 bool Warn = (MD && !MD->isStatic()); 9231 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9232 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9233 if (!isa<FieldDecl>(ME->getMemberDecl())) 9234 Warn = false; 9235 Base = ME->getBase()->IgnoreParenImpCasts(); 9236 } 9237 9238 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9239 if (Warn) 9240 HandleDeclRefExpr(DRE); 9241 return; 9242 } 9243 9244 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9245 // Visit that expression. 9246 Visit(Base); 9247 } 9248 9249 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9250 Expr *Callee = E->getCallee(); 9251 9252 if (isa<UnresolvedLookupExpr>(Callee)) 9253 return Inherited::VisitCXXOperatorCallExpr(E); 9254 9255 Visit(Callee); 9256 for (auto Arg: E->arguments()) 9257 HandleValue(Arg->IgnoreParenImpCasts()); 9258 } 9259 9260 void VisitUnaryOperator(UnaryOperator *E) { 9261 // For POD record types, addresses of its own members are well-defined. 9262 if (E->getOpcode() == UO_AddrOf && isRecordType && 9263 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9264 if (!isPODType) 9265 HandleValue(E->getSubExpr()); 9266 return; 9267 } 9268 9269 if (E->isIncrementDecrementOp()) { 9270 HandleValue(E->getSubExpr()); 9271 return; 9272 } 9273 9274 Inherited::VisitUnaryOperator(E); 9275 } 9276 9277 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9278 9279 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9280 if (E->getConstructor()->isCopyConstructor()) { 9281 Expr *ArgExpr = E->getArg(0); 9282 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9283 if (ILE->getNumInits() == 1) 9284 ArgExpr = ILE->getInit(0); 9285 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9286 if (ICE->getCastKind() == CK_NoOp) 9287 ArgExpr = ICE->getSubExpr(); 9288 HandleValue(ArgExpr); 9289 return; 9290 } 9291 Inherited::VisitCXXConstructExpr(E); 9292 } 9293 9294 void VisitCallExpr(CallExpr *E) { 9295 // Treat std::move as a use. 9296 if (E->getNumArgs() == 1) { 9297 if (FunctionDecl *FD = E->getDirectCallee()) { 9298 if (FD->isInStdNamespace() && FD->getIdentifier() && 9299 FD->getIdentifier()->isStr("move")) { 9300 HandleValue(E->getArg(0)); 9301 return; 9302 } 9303 } 9304 } 9305 9306 Inherited::VisitCallExpr(E); 9307 } 9308 9309 void VisitBinaryOperator(BinaryOperator *E) { 9310 if (E->isCompoundAssignmentOp()) { 9311 HandleValue(E->getLHS()); 9312 Visit(E->getRHS()); 9313 return; 9314 } 9315 9316 Inherited::VisitBinaryOperator(E); 9317 } 9318 9319 // A custom visitor for BinaryConditionalOperator is needed because the 9320 // regular visitor would check the condition and true expression separately 9321 // but both point to the same place giving duplicate diagnostics. 9322 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9323 Visit(E->getCond()); 9324 Visit(E->getFalseExpr()); 9325 } 9326 9327 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9328 Decl* ReferenceDecl = DRE->getDecl(); 9329 if (OrigDecl != ReferenceDecl) return; 9330 unsigned diag; 9331 if (isReferenceType) { 9332 diag = diag::warn_uninit_self_reference_in_reference_init; 9333 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9334 diag = diag::warn_static_self_reference_in_init; 9335 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9336 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9337 DRE->getDecl()->getType()->isRecordType()) { 9338 diag = diag::warn_uninit_self_reference_in_init; 9339 } else { 9340 // Local variables will be handled by the CFG analysis. 9341 return; 9342 } 9343 9344 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9345 S.PDiag(diag) 9346 << DRE->getNameInfo().getName() 9347 << OrigDecl->getLocation() 9348 << DRE->getSourceRange()); 9349 } 9350 }; 9351 9352 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9353 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9354 bool DirectInit) { 9355 // Parameters arguments are occassionially constructed with itself, 9356 // for instance, in recursive functions. Skip them. 9357 if (isa<ParmVarDecl>(OrigDecl)) 9358 return; 9359 9360 E = E->IgnoreParens(); 9361 9362 // Skip checking T a = a where T is not a record or reference type. 9363 // Doing so is a way to silence uninitialized warnings. 9364 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9365 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9366 if (ICE->getCastKind() == CK_LValueToRValue) 9367 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9368 if (DRE->getDecl() == OrigDecl) 9369 return; 9370 9371 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9372 } 9373 } // end anonymous namespace 9374 9375 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9376 DeclarationName Name, QualType Type, 9377 TypeSourceInfo *TSI, 9378 SourceRange Range, bool DirectInit, 9379 Expr *Init) { 9380 bool IsInitCapture = !VDecl; 9381 assert((!VDecl || !VDecl->isInitCapture()) && 9382 "init captures are expected to be deduced prior to initialization"); 9383 9384 ArrayRef<Expr *> DeduceInits = Init; 9385 if (DirectInit) { 9386 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9387 DeduceInits = PL->exprs(); 9388 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9389 DeduceInits = IL->inits(); 9390 } 9391 9392 // Deduction only works if we have exactly one source expression. 9393 if (DeduceInits.empty()) { 9394 // It isn't possible to write this directly, but it is possible to 9395 // end up in this situation with "auto x(some_pack...);" 9396 Diag(Init->getLocStart(), IsInitCapture 9397 ? diag::err_init_capture_no_expression 9398 : diag::err_auto_var_init_no_expression) 9399 << Name << Type << Range; 9400 return QualType(); 9401 } 9402 9403 if (DeduceInits.size() > 1) { 9404 Diag(DeduceInits[1]->getLocStart(), 9405 IsInitCapture ? diag::err_init_capture_multiple_expressions 9406 : diag::err_auto_var_init_multiple_expressions) 9407 << Name << Type << Range; 9408 return QualType(); 9409 } 9410 9411 Expr *DeduceInit = DeduceInits[0]; 9412 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9413 Diag(Init->getLocStart(), IsInitCapture 9414 ? diag::err_init_capture_paren_braces 9415 : diag::err_auto_var_init_paren_braces) 9416 << isa<InitListExpr>(Init) << Name << Type << Range; 9417 return QualType(); 9418 } 9419 9420 // Expressions default to 'id' when we're in a debugger. 9421 bool DefaultedAnyToId = false; 9422 if (getLangOpts().DebuggerCastResultToId && 9423 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9424 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9425 if (Result.isInvalid()) { 9426 return QualType(); 9427 } 9428 Init = Result.get(); 9429 DefaultedAnyToId = true; 9430 } 9431 9432 QualType DeducedType; 9433 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9434 if (!IsInitCapture) 9435 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9436 else if (isa<InitListExpr>(Init)) 9437 Diag(Range.getBegin(), 9438 diag::err_init_capture_deduction_failure_from_init_list) 9439 << Name 9440 << (DeduceInit->getType().isNull() ? TSI->getType() 9441 : DeduceInit->getType()) 9442 << DeduceInit->getSourceRange(); 9443 else 9444 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9445 << Name << TSI->getType() 9446 << (DeduceInit->getType().isNull() ? TSI->getType() 9447 : DeduceInit->getType()) 9448 << DeduceInit->getSourceRange(); 9449 } 9450 9451 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9452 // 'id' instead of a specific object type prevents most of our usual 9453 // checks. 9454 // We only want to warn outside of template instantiations, though: 9455 // inside a template, the 'id' could have come from a parameter. 9456 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9457 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9458 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9459 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range; 9460 } 9461 9462 return DeducedType; 9463 } 9464 9465 /// AddInitializerToDecl - Adds the initializer Init to the 9466 /// declaration dcl. If DirectInit is true, this is C++ direct 9467 /// initialization rather than copy initialization. 9468 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 9469 bool DirectInit, bool TypeMayContainAuto) { 9470 // If there is no declaration, there was an error parsing it. Just ignore 9471 // the initializer. 9472 if (!RealDecl || RealDecl->isInvalidDecl()) { 9473 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9474 return; 9475 } 9476 9477 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9478 // Pure-specifiers are handled in ActOnPureSpecifier. 9479 Diag(Method->getLocation(), diag::err_member_function_initialization) 9480 << Method->getDeclName() << Init->getSourceRange(); 9481 Method->setInvalidDecl(); 9482 return; 9483 } 9484 9485 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9486 if (!VDecl) { 9487 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9488 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9489 RealDecl->setInvalidDecl(); 9490 return; 9491 } 9492 9493 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9494 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 9495 // Attempt typo correction early so that the type of the init expression can 9496 // be deduced based on the chosen correction if the original init contains a 9497 // TypoExpr. 9498 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9499 if (!Res.isUsable()) { 9500 RealDecl->setInvalidDecl(); 9501 return; 9502 } 9503 Init = Res.get(); 9504 9505 QualType DeducedType = deduceVarTypeFromInitializer( 9506 VDecl, VDecl->getDeclName(), VDecl->getType(), 9507 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9508 if (DeducedType.isNull()) { 9509 RealDecl->setInvalidDecl(); 9510 return; 9511 } 9512 9513 VDecl->setType(DeducedType); 9514 assert(VDecl->isLinkageValid()); 9515 9516 // In ARC, infer lifetime. 9517 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9518 VDecl->setInvalidDecl(); 9519 9520 // If this is a redeclaration, check that the type we just deduced matches 9521 // the previously declared type. 9522 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9523 // We never need to merge the type, because we cannot form an incomplete 9524 // array of auto, nor deduce such a type. 9525 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9526 } 9527 9528 // Check the deduced type is valid for a variable declaration. 9529 CheckVariableDeclarationType(VDecl); 9530 if (VDecl->isInvalidDecl()) 9531 return; 9532 } 9533 9534 // dllimport cannot be used on variable definitions. 9535 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9536 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9537 VDecl->setInvalidDecl(); 9538 return; 9539 } 9540 9541 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9542 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9543 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9544 VDecl->setInvalidDecl(); 9545 return; 9546 } 9547 9548 if (!VDecl->getType()->isDependentType()) { 9549 // A definition must end up with a complete type, which means it must be 9550 // complete with the restriction that an array type might be completed by 9551 // the initializer; note that later code assumes this restriction. 9552 QualType BaseDeclType = VDecl->getType(); 9553 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9554 BaseDeclType = Array->getElementType(); 9555 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9556 diag::err_typecheck_decl_incomplete_type)) { 9557 RealDecl->setInvalidDecl(); 9558 return; 9559 } 9560 9561 // The variable can not have an abstract class type. 9562 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9563 diag::err_abstract_type_in_decl, 9564 AbstractVariableType)) 9565 VDecl->setInvalidDecl(); 9566 } 9567 9568 VarDecl *Def; 9569 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 9570 NamedDecl *Hidden = nullptr; 9571 if (!hasVisibleDefinition(Def, &Hidden) && 9572 (VDecl->getFormalLinkage() == InternalLinkage || 9573 VDecl->getDescribedVarTemplate() || 9574 VDecl->getNumTemplateParameterLists() || 9575 VDecl->getDeclContext()->isDependentContext())) { 9576 // The previous definition is hidden, and multiple definitions are 9577 // permitted (in separate TUs). Form another definition of it. 9578 } else { 9579 Diag(VDecl->getLocation(), diag::err_redefinition) 9580 << VDecl->getDeclName(); 9581 Diag(Def->getLocation(), diag::note_previous_definition); 9582 VDecl->setInvalidDecl(); 9583 return; 9584 } 9585 } 9586 9587 if (getLangOpts().CPlusPlus) { 9588 // C++ [class.static.data]p4 9589 // If a static data member is of const integral or const 9590 // enumeration type, its declaration in the class definition can 9591 // specify a constant-initializer which shall be an integral 9592 // constant expression (5.19). In that case, the member can appear 9593 // in integral constant expressions. The member shall still be 9594 // defined in a namespace scope if it is used in the program and the 9595 // namespace scope definition shall not contain an initializer. 9596 // 9597 // We already performed a redefinition check above, but for static 9598 // data members we also need to check whether there was an in-class 9599 // declaration with an initializer. 9600 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9601 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9602 << VDecl->getDeclName(); 9603 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9604 diag::note_previous_initializer) 9605 << 0; 9606 return; 9607 } 9608 9609 if (VDecl->hasLocalStorage()) 9610 getCurFunction()->setHasBranchProtectedScope(); 9611 9612 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 9613 VDecl->setInvalidDecl(); 9614 return; 9615 } 9616 } 9617 9618 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 9619 // a kernel function cannot be initialized." 9620 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 9621 Diag(VDecl->getLocation(), diag::err_local_cant_init); 9622 VDecl->setInvalidDecl(); 9623 return; 9624 } 9625 9626 // Get the decls type and save a reference for later, since 9627 // CheckInitializerTypes may change it. 9628 QualType DclT = VDecl->getType(), SavT = DclT; 9629 9630 // Expressions default to 'id' when we're in a debugger 9631 // and we are assigning it to a variable of Objective-C pointer type. 9632 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 9633 Init->getType() == Context.UnknownAnyTy) { 9634 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9635 if (Result.isInvalid()) { 9636 VDecl->setInvalidDecl(); 9637 return; 9638 } 9639 Init = Result.get(); 9640 } 9641 9642 // Perform the initialization. 9643 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 9644 if (!VDecl->isInvalidDecl()) { 9645 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9646 InitializationKind Kind = 9647 DirectInit 9648 ? CXXDirectInit 9649 ? InitializationKind::CreateDirect(VDecl->getLocation(), 9650 Init->getLocStart(), 9651 Init->getLocEnd()) 9652 : InitializationKind::CreateDirectList(VDecl->getLocation()) 9653 : InitializationKind::CreateCopy(VDecl->getLocation(), 9654 Init->getLocStart()); 9655 9656 MultiExprArg Args = Init; 9657 if (CXXDirectInit) 9658 Args = MultiExprArg(CXXDirectInit->getExprs(), 9659 CXXDirectInit->getNumExprs()); 9660 9661 // Try to correct any TypoExprs in the initialization arguments. 9662 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9663 ExprResult Res = CorrectDelayedTyposInExpr( 9664 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9665 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9666 return Init.Failed() ? ExprError() : E; 9667 }); 9668 if (Res.isInvalid()) { 9669 VDecl->setInvalidDecl(); 9670 } else if (Res.get() != Args[Idx]) { 9671 Args[Idx] = Res.get(); 9672 } 9673 } 9674 if (VDecl->isInvalidDecl()) 9675 return; 9676 9677 InitializationSequence InitSeq(*this, Entity, Kind, Args, 9678 /*TopLevelOfInitList=*/false, 9679 /*TreatUnavailableAsInvalid=*/false); 9680 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9681 if (Result.isInvalid()) { 9682 VDecl->setInvalidDecl(); 9683 return; 9684 } 9685 9686 Init = Result.getAs<Expr>(); 9687 } 9688 9689 // Check for self-references within variable initializers. 9690 // Variables declared within a function/method body (except for references) 9691 // are handled by a dataflow analysis. 9692 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9693 VDecl->getType()->isReferenceType()) { 9694 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9695 } 9696 9697 // If the type changed, it means we had an incomplete type that was 9698 // completed by the initializer. For example: 9699 // int ary[] = { 1, 3, 5 }; 9700 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9701 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9702 VDecl->setType(DclT); 9703 9704 if (!VDecl->isInvalidDecl()) { 9705 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9706 9707 if (VDecl->hasAttr<BlocksAttr>()) 9708 checkRetainCycles(VDecl, Init); 9709 9710 // It is safe to assign a weak reference into a strong variable. 9711 // Although this code can still have problems: 9712 // id x = self.weakProp; 9713 // id y = self.weakProp; 9714 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9715 // paths through the function. This should be revisited if 9716 // -Wrepeated-use-of-weak is made flow-sensitive. 9717 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9718 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9719 Init->getLocStart())) 9720 getCurFunction()->markSafeWeakUse(Init); 9721 } 9722 9723 // The initialization is usually a full-expression. 9724 // 9725 // FIXME: If this is a braced initialization of an aggregate, it is not 9726 // an expression, and each individual field initializer is a separate 9727 // full-expression. For instance, in: 9728 // 9729 // struct Temp { ~Temp(); }; 9730 // struct S { S(Temp); }; 9731 // struct T { S a, b; } t = { Temp(), Temp() } 9732 // 9733 // we should destroy the first Temp before constructing the second. 9734 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9735 false, 9736 VDecl->isConstexpr()); 9737 if (Result.isInvalid()) { 9738 VDecl->setInvalidDecl(); 9739 return; 9740 } 9741 Init = Result.get(); 9742 9743 // Attach the initializer to the decl. 9744 VDecl->setInit(Init); 9745 9746 if (VDecl->isLocalVarDecl()) { 9747 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9748 // static storage duration shall be constant expressions or string literals. 9749 // C++ does not have this restriction. 9750 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9751 const Expr *Culprit; 9752 if (VDecl->getStorageClass() == SC_Static) 9753 CheckForConstantInitializer(Init, DclT); 9754 // C89 is stricter than C99 for non-static aggregate types. 9755 // C89 6.5.7p3: All the expressions [...] in an initializer list 9756 // for an object that has aggregate or union type shall be 9757 // constant expressions. 9758 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9759 isa<InitListExpr>(Init) && 9760 !Init->isConstantInitializer(Context, false, &Culprit)) 9761 Diag(Culprit->getExprLoc(), 9762 diag::ext_aggregate_init_not_constant) 9763 << Culprit->getSourceRange(); 9764 } 9765 } else if (VDecl->isStaticDataMember() && 9766 VDecl->getLexicalDeclContext()->isRecord()) { 9767 // This is an in-class initialization for a static data member, e.g., 9768 // 9769 // struct S { 9770 // static const int value = 17; 9771 // }; 9772 9773 // C++ [class.mem]p4: 9774 // A member-declarator can contain a constant-initializer only 9775 // if it declares a static member (9.4) of const integral or 9776 // const enumeration type, see 9.4.2. 9777 // 9778 // C++11 [class.static.data]p3: 9779 // If a non-volatile const static data member is of integral or 9780 // enumeration type, its declaration in the class definition can 9781 // specify a brace-or-equal-initializer in which every initalizer-clause 9782 // that is an assignment-expression is a constant expression. A static 9783 // data member of literal type can be declared in the class definition 9784 // with the constexpr specifier; if so, its declaration shall specify a 9785 // brace-or-equal-initializer in which every initializer-clause that is 9786 // an assignment-expression is a constant expression. 9787 9788 // Do nothing on dependent types. 9789 if (DclT->isDependentType()) { 9790 9791 // Allow any 'static constexpr' members, whether or not they are of literal 9792 // type. We separately check that every constexpr variable is of literal 9793 // type. 9794 } else if (VDecl->isConstexpr()) { 9795 9796 // Require constness. 9797 } else if (!DclT.isConstQualified()) { 9798 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9799 << Init->getSourceRange(); 9800 VDecl->setInvalidDecl(); 9801 9802 // We allow integer constant expressions in all cases. 9803 } else if (DclT->isIntegralOrEnumerationType()) { 9804 // Check whether the expression is a constant expression. 9805 SourceLocation Loc; 9806 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9807 // In C++11, a non-constexpr const static data member with an 9808 // in-class initializer cannot be volatile. 9809 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9810 else if (Init->isValueDependent()) 9811 ; // Nothing to check. 9812 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9813 ; // Ok, it's an ICE! 9814 else if (Init->isEvaluatable(Context)) { 9815 // If we can constant fold the initializer through heroics, accept it, 9816 // but report this as a use of an extension for -pedantic. 9817 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9818 << Init->getSourceRange(); 9819 } else { 9820 // Otherwise, this is some crazy unknown case. Report the issue at the 9821 // location provided by the isIntegerConstantExpr failed check. 9822 Diag(Loc, diag::err_in_class_initializer_non_constant) 9823 << Init->getSourceRange(); 9824 VDecl->setInvalidDecl(); 9825 } 9826 9827 // We allow foldable floating-point constants as an extension. 9828 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9829 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9830 // it anyway and provide a fixit to add the 'constexpr'. 9831 if (getLangOpts().CPlusPlus11) { 9832 Diag(VDecl->getLocation(), 9833 diag::ext_in_class_initializer_float_type_cxx11) 9834 << DclT << Init->getSourceRange(); 9835 Diag(VDecl->getLocStart(), 9836 diag::note_in_class_initializer_float_type_cxx11) 9837 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9838 } else { 9839 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9840 << DclT << Init->getSourceRange(); 9841 9842 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9843 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9844 << Init->getSourceRange(); 9845 VDecl->setInvalidDecl(); 9846 } 9847 } 9848 9849 // Suggest adding 'constexpr' in C++11 for literal types. 9850 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9851 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9852 << DclT << Init->getSourceRange() 9853 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9854 VDecl->setConstexpr(true); 9855 9856 } else { 9857 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9858 << DclT << Init->getSourceRange(); 9859 VDecl->setInvalidDecl(); 9860 } 9861 } else if (VDecl->isFileVarDecl()) { 9862 if (VDecl->getStorageClass() == SC_Extern && 9863 (!getLangOpts().CPlusPlus || 9864 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 9865 VDecl->isExternC())) && 9866 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9867 Diag(VDecl->getLocation(), diag::warn_extern_init); 9868 9869 // C99 6.7.8p4. All file scoped initializers need to be constant. 9870 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9871 CheckForConstantInitializer(Init, DclT); 9872 } 9873 9874 // We will represent direct-initialization similarly to copy-initialization: 9875 // int x(1); -as-> int x = 1; 9876 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9877 // 9878 // Clients that want to distinguish between the two forms, can check for 9879 // direct initializer using VarDecl::getInitStyle(). 9880 // A major benefit is that clients that don't particularly care about which 9881 // exactly form was it (like the CodeGen) can handle both cases without 9882 // special case code. 9883 9884 // C++ 8.5p11: 9885 // The form of initialization (using parentheses or '=') is generally 9886 // insignificant, but does matter when the entity being initialized has a 9887 // class type. 9888 if (CXXDirectInit) { 9889 assert(DirectInit && "Call-style initializer must be direct init."); 9890 VDecl->setInitStyle(VarDecl::CallInit); 9891 } else if (DirectInit) { 9892 // This must be list-initialization. No other way is direct-initialization. 9893 VDecl->setInitStyle(VarDecl::ListInit); 9894 } 9895 9896 CheckCompleteVariableDeclaration(VDecl); 9897 } 9898 9899 /// ActOnInitializerError - Given that there was an error parsing an 9900 /// initializer for the given declaration, try to return to some form 9901 /// of sanity. 9902 void Sema::ActOnInitializerError(Decl *D) { 9903 // Our main concern here is re-establishing invariants like "a 9904 // variable's type is either dependent or complete". 9905 if (!D || D->isInvalidDecl()) return; 9906 9907 VarDecl *VD = dyn_cast<VarDecl>(D); 9908 if (!VD) return; 9909 9910 // Auto types are meaningless if we can't make sense of the initializer. 9911 if (ParsingInitForAutoVars.count(D)) { 9912 D->setInvalidDecl(); 9913 return; 9914 } 9915 9916 QualType Ty = VD->getType(); 9917 if (Ty->isDependentType()) return; 9918 9919 // Require a complete type. 9920 if (RequireCompleteType(VD->getLocation(), 9921 Context.getBaseElementType(Ty), 9922 diag::err_typecheck_decl_incomplete_type)) { 9923 VD->setInvalidDecl(); 9924 return; 9925 } 9926 9927 // Require a non-abstract type. 9928 if (RequireNonAbstractType(VD->getLocation(), Ty, 9929 diag::err_abstract_type_in_decl, 9930 AbstractVariableType)) { 9931 VD->setInvalidDecl(); 9932 return; 9933 } 9934 9935 // Don't bother complaining about constructors or destructors, 9936 // though. 9937 } 9938 9939 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9940 bool TypeMayContainAuto) { 9941 // If there is no declaration, there was an error parsing it. Just ignore it. 9942 if (!RealDecl) 9943 return; 9944 9945 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9946 QualType Type = Var->getType(); 9947 9948 // C++11 [dcl.spec.auto]p3 9949 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9950 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9951 << Var->getDeclName() << Type; 9952 Var->setInvalidDecl(); 9953 return; 9954 } 9955 9956 // C++11 [class.static.data]p3: A static data member can be declared with 9957 // the constexpr specifier; if so, its declaration shall specify 9958 // a brace-or-equal-initializer. 9959 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9960 // the definition of a variable [...] or the declaration of a static data 9961 // member. 9962 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9963 if (Var->isStaticDataMember()) 9964 Diag(Var->getLocation(), 9965 diag::err_constexpr_static_mem_var_requires_init) 9966 << Var->getDeclName(); 9967 else 9968 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9969 Var->setInvalidDecl(); 9970 return; 9971 } 9972 9973 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 9974 // definition having the concept specifier is called a variable concept. A 9975 // concept definition refers to [...] a variable concept and its initializer. 9976 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 9977 if (VTD->isConcept()) { 9978 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 9979 Var->setInvalidDecl(); 9980 return; 9981 } 9982 } 9983 9984 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9985 // be initialized. 9986 if (!Var->isInvalidDecl() && 9987 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9988 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9989 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9990 Var->setInvalidDecl(); 9991 return; 9992 } 9993 9994 switch (Var->isThisDeclarationADefinition()) { 9995 case VarDecl::Definition: 9996 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9997 break; 9998 9999 // We have an out-of-line definition of a static data member 10000 // that has an in-class initializer, so we type-check this like 10001 // a declaration. 10002 // 10003 // Fall through 10004 10005 case VarDecl::DeclarationOnly: 10006 // It's only a declaration. 10007 10008 // Block scope. C99 6.7p7: If an identifier for an object is 10009 // declared with no linkage (C99 6.2.2p6), the type for the 10010 // object shall be complete. 10011 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10012 !Var->hasLinkage() && !Var->isInvalidDecl() && 10013 RequireCompleteType(Var->getLocation(), Type, 10014 diag::err_typecheck_decl_incomplete_type)) 10015 Var->setInvalidDecl(); 10016 10017 // Make sure that the type is not abstract. 10018 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10019 RequireNonAbstractType(Var->getLocation(), Type, 10020 diag::err_abstract_type_in_decl, 10021 AbstractVariableType)) 10022 Var->setInvalidDecl(); 10023 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10024 Var->getStorageClass() == SC_PrivateExtern) { 10025 Diag(Var->getLocation(), diag::warn_private_extern); 10026 Diag(Var->getLocation(), diag::note_private_extern); 10027 } 10028 10029 return; 10030 10031 case VarDecl::TentativeDefinition: 10032 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10033 // object that has file scope without an initializer, and without a 10034 // storage-class specifier or with the storage-class specifier "static", 10035 // constitutes a tentative definition. Note: A tentative definition with 10036 // external linkage is valid (C99 6.2.2p5). 10037 if (!Var->isInvalidDecl()) { 10038 if (const IncompleteArrayType *ArrayT 10039 = Context.getAsIncompleteArrayType(Type)) { 10040 if (RequireCompleteType(Var->getLocation(), 10041 ArrayT->getElementType(), 10042 diag::err_illegal_decl_array_incomplete_type)) 10043 Var->setInvalidDecl(); 10044 } else if (Var->getStorageClass() == SC_Static) { 10045 // C99 6.9.2p3: If the declaration of an identifier for an object is 10046 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10047 // declared type shall not be an incomplete type. 10048 // NOTE: code such as the following 10049 // static struct s; 10050 // struct s { int a; }; 10051 // is accepted by gcc. Hence here we issue a warning instead of 10052 // an error and we do not invalidate the static declaration. 10053 // NOTE: to avoid multiple warnings, only check the first declaration. 10054 if (Var->isFirstDecl()) 10055 RequireCompleteType(Var->getLocation(), Type, 10056 diag::ext_typecheck_decl_incomplete_type); 10057 } 10058 } 10059 10060 // Record the tentative definition; we're done. 10061 if (!Var->isInvalidDecl()) 10062 TentativeDefinitions.push_back(Var); 10063 return; 10064 } 10065 10066 // Provide a specific diagnostic for uninitialized variable 10067 // definitions with incomplete array type. 10068 if (Type->isIncompleteArrayType()) { 10069 Diag(Var->getLocation(), 10070 diag::err_typecheck_incomplete_array_needs_initializer); 10071 Var->setInvalidDecl(); 10072 return; 10073 } 10074 10075 // Provide a specific diagnostic for uninitialized variable 10076 // definitions with reference type. 10077 if (Type->isReferenceType()) { 10078 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10079 << Var->getDeclName() 10080 << SourceRange(Var->getLocation(), Var->getLocation()); 10081 Var->setInvalidDecl(); 10082 return; 10083 } 10084 10085 // Do not attempt to type-check the default initializer for a 10086 // variable with dependent type. 10087 if (Type->isDependentType()) 10088 return; 10089 10090 if (Var->isInvalidDecl()) 10091 return; 10092 10093 if (!Var->hasAttr<AliasAttr>()) { 10094 if (RequireCompleteType(Var->getLocation(), 10095 Context.getBaseElementType(Type), 10096 diag::err_typecheck_decl_incomplete_type)) { 10097 Var->setInvalidDecl(); 10098 return; 10099 } 10100 } else { 10101 return; 10102 } 10103 10104 // The variable can not have an abstract class type. 10105 if (RequireNonAbstractType(Var->getLocation(), Type, 10106 diag::err_abstract_type_in_decl, 10107 AbstractVariableType)) { 10108 Var->setInvalidDecl(); 10109 return; 10110 } 10111 10112 // Check for jumps past the implicit initializer. C++0x 10113 // clarifies that this applies to a "variable with automatic 10114 // storage duration", not a "local variable". 10115 // C++11 [stmt.dcl]p3 10116 // A program that jumps from a point where a variable with automatic 10117 // storage duration is not in scope to a point where it is in scope is 10118 // ill-formed unless the variable has scalar type, class type with a 10119 // trivial default constructor and a trivial destructor, a cv-qualified 10120 // version of one of these types, or an array of one of the preceding 10121 // types and is declared without an initializer. 10122 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10123 if (const RecordType *Record 10124 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10125 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10126 // Mark the function for further checking even if the looser rules of 10127 // C++11 do not require such checks, so that we can diagnose 10128 // incompatibilities with C++98. 10129 if (!CXXRecord->isPOD()) 10130 getCurFunction()->setHasBranchProtectedScope(); 10131 } 10132 } 10133 10134 // C++03 [dcl.init]p9: 10135 // If no initializer is specified for an object, and the 10136 // object is of (possibly cv-qualified) non-POD class type (or 10137 // array thereof), the object shall be default-initialized; if 10138 // the object is of const-qualified type, the underlying class 10139 // type shall have a user-declared default 10140 // constructor. Otherwise, if no initializer is specified for 10141 // a non- static object, the object and its subobjects, if 10142 // any, have an indeterminate initial value); if the object 10143 // or any of its subobjects are of const-qualified type, the 10144 // program is ill-formed. 10145 // C++0x [dcl.init]p11: 10146 // If no initializer is specified for an object, the object is 10147 // default-initialized; [...]. 10148 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10149 InitializationKind Kind 10150 = InitializationKind::CreateDefault(Var->getLocation()); 10151 10152 InitializationSequence InitSeq(*this, Entity, Kind, None); 10153 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10154 if (Init.isInvalid()) 10155 Var->setInvalidDecl(); 10156 else if (Init.get()) { 10157 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10158 // This is important for template substitution. 10159 Var->setInitStyle(VarDecl::CallInit); 10160 } 10161 10162 CheckCompleteVariableDeclaration(Var); 10163 } 10164 } 10165 10166 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10167 // If there is no declaration, there was an error parsing it. Ignore it. 10168 if (!D) 10169 return; 10170 10171 VarDecl *VD = dyn_cast<VarDecl>(D); 10172 if (!VD) { 10173 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10174 D->setInvalidDecl(); 10175 return; 10176 } 10177 10178 VD->setCXXForRangeDecl(true); 10179 10180 // for-range-declaration cannot be given a storage class specifier. 10181 int Error = -1; 10182 switch (VD->getStorageClass()) { 10183 case SC_None: 10184 break; 10185 case SC_Extern: 10186 Error = 0; 10187 break; 10188 case SC_Static: 10189 Error = 1; 10190 break; 10191 case SC_PrivateExtern: 10192 Error = 2; 10193 break; 10194 case SC_Auto: 10195 Error = 3; 10196 break; 10197 case SC_Register: 10198 Error = 4; 10199 break; 10200 } 10201 if (Error != -1) { 10202 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10203 << VD->getDeclName() << Error; 10204 D->setInvalidDecl(); 10205 } 10206 } 10207 10208 StmtResult 10209 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10210 IdentifierInfo *Ident, 10211 ParsedAttributes &Attrs, 10212 SourceLocation AttrEnd) { 10213 // C++1y [stmt.iter]p1: 10214 // A range-based for statement of the form 10215 // for ( for-range-identifier : for-range-initializer ) statement 10216 // is equivalent to 10217 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10218 DeclSpec DS(Attrs.getPool().getFactory()); 10219 10220 const char *PrevSpec; 10221 unsigned DiagID; 10222 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10223 getPrintingPolicy()); 10224 10225 Declarator D(DS, Declarator::ForContext); 10226 D.SetIdentifier(Ident, IdentLoc); 10227 D.takeAttributes(Attrs, AttrEnd); 10228 10229 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10230 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10231 EmptyAttrs, IdentLoc); 10232 Decl *Var = ActOnDeclarator(S, D); 10233 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10234 FinalizeDeclaration(Var); 10235 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10236 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10237 } 10238 10239 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10240 if (var->isInvalidDecl()) return; 10241 10242 if (getLangOpts().OpenCL) { 10243 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10244 // initialiser 10245 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10246 !var->hasInit()) { 10247 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10248 << 1 /*Init*/; 10249 var->setInvalidDecl(); 10250 return; 10251 } 10252 } 10253 10254 // In Objective-C, don't allow jumps past the implicit initialization of a 10255 // local retaining variable. 10256 if (getLangOpts().ObjC1 && 10257 var->hasLocalStorage()) { 10258 switch (var->getType().getObjCLifetime()) { 10259 case Qualifiers::OCL_None: 10260 case Qualifiers::OCL_ExplicitNone: 10261 case Qualifiers::OCL_Autoreleasing: 10262 break; 10263 10264 case Qualifiers::OCL_Weak: 10265 case Qualifiers::OCL_Strong: 10266 getCurFunction()->setHasBranchProtectedScope(); 10267 break; 10268 } 10269 } 10270 10271 // Warn about externally-visible variables being defined without a 10272 // prior declaration. We only want to do this for global 10273 // declarations, but we also specifically need to avoid doing it for 10274 // class members because the linkage of an anonymous class can 10275 // change if it's later given a typedef name. 10276 if (var->isThisDeclarationADefinition() && 10277 var->getDeclContext()->getRedeclContext()->isFileContext() && 10278 var->isExternallyVisible() && var->hasLinkage() && 10279 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10280 var->getLocation())) { 10281 // Find a previous declaration that's not a definition. 10282 VarDecl *prev = var->getPreviousDecl(); 10283 while (prev && prev->isThisDeclarationADefinition()) 10284 prev = prev->getPreviousDecl(); 10285 10286 if (!prev) 10287 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10288 } 10289 10290 if (var->getTLSKind() == VarDecl::TLS_Static) { 10291 const Expr *Culprit; 10292 if (var->getType().isDestructedType()) { 10293 // GNU C++98 edits for __thread, [basic.start.term]p3: 10294 // The type of an object with thread storage duration shall not 10295 // have a non-trivial destructor. 10296 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10297 if (getLangOpts().CPlusPlus11) 10298 Diag(var->getLocation(), diag::note_use_thread_local); 10299 } else if (getLangOpts().CPlusPlus && var->hasInit() && 10300 !var->getInit()->isConstantInitializer( 10301 Context, var->getType()->isReferenceType(), &Culprit)) { 10302 // GNU C++98 edits for __thread, [basic.start.init]p4: 10303 // An object of thread storage duration shall not require dynamic 10304 // initialization. 10305 // FIXME: Need strict checking here. 10306 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 10307 << Culprit->getSourceRange(); 10308 if (getLangOpts().CPlusPlus11) 10309 Diag(var->getLocation(), diag::note_use_thread_local); 10310 } 10311 } 10312 10313 // Apply section attributes and pragmas to global variables. 10314 bool GlobalStorage = var->hasGlobalStorage(); 10315 if (GlobalStorage && var->isThisDeclarationADefinition() && 10316 ActiveTemplateInstantiations.empty()) { 10317 PragmaStack<StringLiteral *> *Stack = nullptr; 10318 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10319 if (var->getType().isConstQualified()) 10320 Stack = &ConstSegStack; 10321 else if (!var->getInit()) { 10322 Stack = &BSSSegStack; 10323 SectionFlags |= ASTContext::PSF_Write; 10324 } else { 10325 Stack = &DataSegStack; 10326 SectionFlags |= ASTContext::PSF_Write; 10327 } 10328 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10329 var->addAttr(SectionAttr::CreateImplicit( 10330 Context, SectionAttr::Declspec_allocate, 10331 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10332 } 10333 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10334 if (UnifySection(SA->getName(), SectionFlags, var)) 10335 var->dropAttr<SectionAttr>(); 10336 10337 // Apply the init_seg attribute if this has an initializer. If the 10338 // initializer turns out to not be dynamic, we'll end up ignoring this 10339 // attribute. 10340 if (CurInitSeg && var->getInit()) 10341 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10342 CurInitSegLoc)); 10343 } 10344 10345 // All the following checks are C++ only. 10346 if (!getLangOpts().CPlusPlus) return; 10347 10348 QualType type = var->getType(); 10349 if (type->isDependentType()) return; 10350 10351 // __block variables might require us to capture a copy-initializer. 10352 if (var->hasAttr<BlocksAttr>()) { 10353 // It's currently invalid to ever have a __block variable with an 10354 // array type; should we diagnose that here? 10355 10356 // Regardless, we don't want to ignore array nesting when 10357 // constructing this copy. 10358 if (type->isStructureOrClassType()) { 10359 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10360 SourceLocation poi = var->getLocation(); 10361 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10362 ExprResult result 10363 = PerformMoveOrCopyInitialization( 10364 InitializedEntity::InitializeBlock(poi, type, false), 10365 var, var->getType(), varRef, /*AllowNRVO=*/true); 10366 if (!result.isInvalid()) { 10367 result = MaybeCreateExprWithCleanups(result); 10368 Expr *init = result.getAs<Expr>(); 10369 Context.setBlockVarCopyInits(var, init); 10370 } 10371 } 10372 } 10373 10374 Expr *Init = var->getInit(); 10375 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10376 QualType baseType = Context.getBaseElementType(type); 10377 10378 if (!var->getDeclContext()->isDependentContext() && 10379 Init && !Init->isValueDependent()) { 10380 if (IsGlobal && !var->isConstexpr() && 10381 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10382 var->getLocation())) { 10383 // Warn about globals which don't have a constant initializer. Don't 10384 // warn about globals with a non-trivial destructor because we already 10385 // warned about them. 10386 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10387 if (!(RD && !RD->hasTrivialDestructor()) && 10388 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 10389 Diag(var->getLocation(), diag::warn_global_constructor) 10390 << Init->getSourceRange(); 10391 } 10392 10393 if (var->isConstexpr()) { 10394 SmallVector<PartialDiagnosticAt, 8> Notes; 10395 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10396 SourceLocation DiagLoc = var->getLocation(); 10397 // If the note doesn't add any useful information other than a source 10398 // location, fold it into the primary diagnostic. 10399 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10400 diag::note_invalid_subexpr_in_const_expr) { 10401 DiagLoc = Notes[0].first; 10402 Notes.clear(); 10403 } 10404 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10405 << var << Init->getSourceRange(); 10406 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10407 Diag(Notes[I].first, Notes[I].second); 10408 } 10409 } else if (var->isUsableInConstantExpressions(Context)) { 10410 // Check whether the initializer of a const variable of integral or 10411 // enumeration type is an ICE now, since we can't tell whether it was 10412 // initialized by a constant expression if we check later. 10413 var->checkInitIsICE(); 10414 } 10415 } 10416 10417 // Require the destructor. 10418 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10419 FinalizeVarWithDestructor(var, recordType); 10420 } 10421 10422 /// \brief Determines if a variable's alignment is dependent. 10423 static bool hasDependentAlignment(VarDecl *VD) { 10424 if (VD->getType()->isDependentType()) 10425 return true; 10426 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10427 if (I->isAlignmentDependent()) 10428 return true; 10429 return false; 10430 } 10431 10432 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10433 /// any semantic actions necessary after any initializer has been attached. 10434 void 10435 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10436 // Note that we are no longer parsing the initializer for this declaration. 10437 ParsingInitForAutoVars.erase(ThisDecl); 10438 10439 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10440 if (!VD) 10441 return; 10442 10443 checkAttributesAfterMerging(*this, *VD); 10444 10445 // Perform TLS alignment check here after attributes attached to the variable 10446 // which may affect the alignment have been processed. Only perform the check 10447 // if the target has a maximum TLS alignment (zero means no constraints). 10448 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10449 // Protect the check so that it's not performed on dependent types and 10450 // dependent alignments (we can't determine the alignment in that case). 10451 if (VD->getTLSKind() && !hasDependentAlignment(VD)) { 10452 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10453 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10454 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10455 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10456 << (unsigned)MaxAlignChars.getQuantity(); 10457 } 10458 } 10459 } 10460 10461 if (VD->isStaticLocal()) { 10462 if (FunctionDecl *FD = 10463 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10464 // Static locals inherit dll attributes from their function. 10465 if (Attr *A = getDLLAttr(FD)) { 10466 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10467 NewAttr->setInherited(true); 10468 VD->addAttr(NewAttr); 10469 } 10470 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 10471 // function, only __shared__ variables may be declared with 10472 // static storage class. 10473 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 10474 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) && 10475 !VD->hasAttr<CUDASharedAttr>()) { 10476 Diag(VD->getLocation(), diag::err_device_static_local_var); 10477 VD->setInvalidDecl(); 10478 } 10479 } 10480 } 10481 10482 // Perform check for initializers of device-side global variables. 10483 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 10484 // 7.5). We must also apply the same checks to all __shared__ 10485 // variables whether they are local or not. CUDA also allows 10486 // constant initializers for __constant__ and __device__ variables. 10487 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 10488 const Expr *Init = VD->getInit(); 10489 if (Init && VD->hasGlobalStorage() && 10490 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 10491 VD->hasAttr<CUDASharedAttr>())) { 10492 assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>())); 10493 bool AllowedInit = false; 10494 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 10495 AllowedInit = 10496 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 10497 // We'll allow constant initializers even if it's a non-empty 10498 // constructor according to CUDA rules. This deviates from NVCC, 10499 // but allows us to handle things like constexpr constructors. 10500 if (!AllowedInit && 10501 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 10502 AllowedInit = VD->getInit()->isConstantInitializer( 10503 Context, VD->getType()->isReferenceType()); 10504 10505 // Also make sure that destructor, if there is one, is empty. 10506 if (AllowedInit) 10507 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 10508 AllowedInit = 10509 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 10510 10511 if (!AllowedInit) { 10512 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 10513 ? diag::err_shared_var_init 10514 : diag::err_dynamic_var_init) 10515 << Init->getSourceRange(); 10516 VD->setInvalidDecl(); 10517 } 10518 } 10519 } 10520 10521 // Grab the dllimport or dllexport attribute off of the VarDecl. 10522 const InheritableAttr *DLLAttr = getDLLAttr(VD); 10523 10524 // Imported static data members cannot be defined out-of-line. 10525 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 10526 if (VD->isStaticDataMember() && VD->isOutOfLine() && 10527 VD->isThisDeclarationADefinition()) { 10528 // We allow definitions of dllimport class template static data members 10529 // with a warning. 10530 CXXRecordDecl *Context = 10531 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 10532 bool IsClassTemplateMember = 10533 isa<ClassTemplatePartialSpecializationDecl>(Context) || 10534 Context->getDescribedClassTemplate(); 10535 10536 Diag(VD->getLocation(), 10537 IsClassTemplateMember 10538 ? diag::warn_attribute_dllimport_static_field_definition 10539 : diag::err_attribute_dllimport_static_field_definition); 10540 Diag(IA->getLocation(), diag::note_attribute); 10541 if (!IsClassTemplateMember) 10542 VD->setInvalidDecl(); 10543 } 10544 } 10545 10546 // dllimport/dllexport variables cannot be thread local, their TLS index 10547 // isn't exported with the variable. 10548 if (DLLAttr && VD->getTLSKind()) { 10549 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 10550 if (F && getDLLAttr(F)) { 10551 assert(VD->isStaticLocal()); 10552 // But if this is a static local in a dlimport/dllexport function, the 10553 // function will never be inlined, which means the var would never be 10554 // imported, so having it marked import/export is safe. 10555 } else { 10556 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 10557 << DLLAttr; 10558 VD->setInvalidDecl(); 10559 } 10560 } 10561 10562 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 10563 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 10564 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 10565 VD->dropAttr<UsedAttr>(); 10566 } 10567 } 10568 10569 const DeclContext *DC = VD->getDeclContext(); 10570 // If there's a #pragma GCC visibility in scope, and this isn't a class 10571 // member, set the visibility of this variable. 10572 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 10573 AddPushedVisibilityAttribute(VD); 10574 10575 // FIXME: Warn on unused templates. 10576 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 10577 !isa<VarTemplatePartialSpecializationDecl>(VD)) 10578 MarkUnusedFileScopedDecl(VD); 10579 10580 // Now we have parsed the initializer and can update the table of magic 10581 // tag values. 10582 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 10583 !VD->getType()->isIntegralOrEnumerationType()) 10584 return; 10585 10586 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 10587 const Expr *MagicValueExpr = VD->getInit(); 10588 if (!MagicValueExpr) { 10589 continue; 10590 } 10591 llvm::APSInt MagicValueInt; 10592 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 10593 Diag(I->getRange().getBegin(), 10594 diag::err_type_tag_for_datatype_not_ice) 10595 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10596 continue; 10597 } 10598 if (MagicValueInt.getActiveBits() > 64) { 10599 Diag(I->getRange().getBegin(), 10600 diag::err_type_tag_for_datatype_too_large) 10601 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10602 continue; 10603 } 10604 uint64_t MagicValue = MagicValueInt.getZExtValue(); 10605 RegisterTypeTagForDatatype(I->getArgumentKind(), 10606 MagicValue, 10607 I->getMatchingCType(), 10608 I->getLayoutCompatible(), 10609 I->getMustBeNull()); 10610 } 10611 } 10612 10613 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 10614 ArrayRef<Decl *> Group) { 10615 SmallVector<Decl*, 8> Decls; 10616 10617 if (DS.isTypeSpecOwned()) 10618 Decls.push_back(DS.getRepAsDecl()); 10619 10620 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 10621 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10622 if (Decl *D = Group[i]) { 10623 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 10624 if (!FirstDeclaratorInGroup) 10625 FirstDeclaratorInGroup = DD; 10626 Decls.push_back(D); 10627 } 10628 10629 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 10630 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 10631 handleTagNumbering(Tag, S); 10632 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 10633 getLangOpts().CPlusPlus) 10634 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 10635 } 10636 } 10637 10638 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 10639 } 10640 10641 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 10642 /// group, performing any necessary semantic checking. 10643 Sema::DeclGroupPtrTy 10644 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 10645 bool TypeMayContainAuto) { 10646 // C++0x [dcl.spec.auto]p7: 10647 // If the type deduced for the template parameter U is not the same in each 10648 // deduction, the program is ill-formed. 10649 // FIXME: When initializer-list support is added, a distinction is needed 10650 // between the deduced type U and the deduced type which 'auto' stands for. 10651 // auto a = 0, b = { 1, 2, 3 }; 10652 // is legal because the deduced type U is 'int' in both cases. 10653 if (TypeMayContainAuto && Group.size() > 1) { 10654 QualType Deduced; 10655 CanQualType DeducedCanon; 10656 VarDecl *DeducedDecl = nullptr; 10657 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10658 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 10659 AutoType *AT = D->getType()->getContainedAutoType(); 10660 // Don't reissue diagnostics when instantiating a template. 10661 if (AT && D->isInvalidDecl()) 10662 break; 10663 QualType U = AT ? AT->getDeducedType() : QualType(); 10664 if (!U.isNull()) { 10665 CanQualType UCanon = Context.getCanonicalType(U); 10666 if (Deduced.isNull()) { 10667 Deduced = U; 10668 DeducedCanon = UCanon; 10669 DeducedDecl = D; 10670 } else if (DeducedCanon != UCanon) { 10671 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 10672 diag::err_auto_different_deductions) 10673 << (unsigned)AT->getKeyword() 10674 << Deduced << DeducedDecl->getDeclName() 10675 << U << D->getDeclName() 10676 << DeducedDecl->getInit()->getSourceRange() 10677 << D->getInit()->getSourceRange(); 10678 D->setInvalidDecl(); 10679 break; 10680 } 10681 } 10682 } 10683 } 10684 } 10685 10686 ActOnDocumentableDecls(Group); 10687 10688 return DeclGroupPtrTy::make( 10689 DeclGroupRef::Create(Context, Group.data(), Group.size())); 10690 } 10691 10692 void Sema::ActOnDocumentableDecl(Decl *D) { 10693 ActOnDocumentableDecls(D); 10694 } 10695 10696 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 10697 // Don't parse the comment if Doxygen diagnostics are ignored. 10698 if (Group.empty() || !Group[0]) 10699 return; 10700 10701 if (Diags.isIgnored(diag::warn_doc_param_not_found, 10702 Group[0]->getLocation()) && 10703 Diags.isIgnored(diag::warn_unknown_comment_command_name, 10704 Group[0]->getLocation())) 10705 return; 10706 10707 if (Group.size() >= 2) { 10708 // This is a decl group. Normally it will contain only declarations 10709 // produced from declarator list. But in case we have any definitions or 10710 // additional declaration references: 10711 // 'typedef struct S {} S;' 10712 // 'typedef struct S *S;' 10713 // 'struct S *pS;' 10714 // FinalizeDeclaratorGroup adds these as separate declarations. 10715 Decl *MaybeTagDecl = Group[0]; 10716 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 10717 Group = Group.slice(1); 10718 } 10719 } 10720 10721 // See if there are any new comments that are not attached to a decl. 10722 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 10723 if (!Comments.empty() && 10724 !Comments.back()->isAttached()) { 10725 // There is at least one comment that not attached to a decl. 10726 // Maybe it should be attached to one of these decls? 10727 // 10728 // Note that this way we pick up not only comments that precede the 10729 // declaration, but also comments that *follow* the declaration -- thanks to 10730 // the lookahead in the lexer: we've consumed the semicolon and looked 10731 // ahead through comments. 10732 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10733 Context.getCommentForDecl(Group[i], &PP); 10734 } 10735 } 10736 10737 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 10738 /// to introduce parameters into function prototype scope. 10739 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 10740 const DeclSpec &DS = D.getDeclSpec(); 10741 10742 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 10743 10744 // C++03 [dcl.stc]p2 also permits 'auto'. 10745 StorageClass SC = SC_None; 10746 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 10747 SC = SC_Register; 10748 } else if (getLangOpts().CPlusPlus && 10749 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 10750 SC = SC_Auto; 10751 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 10752 Diag(DS.getStorageClassSpecLoc(), 10753 diag::err_invalid_storage_class_in_func_decl); 10754 D.getMutableDeclSpec().ClearStorageClassSpecs(); 10755 } 10756 10757 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 10758 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 10759 << DeclSpec::getSpecifierName(TSCS); 10760 if (DS.isConstexprSpecified()) 10761 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 10762 << 0; 10763 if (DS.isConceptSpecified()) 10764 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 10765 10766 DiagnoseFunctionSpecifiers(DS); 10767 10768 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10769 QualType parmDeclType = TInfo->getType(); 10770 10771 if (getLangOpts().CPlusPlus) { 10772 // Check that there are no default arguments inside the type of this 10773 // parameter. 10774 CheckExtraCXXDefaultArguments(D); 10775 10776 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 10777 if (D.getCXXScopeSpec().isSet()) { 10778 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 10779 << D.getCXXScopeSpec().getRange(); 10780 D.getCXXScopeSpec().clear(); 10781 } 10782 } 10783 10784 // Ensure we have a valid name 10785 IdentifierInfo *II = nullptr; 10786 if (D.hasName()) { 10787 II = D.getIdentifier(); 10788 if (!II) { 10789 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 10790 << GetNameForDeclarator(D).getName(); 10791 D.setInvalidType(true); 10792 } 10793 } 10794 10795 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 10796 if (II) { 10797 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 10798 ForRedeclaration); 10799 LookupName(R, S); 10800 if (R.isSingleResult()) { 10801 NamedDecl *PrevDecl = R.getFoundDecl(); 10802 if (PrevDecl->isTemplateParameter()) { 10803 // Maybe we will complain about the shadowed template parameter. 10804 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10805 // Just pretend that we didn't see the previous declaration. 10806 PrevDecl = nullptr; 10807 } else if (S->isDeclScope(PrevDecl)) { 10808 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 10809 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10810 10811 // Recover by removing the name 10812 II = nullptr; 10813 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 10814 D.setInvalidType(true); 10815 } 10816 } 10817 } 10818 10819 // Temporarily put parameter variables in the translation unit, not 10820 // the enclosing context. This prevents them from accidentally 10821 // looking like class members in C++. 10822 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 10823 D.getLocStart(), 10824 D.getIdentifierLoc(), II, 10825 parmDeclType, TInfo, 10826 SC); 10827 10828 if (D.isInvalidType()) 10829 New->setInvalidDecl(); 10830 10831 assert(S->isFunctionPrototypeScope()); 10832 assert(S->getFunctionPrototypeDepth() >= 1); 10833 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 10834 S->getNextFunctionPrototypeIndex()); 10835 10836 // Add the parameter declaration into this scope. 10837 S->AddDecl(New); 10838 if (II) 10839 IdResolver.AddDecl(New); 10840 10841 ProcessDeclAttributes(S, New, D); 10842 10843 if (D.getDeclSpec().isModulePrivateSpecified()) 10844 Diag(New->getLocation(), diag::err_module_private_local) 10845 << 1 << New->getDeclName() 10846 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10847 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10848 10849 if (New->hasAttr<BlocksAttr>()) { 10850 Diag(New->getLocation(), diag::err_block_on_nonlocal); 10851 } 10852 return New; 10853 } 10854 10855 /// \brief Synthesizes a variable for a parameter arising from a 10856 /// typedef. 10857 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 10858 SourceLocation Loc, 10859 QualType T) { 10860 /* FIXME: setting StartLoc == Loc. 10861 Would it be worth to modify callers so as to provide proper source 10862 location for the unnamed parameters, embedding the parameter's type? */ 10863 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 10864 T, Context.getTrivialTypeSourceInfo(T, Loc), 10865 SC_None, nullptr); 10866 Param->setImplicit(); 10867 return Param; 10868 } 10869 10870 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 10871 ParmVarDecl * const *ParamEnd) { 10872 // Don't diagnose unused-parameter errors in template instantiations; we 10873 // will already have done so in the template itself. 10874 if (!ActiveTemplateInstantiations.empty()) 10875 return; 10876 10877 for (; Param != ParamEnd; ++Param) { 10878 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 10879 !(*Param)->hasAttr<UnusedAttr>()) { 10880 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 10881 << (*Param)->getDeclName(); 10882 } 10883 } 10884 } 10885 10886 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 10887 ParmVarDecl * const *ParamEnd, 10888 QualType ReturnTy, 10889 NamedDecl *D) { 10890 if (LangOpts.NumLargeByValueCopy == 0) // No check. 10891 return; 10892 10893 // Warn if the return value is pass-by-value and larger than the specified 10894 // threshold. 10895 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 10896 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 10897 if (Size > LangOpts.NumLargeByValueCopy) 10898 Diag(D->getLocation(), diag::warn_return_value_size) 10899 << D->getDeclName() << Size; 10900 } 10901 10902 // Warn if any parameter is pass-by-value and larger than the specified 10903 // threshold. 10904 for (; Param != ParamEnd; ++Param) { 10905 QualType T = (*Param)->getType(); 10906 if (T->isDependentType() || !T.isPODType(Context)) 10907 continue; 10908 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 10909 if (Size > LangOpts.NumLargeByValueCopy) 10910 Diag((*Param)->getLocation(), diag::warn_parameter_size) 10911 << (*Param)->getDeclName() << Size; 10912 } 10913 } 10914 10915 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 10916 SourceLocation NameLoc, IdentifierInfo *Name, 10917 QualType T, TypeSourceInfo *TSInfo, 10918 StorageClass SC) { 10919 // In ARC, infer a lifetime qualifier for appropriate parameter types. 10920 if (getLangOpts().ObjCAutoRefCount && 10921 T.getObjCLifetime() == Qualifiers::OCL_None && 10922 T->isObjCLifetimeType()) { 10923 10924 Qualifiers::ObjCLifetime lifetime; 10925 10926 // Special cases for arrays: 10927 // - if it's const, use __unsafe_unretained 10928 // - otherwise, it's an error 10929 if (T->isArrayType()) { 10930 if (!T.isConstQualified()) { 10931 DelayedDiagnostics.add( 10932 sema::DelayedDiagnostic::makeForbiddenType( 10933 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 10934 } 10935 lifetime = Qualifiers::OCL_ExplicitNone; 10936 } else { 10937 lifetime = T->getObjCARCImplicitLifetime(); 10938 } 10939 T = Context.getLifetimeQualifiedType(T, lifetime); 10940 } 10941 10942 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 10943 Context.getAdjustedParameterType(T), 10944 TSInfo, SC, nullptr); 10945 10946 // Parameters can not be abstract class types. 10947 // For record types, this is done by the AbstractClassUsageDiagnoser once 10948 // the class has been completely parsed. 10949 if (!CurContext->isRecord() && 10950 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 10951 AbstractParamType)) 10952 New->setInvalidDecl(); 10953 10954 // Parameter declarators cannot be interface types. All ObjC objects are 10955 // passed by reference. 10956 if (T->isObjCObjectType()) { 10957 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 10958 Diag(NameLoc, 10959 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 10960 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 10961 T = Context.getObjCObjectPointerType(T); 10962 New->setType(T); 10963 } 10964 10965 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 10966 // duration shall not be qualified by an address-space qualifier." 10967 // Since all parameters have automatic store duration, they can not have 10968 // an address space. 10969 if (T.getAddressSpace() != 0) { 10970 // OpenCL allows function arguments declared to be an array of a type 10971 // to be qualified with an address space. 10972 if (!(getLangOpts().OpenCL && T->isArrayType())) { 10973 Diag(NameLoc, diag::err_arg_with_address_space); 10974 New->setInvalidDecl(); 10975 } 10976 } 10977 10978 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. 10979 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. 10980 if (getLangOpts().OpenCL && T->isPointerType()) { 10981 const QualType PTy = T->getPointeeType(); 10982 if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) { 10983 Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy; 10984 New->setInvalidDecl(); 10985 } 10986 } 10987 10988 return New; 10989 } 10990 10991 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 10992 SourceLocation LocAfterDecls) { 10993 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10994 10995 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 10996 // for a K&R function. 10997 if (!FTI.hasPrototype) { 10998 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10999 --i; 11000 if (FTI.Params[i].Param == nullptr) { 11001 SmallString<256> Code; 11002 llvm::raw_svector_ostream(Code) 11003 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11004 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11005 << FTI.Params[i].Ident 11006 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11007 11008 // Implicitly declare the argument as type 'int' for lack of a better 11009 // type. 11010 AttributeFactory attrs; 11011 DeclSpec DS(attrs); 11012 const char* PrevSpec; // unused 11013 unsigned DiagID; // unused 11014 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11015 DiagID, Context.getPrintingPolicy()); 11016 // Use the identifier location for the type source range. 11017 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11018 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11019 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11020 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11021 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11022 } 11023 } 11024 } 11025 } 11026 11027 Decl * 11028 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11029 MultiTemplateParamsArg TemplateParameterLists, 11030 SkipBodyInfo *SkipBody) { 11031 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11032 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11033 Scope *ParentScope = FnBodyScope->getParent(); 11034 11035 D.setFunctionDefinitionKind(FDK_Definition); 11036 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11037 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11038 } 11039 11040 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11041 Consumer.HandleInlineFunctionDefinition(D); 11042 } 11043 11044 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11045 const FunctionDecl*& PossibleZeroParamPrototype) { 11046 // Don't warn about invalid declarations. 11047 if (FD->isInvalidDecl()) 11048 return false; 11049 11050 // Or declarations that aren't global. 11051 if (!FD->isGlobal()) 11052 return false; 11053 11054 // Don't warn about C++ member functions. 11055 if (isa<CXXMethodDecl>(FD)) 11056 return false; 11057 11058 // Don't warn about 'main'. 11059 if (FD->isMain()) 11060 return false; 11061 11062 // Don't warn about inline functions. 11063 if (FD->isInlined()) 11064 return false; 11065 11066 // Don't warn about function templates. 11067 if (FD->getDescribedFunctionTemplate()) 11068 return false; 11069 11070 // Don't warn about function template specializations. 11071 if (FD->isFunctionTemplateSpecialization()) 11072 return false; 11073 11074 // Don't warn for OpenCL kernels. 11075 if (FD->hasAttr<OpenCLKernelAttr>()) 11076 return false; 11077 11078 // Don't warn on explicitly deleted functions. 11079 if (FD->isDeleted()) 11080 return false; 11081 11082 bool MissingPrototype = true; 11083 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11084 Prev; Prev = Prev->getPreviousDecl()) { 11085 // Ignore any declarations that occur in function or method 11086 // scope, because they aren't visible from the header. 11087 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11088 continue; 11089 11090 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11091 if (FD->getNumParams() == 0) 11092 PossibleZeroParamPrototype = Prev; 11093 break; 11094 } 11095 11096 return MissingPrototype; 11097 } 11098 11099 void 11100 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11101 const FunctionDecl *EffectiveDefinition, 11102 SkipBodyInfo *SkipBody) { 11103 // Don't complain if we're in GNU89 mode and the previous definition 11104 // was an extern inline function. 11105 const FunctionDecl *Definition = EffectiveDefinition; 11106 if (!Definition) 11107 if (!FD->isDefined(Definition)) 11108 return; 11109 11110 if (canRedefineFunction(Definition, getLangOpts())) 11111 return; 11112 11113 // If we don't have a visible definition of the function, and it's inline or 11114 // a template, skip the new definition. 11115 if (SkipBody && !hasVisibleDefinition(Definition) && 11116 (Definition->getFormalLinkage() == InternalLinkage || 11117 Definition->isInlined() || 11118 Definition->getDescribedFunctionTemplate() || 11119 Definition->getNumTemplateParameterLists())) { 11120 SkipBody->ShouldSkip = true; 11121 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11122 makeMergedDefinitionVisible(TD, FD->getLocation()); 11123 else 11124 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 11125 FD->getLocation()); 11126 return; 11127 } 11128 11129 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11130 Definition->getStorageClass() == SC_Extern) 11131 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11132 << FD->getDeclName() << getLangOpts().CPlusPlus; 11133 else 11134 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11135 11136 Diag(Definition->getLocation(), diag::note_previous_definition); 11137 FD->setInvalidDecl(); 11138 } 11139 11140 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11141 Sema &S) { 11142 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11143 11144 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11145 LSI->CallOperator = CallOperator; 11146 LSI->Lambda = LambdaClass; 11147 LSI->ReturnType = CallOperator->getReturnType(); 11148 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11149 11150 if (LCD == LCD_None) 11151 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11152 else if (LCD == LCD_ByCopy) 11153 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11154 else if (LCD == LCD_ByRef) 11155 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11156 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11157 11158 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11159 LSI->Mutable = !CallOperator->isConst(); 11160 11161 // Add the captures to the LSI so they can be noted as already 11162 // captured within tryCaptureVar. 11163 auto I = LambdaClass->field_begin(); 11164 for (const auto &C : LambdaClass->captures()) { 11165 if (C.capturesVariable()) { 11166 VarDecl *VD = C.getCapturedVar(); 11167 if (VD->isInitCapture()) 11168 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11169 QualType CaptureType = VD->getType(); 11170 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11171 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11172 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11173 /*EllipsisLoc*/C.isPackExpansion() 11174 ? C.getEllipsisLoc() : SourceLocation(), 11175 CaptureType, /*Expr*/ nullptr); 11176 11177 } else if (C.capturesThis()) { 11178 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11179 S.getCurrentThisType(), /*Expr*/ nullptr, 11180 C.getCaptureKind() == LCK_StarThis); 11181 } else { 11182 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11183 } 11184 ++I; 11185 } 11186 } 11187 11188 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11189 SkipBodyInfo *SkipBody) { 11190 // Clear the last template instantiation error context. 11191 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 11192 11193 if (!D) 11194 return D; 11195 FunctionDecl *FD = nullptr; 11196 11197 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11198 FD = FunTmpl->getTemplatedDecl(); 11199 else 11200 FD = cast<FunctionDecl>(D); 11201 11202 // See if this is a redefinition. 11203 if (!FD->isLateTemplateParsed()) { 11204 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11205 11206 // If we're skipping the body, we're done. Don't enter the scope. 11207 if (SkipBody && SkipBody->ShouldSkip) 11208 return D; 11209 } 11210 11211 // If we are instantiating a generic lambda call operator, push 11212 // a LambdaScopeInfo onto the function stack. But use the information 11213 // that's already been calculated (ActOnLambdaExpr) to prime the current 11214 // LambdaScopeInfo. 11215 // When the template operator is being specialized, the LambdaScopeInfo, 11216 // has to be properly restored so that tryCaptureVariable doesn't try 11217 // and capture any new variables. In addition when calculating potential 11218 // captures during transformation of nested lambdas, it is necessary to 11219 // have the LSI properly restored. 11220 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11221 assert(ActiveTemplateInstantiations.size() && 11222 "There should be an active template instantiation on the stack " 11223 "when instantiating a generic lambda!"); 11224 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 11225 } 11226 else 11227 // Enter a new function scope 11228 PushFunctionScope(); 11229 11230 // Builtin functions cannot be defined. 11231 if (unsigned BuiltinID = FD->getBuiltinID()) { 11232 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 11233 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 11234 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 11235 FD->setInvalidDecl(); 11236 } 11237 } 11238 11239 // The return type of a function definition must be complete 11240 // (C99 6.9.1p3, C++ [dcl.fct]p6). 11241 QualType ResultType = FD->getReturnType(); 11242 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 11243 !FD->isInvalidDecl() && 11244 RequireCompleteType(FD->getLocation(), ResultType, 11245 diag::err_func_def_incomplete_result)) 11246 FD->setInvalidDecl(); 11247 11248 if (FnBodyScope) 11249 PushDeclContext(FnBodyScope, FD); 11250 11251 // Check the validity of our function parameters 11252 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 11253 /*CheckParameterNames=*/true); 11254 11255 // Introduce our parameters into the function scope 11256 for (auto Param : FD->params()) { 11257 Param->setOwningFunction(FD); 11258 11259 // If this has an identifier, add it to the scope stack. 11260 if (Param->getIdentifier() && FnBodyScope) { 11261 CheckShadow(FnBodyScope, Param); 11262 11263 PushOnScopeChains(Param, FnBodyScope); 11264 } 11265 } 11266 11267 // If we had any tags defined in the function prototype, 11268 // introduce them into the function scope. 11269 if (FnBodyScope) { 11270 for (ArrayRef<NamedDecl *>::iterator 11271 I = FD->getDeclsInPrototypeScope().begin(), 11272 E = FD->getDeclsInPrototypeScope().end(); 11273 I != E; ++I) { 11274 NamedDecl *D = *I; 11275 11276 // Some of these decls (like enums) may have been pinned to the 11277 // translation unit for lack of a real context earlier. If so, remove 11278 // from the translation unit and reattach to the current context. 11279 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 11280 // Is the decl actually in the context? 11281 if (Context.getTranslationUnitDecl()->containsDecl(D)) 11282 Context.getTranslationUnitDecl()->removeDecl(D); 11283 // Either way, reassign the lexical decl context to our FunctionDecl. 11284 D->setLexicalDeclContext(CurContext); 11285 } 11286 11287 // If the decl has a non-null name, make accessible in the current scope. 11288 if (!D->getName().empty()) 11289 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 11290 11291 // Similarly, dive into enums and fish their constants out, making them 11292 // accessible in this scope. 11293 if (auto *ED = dyn_cast<EnumDecl>(D)) { 11294 for (auto *EI : ED->enumerators()) 11295 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11296 } 11297 } 11298 } 11299 11300 // Ensure that the function's exception specification is instantiated. 11301 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11302 ResolveExceptionSpec(D->getLocation(), FPT); 11303 11304 // dllimport cannot be applied to non-inline function definitions. 11305 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11306 !FD->isTemplateInstantiation()) { 11307 assert(!FD->hasAttr<DLLExportAttr>()); 11308 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11309 FD->setInvalidDecl(); 11310 return D; 11311 } 11312 // We want to attach documentation to original Decl (which might be 11313 // a function template). 11314 ActOnDocumentableDecl(D); 11315 if (getCurLexicalContext()->isObjCContainer() && 11316 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11317 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11318 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11319 11320 return D; 11321 } 11322 11323 /// \brief Given the set of return statements within a function body, 11324 /// compute the variables that are subject to the named return value 11325 /// optimization. 11326 /// 11327 /// Each of the variables that is subject to the named return value 11328 /// optimization will be marked as NRVO variables in the AST, and any 11329 /// return statement that has a marked NRVO variable as its NRVO candidate can 11330 /// use the named return value optimization. 11331 /// 11332 /// This function applies a very simplistic algorithm for NRVO: if every return 11333 /// statement in the scope of a variable has the same NRVO candidate, that 11334 /// candidate is an NRVO variable. 11335 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11336 ReturnStmt **Returns = Scope->Returns.data(); 11337 11338 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11339 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11340 if (!NRVOCandidate->isNRVOVariable()) 11341 Returns[I]->setNRVOCandidate(nullptr); 11342 } 11343 } 11344 } 11345 11346 bool Sema::canDelayFunctionBody(const Declarator &D) { 11347 // We can't delay parsing the body of a constexpr function template (yet). 11348 if (D.getDeclSpec().isConstexprSpecified()) 11349 return false; 11350 11351 // We can't delay parsing the body of a function template with a deduced 11352 // return type (yet). 11353 if (D.getDeclSpec().containsPlaceholderType()) { 11354 // If the placeholder introduces a non-deduced trailing return type, 11355 // we can still delay parsing it. 11356 if (D.getNumTypeObjects()) { 11357 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11358 if (Outer.Kind == DeclaratorChunk::Function && 11359 Outer.Fun.hasTrailingReturnType()) { 11360 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11361 return Ty.isNull() || !Ty->isUndeducedType(); 11362 } 11363 } 11364 return false; 11365 } 11366 11367 return true; 11368 } 11369 11370 bool Sema::canSkipFunctionBody(Decl *D) { 11371 // We cannot skip the body of a function (or function template) which is 11372 // constexpr, since we may need to evaluate its body in order to parse the 11373 // rest of the file. 11374 // We cannot skip the body of a function with an undeduced return type, 11375 // because any callers of that function need to know the type. 11376 if (const FunctionDecl *FD = D->getAsFunction()) 11377 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11378 return false; 11379 return Consumer.shouldSkipFunctionBody(D); 11380 } 11381 11382 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11383 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11384 FD->setHasSkippedBody(); 11385 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11386 MD->setHasSkippedBody(); 11387 return ActOnFinishFunctionBody(Decl, nullptr); 11388 } 11389 11390 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11391 return ActOnFinishFunctionBody(D, BodyArg, false); 11392 } 11393 11394 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11395 bool IsInstantiation) { 11396 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11397 11398 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11399 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11400 11401 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty()) 11402 CheckCompletedCoroutineBody(FD, Body); 11403 11404 if (FD) { 11405 FD->setBody(Body); 11406 11407 if (getLangOpts().CPlusPlus14) { 11408 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 11409 FD->getReturnType()->isUndeducedType()) { 11410 // If the function has a deduced result type but contains no 'return' 11411 // statements, the result type as written must be exactly 'auto', and 11412 // the deduced result type is 'void'. 11413 if (!FD->getReturnType()->getAs<AutoType>()) { 11414 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 11415 << FD->getReturnType(); 11416 FD->setInvalidDecl(); 11417 } else { 11418 // Substitute 'void' for the 'auto' in the type. 11419 TypeLoc ResultType = getReturnTypeLoc(FD); 11420 Context.adjustDeducedFunctionResultType( 11421 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 11422 } 11423 } 11424 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11425 // In C++11, we don't use 'auto' deduction rules for lambda call 11426 // operators because we don't support return type deduction. 11427 auto *LSI = getCurLambda(); 11428 if (LSI->HasImplicitReturnType) { 11429 deduceClosureReturnType(*LSI); 11430 11431 // C++11 [expr.prim.lambda]p4: 11432 // [...] if there are no return statements in the compound-statement 11433 // [the deduced type is] the type void 11434 QualType RetType = 11435 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11436 11437 // Update the return type to the deduced type. 11438 const FunctionProtoType *Proto = 11439 FD->getType()->getAs<FunctionProtoType>(); 11440 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11441 Proto->getExtProtoInfo())); 11442 } 11443 } 11444 11445 // The only way to be included in UndefinedButUsed is if there is an 11446 // ODR use before the definition. Avoid the expensive map lookup if this 11447 // is the first declaration. 11448 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11449 if (!FD->isExternallyVisible()) 11450 UndefinedButUsed.erase(FD); 11451 else if (FD->isInlined() && 11452 !LangOpts.GNUInline && 11453 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11454 UndefinedButUsed.erase(FD); 11455 } 11456 11457 // If the function implicitly returns zero (like 'main') or is naked, 11458 // don't complain about missing return statements. 11459 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11460 WP.disableCheckFallThrough(); 11461 11462 // MSVC permits the use of pure specifier (=0) on function definition, 11463 // defined at class scope, warn about this non-standard construct. 11464 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11465 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11466 11467 if (!FD->isInvalidDecl()) { 11468 // Don't diagnose unused parameters of defaulted or deleted functions. 11469 if (!FD->isDeleted() && !FD->isDefaulted()) 11470 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 11471 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 11472 FD->getReturnType(), FD); 11473 11474 // If this is a structor, we need a vtable. 11475 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11476 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11477 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 11478 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 11479 11480 // Try to apply the named return value optimization. We have to check 11481 // if we can do this here because lambdas keep return statements around 11482 // to deduce an implicit return type. 11483 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 11484 !FD->isDependentContext()) 11485 computeNRVO(Body, getCurFunction()); 11486 } 11487 11488 // GNU warning -Wmissing-prototypes: 11489 // Warn if a global function is defined without a previous 11490 // prototype declaration. This warning is issued even if the 11491 // definition itself provides a prototype. The aim is to detect 11492 // global functions that fail to be declared in header files. 11493 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 11494 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 11495 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 11496 11497 if (PossibleZeroParamPrototype) { 11498 // We found a declaration that is not a prototype, 11499 // but that could be a zero-parameter prototype 11500 if (TypeSourceInfo *TI = 11501 PossibleZeroParamPrototype->getTypeSourceInfo()) { 11502 TypeLoc TL = TI->getTypeLoc(); 11503 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 11504 Diag(PossibleZeroParamPrototype->getLocation(), 11505 diag::note_declaration_not_a_prototype) 11506 << PossibleZeroParamPrototype 11507 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 11508 } 11509 } 11510 } 11511 11512 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11513 const CXXMethodDecl *KeyFunction; 11514 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 11515 MD->isVirtual() && 11516 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 11517 MD == KeyFunction->getCanonicalDecl()) { 11518 // Update the key-function state if necessary for this ABI. 11519 if (FD->isInlined() && 11520 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11521 Context.setNonKeyFunction(MD); 11522 11523 // If the newly-chosen key function is already defined, then we 11524 // need to mark the vtable as used retroactively. 11525 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 11526 const FunctionDecl *Definition; 11527 if (KeyFunction && KeyFunction->isDefined(Definition)) 11528 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 11529 } else { 11530 // We just defined they key function; mark the vtable as used. 11531 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 11532 } 11533 } 11534 } 11535 11536 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 11537 "Function parsing confused"); 11538 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 11539 assert(MD == getCurMethodDecl() && "Method parsing confused"); 11540 MD->setBody(Body); 11541 if (!MD->isInvalidDecl()) { 11542 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 11543 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 11544 MD->getReturnType(), MD); 11545 11546 if (Body) 11547 computeNRVO(Body, getCurFunction()); 11548 } 11549 if (getCurFunction()->ObjCShouldCallSuper) { 11550 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 11551 << MD->getSelector().getAsString(); 11552 getCurFunction()->ObjCShouldCallSuper = false; 11553 } 11554 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 11555 const ObjCMethodDecl *InitMethod = nullptr; 11556 bool isDesignated = 11557 MD->isDesignatedInitializerForTheInterface(&InitMethod); 11558 assert(isDesignated && InitMethod); 11559 (void)isDesignated; 11560 11561 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 11562 auto IFace = MD->getClassInterface(); 11563 if (!IFace) 11564 return false; 11565 auto SuperD = IFace->getSuperClass(); 11566 if (!SuperD) 11567 return false; 11568 return SuperD->getIdentifier() == 11569 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 11570 }; 11571 // Don't issue this warning for unavailable inits or direct subclasses 11572 // of NSObject. 11573 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 11574 Diag(MD->getLocation(), 11575 diag::warn_objc_designated_init_missing_super_call); 11576 Diag(InitMethod->getLocation(), 11577 diag::note_objc_designated_init_marked_here); 11578 } 11579 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 11580 } 11581 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 11582 // Don't issue this warning for unavaialable inits. 11583 if (!MD->isUnavailable()) 11584 Diag(MD->getLocation(), 11585 diag::warn_objc_secondary_init_missing_init_call); 11586 getCurFunction()->ObjCWarnForNoInitDelegation = false; 11587 } 11588 } else { 11589 return nullptr; 11590 } 11591 11592 assert(!getCurFunction()->ObjCShouldCallSuper && 11593 "This should only be set for ObjC methods, which should have been " 11594 "handled in the block above."); 11595 11596 // Verify and clean out per-function state. 11597 if (Body && (!FD || !FD->isDefaulted())) { 11598 // C++ constructors that have function-try-blocks can't have return 11599 // statements in the handlers of that block. (C++ [except.handle]p14) 11600 // Verify this. 11601 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 11602 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 11603 11604 // Verify that gotos and switch cases don't jump into scopes illegally. 11605 if (getCurFunction()->NeedsScopeChecking() && 11606 !PP.isCodeCompletionEnabled()) 11607 DiagnoseInvalidJumps(Body); 11608 11609 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 11610 if (!Destructor->getParent()->isDependentType()) 11611 CheckDestructor(Destructor); 11612 11613 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11614 Destructor->getParent()); 11615 } 11616 11617 // If any errors have occurred, clear out any temporaries that may have 11618 // been leftover. This ensures that these temporaries won't be picked up for 11619 // deletion in some later function. 11620 if (getDiagnostics().hasErrorOccurred() || 11621 getDiagnostics().getSuppressAllDiagnostics()) { 11622 DiscardCleanupsInEvaluationContext(); 11623 } 11624 if (!getDiagnostics().hasUncompilableErrorOccurred() && 11625 !isa<FunctionTemplateDecl>(dcl)) { 11626 // Since the body is valid, issue any analysis-based warnings that are 11627 // enabled. 11628 ActivePolicy = &WP; 11629 } 11630 11631 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 11632 (!CheckConstexprFunctionDecl(FD) || 11633 !CheckConstexprFunctionBody(FD, Body))) 11634 FD->setInvalidDecl(); 11635 11636 if (FD && FD->hasAttr<NakedAttr>()) { 11637 for (const Stmt *S : Body->children()) { 11638 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 11639 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 11640 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 11641 FD->setInvalidDecl(); 11642 break; 11643 } 11644 } 11645 } 11646 11647 assert(ExprCleanupObjects.size() == 11648 ExprEvalContexts.back().NumCleanupObjects && 11649 "Leftover temporaries in function"); 11650 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 11651 assert(MaybeODRUseExprs.empty() && 11652 "Leftover expressions for odr-use checking"); 11653 } 11654 11655 if (!IsInstantiation) 11656 PopDeclContext(); 11657 11658 PopFunctionScopeInfo(ActivePolicy, dcl); 11659 // If any errors have occurred, clear out any temporaries that may have 11660 // been leftover. This ensures that these temporaries won't be picked up for 11661 // deletion in some later function. 11662 if (getDiagnostics().hasErrorOccurred()) { 11663 DiscardCleanupsInEvaluationContext(); 11664 } 11665 11666 return dcl; 11667 } 11668 11669 /// When we finish delayed parsing of an attribute, we must attach it to the 11670 /// relevant Decl. 11671 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 11672 ParsedAttributes &Attrs) { 11673 // Always attach attributes to the underlying decl. 11674 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 11675 D = TD->getTemplatedDecl(); 11676 ProcessDeclAttributeList(S, D, Attrs.getList()); 11677 11678 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 11679 if (Method->isStatic()) 11680 checkThisInStaticMemberFunctionAttributes(Method); 11681 } 11682 11683 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 11684 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 11685 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 11686 IdentifierInfo &II, Scope *S) { 11687 // Before we produce a declaration for an implicitly defined 11688 // function, see whether there was a locally-scoped declaration of 11689 // this name as a function or variable. If so, use that 11690 // (non-visible) declaration, and complain about it. 11691 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 11692 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 11693 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 11694 return ExternCPrev; 11695 } 11696 11697 // Extension in C99. Legal in C90, but warn about it. 11698 unsigned diag_id; 11699 if (II.getName().startswith("__builtin_")) 11700 diag_id = diag::warn_builtin_unknown; 11701 else if (getLangOpts().C99) 11702 diag_id = diag::ext_implicit_function_decl; 11703 else 11704 diag_id = diag::warn_implicit_function_decl; 11705 Diag(Loc, diag_id) << &II; 11706 11707 // Because typo correction is expensive, only do it if the implicit 11708 // function declaration is going to be treated as an error. 11709 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 11710 TypoCorrection Corrected; 11711 if (S && 11712 (Corrected = CorrectTypo( 11713 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 11714 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 11715 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 11716 /*ErrorRecovery*/false); 11717 } 11718 11719 // Set a Declarator for the implicit definition: int foo(); 11720 const char *Dummy; 11721 AttributeFactory attrFactory; 11722 DeclSpec DS(attrFactory); 11723 unsigned DiagID; 11724 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 11725 Context.getPrintingPolicy()); 11726 (void)Error; // Silence warning. 11727 assert(!Error && "Error setting up implicit decl!"); 11728 SourceLocation NoLoc; 11729 Declarator D(DS, Declarator::BlockContext); 11730 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 11731 /*IsAmbiguous=*/false, 11732 /*LParenLoc=*/NoLoc, 11733 /*Params=*/nullptr, 11734 /*NumParams=*/0, 11735 /*EllipsisLoc=*/NoLoc, 11736 /*RParenLoc=*/NoLoc, 11737 /*TypeQuals=*/0, 11738 /*RefQualifierIsLvalueRef=*/true, 11739 /*RefQualifierLoc=*/NoLoc, 11740 /*ConstQualifierLoc=*/NoLoc, 11741 /*VolatileQualifierLoc=*/NoLoc, 11742 /*RestrictQualifierLoc=*/NoLoc, 11743 /*MutableLoc=*/NoLoc, 11744 EST_None, 11745 /*ESpecRange=*/SourceRange(), 11746 /*Exceptions=*/nullptr, 11747 /*ExceptionRanges=*/nullptr, 11748 /*NumExceptions=*/0, 11749 /*NoexceptExpr=*/nullptr, 11750 /*ExceptionSpecTokens=*/nullptr, 11751 Loc, Loc, D), 11752 DS.getAttributes(), 11753 SourceLocation()); 11754 D.SetIdentifier(&II, Loc); 11755 11756 // Insert this function into translation-unit scope. 11757 11758 DeclContext *PrevDC = CurContext; 11759 CurContext = Context.getTranslationUnitDecl(); 11760 11761 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 11762 FD->setImplicit(); 11763 11764 CurContext = PrevDC; 11765 11766 AddKnownFunctionAttributes(FD); 11767 11768 return FD; 11769 } 11770 11771 /// \brief Adds any function attributes that we know a priori based on 11772 /// the declaration of this function. 11773 /// 11774 /// These attributes can apply both to implicitly-declared builtins 11775 /// (like __builtin___printf_chk) or to library-declared functions 11776 /// like NSLog or printf. 11777 /// 11778 /// We need to check for duplicate attributes both here and where user-written 11779 /// attributes are applied to declarations. 11780 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 11781 if (FD->isInvalidDecl()) 11782 return; 11783 11784 // If this is a built-in function, map its builtin attributes to 11785 // actual attributes. 11786 if (unsigned BuiltinID = FD->getBuiltinID()) { 11787 // Handle printf-formatting attributes. 11788 unsigned FormatIdx; 11789 bool HasVAListArg; 11790 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 11791 if (!FD->hasAttr<FormatAttr>()) { 11792 const char *fmt = "printf"; 11793 unsigned int NumParams = FD->getNumParams(); 11794 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 11795 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 11796 fmt = "NSString"; 11797 FD->addAttr(FormatAttr::CreateImplicit(Context, 11798 &Context.Idents.get(fmt), 11799 FormatIdx+1, 11800 HasVAListArg ? 0 : FormatIdx+2, 11801 FD->getLocation())); 11802 } 11803 } 11804 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 11805 HasVAListArg)) { 11806 if (!FD->hasAttr<FormatAttr>()) 11807 FD->addAttr(FormatAttr::CreateImplicit(Context, 11808 &Context.Idents.get("scanf"), 11809 FormatIdx+1, 11810 HasVAListArg ? 0 : FormatIdx+2, 11811 FD->getLocation())); 11812 } 11813 11814 // Mark const if we don't care about errno and that is the only 11815 // thing preventing the function from being const. This allows 11816 // IRgen to use LLVM intrinsics for such functions. 11817 if (!getLangOpts().MathErrno && 11818 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 11819 if (!FD->hasAttr<ConstAttr>()) 11820 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11821 } 11822 11823 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 11824 !FD->hasAttr<ReturnsTwiceAttr>()) 11825 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 11826 FD->getLocation())); 11827 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 11828 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 11829 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 11830 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 11831 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 11832 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11833 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 11834 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 11835 // Add the appropriate attribute, depending on the CUDA compilation mode 11836 // and which target the builtin belongs to. For example, during host 11837 // compilation, aux builtins are __device__, while the rest are __host__. 11838 if (getLangOpts().CUDAIsDevice != 11839 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 11840 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 11841 else 11842 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 11843 } 11844 } 11845 11846 // If C++ exceptions are enabled but we are told extern "C" functions cannot 11847 // throw, add an implicit nothrow attribute to any extern "C" function we come 11848 // across. 11849 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 11850 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 11851 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 11852 if (!FPT || FPT->getExceptionSpecType() == EST_None) 11853 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 11854 } 11855 11856 IdentifierInfo *Name = FD->getIdentifier(); 11857 if (!Name) 11858 return; 11859 if ((!getLangOpts().CPlusPlus && 11860 FD->getDeclContext()->isTranslationUnit()) || 11861 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 11862 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 11863 LinkageSpecDecl::lang_c)) { 11864 // Okay: this could be a libc/libm/Objective-C function we know 11865 // about. 11866 } else 11867 return; 11868 11869 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 11870 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 11871 // target-specific builtins, perhaps? 11872 if (!FD->hasAttr<FormatAttr>()) 11873 FD->addAttr(FormatAttr::CreateImplicit(Context, 11874 &Context.Idents.get("printf"), 2, 11875 Name->isStr("vasprintf") ? 0 : 3, 11876 FD->getLocation())); 11877 } 11878 11879 if (Name->isStr("__CFStringMakeConstantString")) { 11880 // We already have a __builtin___CFStringMakeConstantString, 11881 // but builds that use -fno-constant-cfstrings don't go through that. 11882 if (!FD->hasAttr<FormatArgAttr>()) 11883 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 11884 FD->getLocation())); 11885 } 11886 } 11887 11888 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 11889 TypeSourceInfo *TInfo) { 11890 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 11891 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 11892 11893 if (!TInfo) { 11894 assert(D.isInvalidType() && "no declarator info for valid type"); 11895 TInfo = Context.getTrivialTypeSourceInfo(T); 11896 } 11897 11898 // Scope manipulation handled by caller. 11899 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 11900 D.getLocStart(), 11901 D.getIdentifierLoc(), 11902 D.getIdentifier(), 11903 TInfo); 11904 11905 // Bail out immediately if we have an invalid declaration. 11906 if (D.isInvalidType()) { 11907 NewTD->setInvalidDecl(); 11908 return NewTD; 11909 } 11910 11911 if (D.getDeclSpec().isModulePrivateSpecified()) { 11912 if (CurContext->isFunctionOrMethod()) 11913 Diag(NewTD->getLocation(), diag::err_module_private_local) 11914 << 2 << NewTD->getDeclName() 11915 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11916 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11917 else 11918 NewTD->setModulePrivate(); 11919 } 11920 11921 // C++ [dcl.typedef]p8: 11922 // If the typedef declaration defines an unnamed class (or 11923 // enum), the first typedef-name declared by the declaration 11924 // to be that class type (or enum type) is used to denote the 11925 // class type (or enum type) for linkage purposes only. 11926 // We need to check whether the type was declared in the declaration. 11927 switch (D.getDeclSpec().getTypeSpecType()) { 11928 case TST_enum: 11929 case TST_struct: 11930 case TST_interface: 11931 case TST_union: 11932 case TST_class: { 11933 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 11934 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 11935 break; 11936 } 11937 11938 default: 11939 break; 11940 } 11941 11942 return NewTD; 11943 } 11944 11945 /// \brief Check that this is a valid underlying type for an enum declaration. 11946 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 11947 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 11948 QualType T = TI->getType(); 11949 11950 if (T->isDependentType()) 11951 return false; 11952 11953 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 11954 if (BT->isInteger()) 11955 return false; 11956 11957 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 11958 return true; 11959 } 11960 11961 /// Check whether this is a valid redeclaration of a previous enumeration. 11962 /// \return true if the redeclaration was invalid. 11963 bool Sema::CheckEnumRedeclaration( 11964 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 11965 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 11966 bool IsFixed = !EnumUnderlyingTy.isNull(); 11967 11968 if (IsScoped != Prev->isScoped()) { 11969 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 11970 << Prev->isScoped(); 11971 Diag(Prev->getLocation(), diag::note_previous_declaration); 11972 return true; 11973 } 11974 11975 if (IsFixed && Prev->isFixed()) { 11976 if (!EnumUnderlyingTy->isDependentType() && 11977 !Prev->getIntegerType()->isDependentType() && 11978 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 11979 Prev->getIntegerType())) { 11980 // TODO: Highlight the underlying type of the redeclaration. 11981 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 11982 << EnumUnderlyingTy << Prev->getIntegerType(); 11983 Diag(Prev->getLocation(), diag::note_previous_declaration) 11984 << Prev->getIntegerTypeRange(); 11985 return true; 11986 } 11987 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 11988 ; 11989 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 11990 ; 11991 } else if (IsFixed != Prev->isFixed()) { 11992 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 11993 << Prev->isFixed(); 11994 Diag(Prev->getLocation(), diag::note_previous_declaration); 11995 return true; 11996 } 11997 11998 return false; 11999 } 12000 12001 /// \brief Get diagnostic %select index for tag kind for 12002 /// redeclaration diagnostic message. 12003 /// WARNING: Indexes apply to particular diagnostics only! 12004 /// 12005 /// \returns diagnostic %select index. 12006 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12007 switch (Tag) { 12008 case TTK_Struct: return 0; 12009 case TTK_Interface: return 1; 12010 case TTK_Class: return 2; 12011 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12012 } 12013 } 12014 12015 /// \brief Determine if tag kind is a class-key compatible with 12016 /// class for redeclaration (class, struct, or __interface). 12017 /// 12018 /// \returns true iff the tag kind is compatible. 12019 static bool isClassCompatTagKind(TagTypeKind Tag) 12020 { 12021 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12022 } 12023 12024 /// \brief Determine whether a tag with a given kind is acceptable 12025 /// as a redeclaration of the given tag declaration. 12026 /// 12027 /// \returns true if the new tag kind is acceptable, false otherwise. 12028 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12029 TagTypeKind NewTag, bool isDefinition, 12030 SourceLocation NewTagLoc, 12031 const IdentifierInfo *Name) { 12032 // C++ [dcl.type.elab]p3: 12033 // The class-key or enum keyword present in the 12034 // elaborated-type-specifier shall agree in kind with the 12035 // declaration to which the name in the elaborated-type-specifier 12036 // refers. This rule also applies to the form of 12037 // elaborated-type-specifier that declares a class-name or 12038 // friend class since it can be construed as referring to the 12039 // definition of the class. Thus, in any 12040 // elaborated-type-specifier, the enum keyword shall be used to 12041 // refer to an enumeration (7.2), the union class-key shall be 12042 // used to refer to a union (clause 9), and either the class or 12043 // struct class-key shall be used to refer to a class (clause 9) 12044 // declared using the class or struct class-key. 12045 TagTypeKind OldTag = Previous->getTagKind(); 12046 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12047 if (OldTag == NewTag) 12048 return true; 12049 12050 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12051 // Warn about the struct/class tag mismatch. 12052 bool isTemplate = false; 12053 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12054 isTemplate = Record->getDescribedClassTemplate(); 12055 12056 if (!ActiveTemplateInstantiations.empty()) { 12057 // In a template instantiation, do not offer fix-its for tag mismatches 12058 // since they usually mess up the template instead of fixing the problem. 12059 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12060 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12061 << getRedeclDiagFromTagKind(OldTag); 12062 return true; 12063 } 12064 12065 if (isDefinition) { 12066 // On definitions, check previous tags and issue a fix-it for each 12067 // one that doesn't match the current tag. 12068 if (Previous->getDefinition()) { 12069 // Don't suggest fix-its for redefinitions. 12070 return true; 12071 } 12072 12073 bool previousMismatch = false; 12074 for (auto I : Previous->redecls()) { 12075 if (I->getTagKind() != NewTag) { 12076 if (!previousMismatch) { 12077 previousMismatch = true; 12078 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12079 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12080 << getRedeclDiagFromTagKind(I->getTagKind()); 12081 } 12082 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12083 << getRedeclDiagFromTagKind(NewTag) 12084 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12085 TypeWithKeyword::getTagTypeKindName(NewTag)); 12086 } 12087 } 12088 return true; 12089 } 12090 12091 // Check for a previous definition. If current tag and definition 12092 // are same type, do nothing. If no definition, but disagree with 12093 // with previous tag type, give a warning, but no fix-it. 12094 const TagDecl *Redecl = Previous->getDefinition() ? 12095 Previous->getDefinition() : Previous; 12096 if (Redecl->getTagKind() == NewTag) { 12097 return true; 12098 } 12099 12100 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12101 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12102 << getRedeclDiagFromTagKind(OldTag); 12103 Diag(Redecl->getLocation(), diag::note_previous_use); 12104 12105 // If there is a previous definition, suggest a fix-it. 12106 if (Previous->getDefinition()) { 12107 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12108 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12109 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12110 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12111 } 12112 12113 return true; 12114 } 12115 return false; 12116 } 12117 12118 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12119 /// from an outer enclosing namespace or file scope inside a friend declaration. 12120 /// This should provide the commented out code in the following snippet: 12121 /// namespace N { 12122 /// struct X; 12123 /// namespace M { 12124 /// struct Y { friend struct /*N::*/ X; }; 12125 /// } 12126 /// } 12127 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12128 SourceLocation NameLoc) { 12129 // While the decl is in a namespace, do repeated lookup of that name and see 12130 // if we get the same namespace back. If we do not, continue until 12131 // translation unit scope, at which point we have a fully qualified NNS. 12132 SmallVector<IdentifierInfo *, 4> Namespaces; 12133 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12134 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12135 // This tag should be declared in a namespace, which can only be enclosed by 12136 // other namespaces. Bail if there's an anonymous namespace in the chain. 12137 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12138 if (!Namespace || Namespace->isAnonymousNamespace()) 12139 return FixItHint(); 12140 IdentifierInfo *II = Namespace->getIdentifier(); 12141 Namespaces.push_back(II); 12142 NamedDecl *Lookup = SemaRef.LookupSingleName( 12143 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12144 if (Lookup == Namespace) 12145 break; 12146 } 12147 12148 // Once we have all the namespaces, reverse them to go outermost first, and 12149 // build an NNS. 12150 SmallString<64> Insertion; 12151 llvm::raw_svector_ostream OS(Insertion); 12152 if (DC->isTranslationUnit()) 12153 OS << "::"; 12154 std::reverse(Namespaces.begin(), Namespaces.end()); 12155 for (auto *II : Namespaces) 12156 OS << II->getName() << "::"; 12157 return FixItHint::CreateInsertion(NameLoc, Insertion); 12158 } 12159 12160 /// \brief Determine whether a tag originally declared in context \p OldDC can 12161 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12162 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12163 /// using-declaration). 12164 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12165 DeclContext *NewDC) { 12166 OldDC = OldDC->getRedeclContext(); 12167 NewDC = NewDC->getRedeclContext(); 12168 12169 if (OldDC->Equals(NewDC)) 12170 return true; 12171 12172 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12173 // encloses the other). 12174 if (S.getLangOpts().MSVCCompat && 12175 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 12176 return true; 12177 12178 return false; 12179 } 12180 12181 /// Find the DeclContext in which a tag is implicitly declared if we see an 12182 /// elaborated type specifier in the specified context, and lookup finds 12183 /// nothing. 12184 static DeclContext *getTagInjectionContext(DeclContext *DC) { 12185 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 12186 DC = DC->getParent(); 12187 return DC; 12188 } 12189 12190 /// Find the Scope in which a tag is implicitly declared if we see an 12191 /// elaborated type specifier in the specified context, and lookup finds 12192 /// nothing. 12193 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 12194 while (S->isClassScope() || 12195 (LangOpts.CPlusPlus && 12196 S->isFunctionPrototypeScope()) || 12197 ((S->getFlags() & Scope::DeclScope) == 0) || 12198 (S->getEntity() && S->getEntity()->isTransparentContext())) 12199 S = S->getParent(); 12200 return S; 12201 } 12202 12203 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 12204 /// former case, Name will be non-null. In the later case, Name will be null. 12205 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 12206 /// reference/declaration/definition of a tag. 12207 /// 12208 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 12209 /// trailing-type-specifier) other than one in an alias-declaration. 12210 /// 12211 /// \param SkipBody If non-null, will be set to indicate if the caller should 12212 /// skip the definition of this tag and treat it as if it were a declaration. 12213 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12214 SourceLocation KWLoc, CXXScopeSpec &SS, 12215 IdentifierInfo *Name, SourceLocation NameLoc, 12216 AttributeList *Attr, AccessSpecifier AS, 12217 SourceLocation ModulePrivateLoc, 12218 MultiTemplateParamsArg TemplateParameterLists, 12219 bool &OwnedDecl, bool &IsDependent, 12220 SourceLocation ScopedEnumKWLoc, 12221 bool ScopedEnumUsesClassTag, 12222 TypeResult UnderlyingType, 12223 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 12224 // If this is not a definition, it must have a name. 12225 IdentifierInfo *OrigName = Name; 12226 assert((Name != nullptr || TUK == TUK_Definition) && 12227 "Nameless record must be a definition!"); 12228 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 12229 12230 OwnedDecl = false; 12231 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12232 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 12233 12234 // FIXME: Check explicit specializations more carefully. 12235 bool isExplicitSpecialization = false; 12236 bool Invalid = false; 12237 12238 // We only need to do this matching if we have template parameters 12239 // or a scope specifier, which also conveniently avoids this work 12240 // for non-C++ cases. 12241 if (TemplateParameterLists.size() > 0 || 12242 (SS.isNotEmpty() && TUK != TUK_Reference)) { 12243 if (TemplateParameterList *TemplateParams = 12244 MatchTemplateParametersToScopeSpecifier( 12245 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 12246 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 12247 if (Kind == TTK_Enum) { 12248 Diag(KWLoc, diag::err_enum_template); 12249 return nullptr; 12250 } 12251 12252 if (TemplateParams->size() > 0) { 12253 // This is a declaration or definition of a class template (which may 12254 // be a member of another template). 12255 12256 if (Invalid) 12257 return nullptr; 12258 12259 OwnedDecl = false; 12260 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 12261 SS, Name, NameLoc, Attr, 12262 TemplateParams, AS, 12263 ModulePrivateLoc, 12264 /*FriendLoc*/SourceLocation(), 12265 TemplateParameterLists.size()-1, 12266 TemplateParameterLists.data(), 12267 SkipBody); 12268 return Result.get(); 12269 } else { 12270 // The "template<>" header is extraneous. 12271 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12272 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12273 isExplicitSpecialization = true; 12274 } 12275 } 12276 } 12277 12278 // Figure out the underlying type if this a enum declaration. We need to do 12279 // this early, because it's needed to detect if this is an incompatible 12280 // redeclaration. 12281 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12282 bool EnumUnderlyingIsImplicit = false; 12283 12284 if (Kind == TTK_Enum) { 12285 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12286 // No underlying type explicitly specified, or we failed to parse the 12287 // type, default to int. 12288 EnumUnderlying = Context.IntTy.getTypePtr(); 12289 else if (UnderlyingType.get()) { 12290 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12291 // integral type; any cv-qualification is ignored. 12292 TypeSourceInfo *TI = nullptr; 12293 GetTypeFromParser(UnderlyingType.get(), &TI); 12294 EnumUnderlying = TI; 12295 12296 if (CheckEnumUnderlyingType(TI)) 12297 // Recover by falling back to int. 12298 EnumUnderlying = Context.IntTy.getTypePtr(); 12299 12300 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12301 UPPC_FixedUnderlyingType)) 12302 EnumUnderlying = Context.IntTy.getTypePtr(); 12303 12304 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12305 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12306 // Microsoft enums are always of int type. 12307 EnumUnderlying = Context.IntTy.getTypePtr(); 12308 EnumUnderlyingIsImplicit = true; 12309 } 12310 } 12311 } 12312 12313 DeclContext *SearchDC = CurContext; 12314 DeclContext *DC = CurContext; 12315 bool isStdBadAlloc = false; 12316 12317 RedeclarationKind Redecl = ForRedeclaration; 12318 if (TUK == TUK_Friend || TUK == TUK_Reference) 12319 Redecl = NotForRedeclaration; 12320 12321 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12322 if (Name && SS.isNotEmpty()) { 12323 // We have a nested-name tag ('struct foo::bar'). 12324 12325 // Check for invalid 'foo::'. 12326 if (SS.isInvalid()) { 12327 Name = nullptr; 12328 goto CreateNewDecl; 12329 } 12330 12331 // If this is a friend or a reference to a class in a dependent 12332 // context, don't try to make a decl for it. 12333 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12334 DC = computeDeclContext(SS, false); 12335 if (!DC) { 12336 IsDependent = true; 12337 return nullptr; 12338 } 12339 } else { 12340 DC = computeDeclContext(SS, true); 12341 if (!DC) { 12342 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12343 << SS.getRange(); 12344 return nullptr; 12345 } 12346 } 12347 12348 if (RequireCompleteDeclContext(SS, DC)) 12349 return nullptr; 12350 12351 SearchDC = DC; 12352 // Look-up name inside 'foo::'. 12353 LookupQualifiedName(Previous, DC); 12354 12355 if (Previous.isAmbiguous()) 12356 return nullptr; 12357 12358 if (Previous.empty()) { 12359 // Name lookup did not find anything. However, if the 12360 // nested-name-specifier refers to the current instantiation, 12361 // and that current instantiation has any dependent base 12362 // classes, we might find something at instantiation time: treat 12363 // this as a dependent elaborated-type-specifier. 12364 // But this only makes any sense for reference-like lookups. 12365 if (Previous.wasNotFoundInCurrentInstantiation() && 12366 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12367 IsDependent = true; 12368 return nullptr; 12369 } 12370 12371 // A tag 'foo::bar' must already exist. 12372 Diag(NameLoc, diag::err_not_tag_in_scope) 12373 << Kind << Name << DC << SS.getRange(); 12374 Name = nullptr; 12375 Invalid = true; 12376 goto CreateNewDecl; 12377 } 12378 } else if (Name) { 12379 // C++14 [class.mem]p14: 12380 // If T is the name of a class, then each of the following shall have a 12381 // name different from T: 12382 // -- every member of class T that is itself a type 12383 if (TUK != TUK_Reference && TUK != TUK_Friend && 12384 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 12385 return nullptr; 12386 12387 // If this is a named struct, check to see if there was a previous forward 12388 // declaration or definition. 12389 // FIXME: We're looking into outer scopes here, even when we 12390 // shouldn't be. Doing so can result in ambiguities that we 12391 // shouldn't be diagnosing. 12392 LookupName(Previous, S); 12393 12394 // When declaring or defining a tag, ignore ambiguities introduced 12395 // by types using'ed into this scope. 12396 if (Previous.isAmbiguous() && 12397 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 12398 LookupResult::Filter F = Previous.makeFilter(); 12399 while (F.hasNext()) { 12400 NamedDecl *ND = F.next(); 12401 if (!ND->getDeclContext()->getRedeclContext()->Equals( 12402 SearchDC->getRedeclContext())) 12403 F.erase(); 12404 } 12405 F.done(); 12406 } 12407 12408 // C++11 [namespace.memdef]p3: 12409 // If the name in a friend declaration is neither qualified nor 12410 // a template-id and the declaration is a function or an 12411 // elaborated-type-specifier, the lookup to determine whether 12412 // the entity has been previously declared shall not consider 12413 // any scopes outside the innermost enclosing namespace. 12414 // 12415 // MSVC doesn't implement the above rule for types, so a friend tag 12416 // declaration may be a redeclaration of a type declared in an enclosing 12417 // scope. They do implement this rule for friend functions. 12418 // 12419 // Does it matter that this should be by scope instead of by 12420 // semantic context? 12421 if (!Previous.empty() && TUK == TUK_Friend) { 12422 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 12423 LookupResult::Filter F = Previous.makeFilter(); 12424 bool FriendSawTagOutsideEnclosingNamespace = false; 12425 while (F.hasNext()) { 12426 NamedDecl *ND = F.next(); 12427 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12428 if (DC->isFileContext() && 12429 !EnclosingNS->Encloses(ND->getDeclContext())) { 12430 if (getLangOpts().MSVCCompat) 12431 FriendSawTagOutsideEnclosingNamespace = true; 12432 else 12433 F.erase(); 12434 } 12435 } 12436 F.done(); 12437 12438 // Diagnose this MSVC extension in the easy case where lookup would have 12439 // unambiguously found something outside the enclosing namespace. 12440 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 12441 NamedDecl *ND = Previous.getFoundDecl(); 12442 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 12443 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 12444 } 12445 } 12446 12447 // Note: there used to be some attempt at recovery here. 12448 if (Previous.isAmbiguous()) 12449 return nullptr; 12450 12451 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 12452 // FIXME: This makes sure that we ignore the contexts associated 12453 // with C structs, unions, and enums when looking for a matching 12454 // tag declaration or definition. See the similar lookup tweak 12455 // in Sema::LookupName; is there a better way to deal with this? 12456 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 12457 SearchDC = SearchDC->getParent(); 12458 } 12459 } 12460 12461 if (Previous.isSingleResult() && 12462 Previous.getFoundDecl()->isTemplateParameter()) { 12463 // Maybe we will complain about the shadowed template parameter. 12464 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 12465 // Just pretend that we didn't see the previous declaration. 12466 Previous.clear(); 12467 } 12468 12469 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 12470 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 12471 // This is a declaration of or a reference to "std::bad_alloc". 12472 isStdBadAlloc = true; 12473 12474 if (Previous.empty() && StdBadAlloc) { 12475 // std::bad_alloc has been implicitly declared (but made invisible to 12476 // name lookup). Fill in this implicit declaration as the previous 12477 // declaration, so that the declarations get chained appropriately. 12478 Previous.addDecl(getStdBadAlloc()); 12479 } 12480 } 12481 12482 // If we didn't find a previous declaration, and this is a reference 12483 // (or friend reference), move to the correct scope. In C++, we 12484 // also need to do a redeclaration lookup there, just in case 12485 // there's a shadow friend decl. 12486 if (Name && Previous.empty() && 12487 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12488 if (Invalid) goto CreateNewDecl; 12489 assert(SS.isEmpty()); 12490 12491 if (TUK == TUK_Reference) { 12492 // C++ [basic.scope.pdecl]p5: 12493 // -- for an elaborated-type-specifier of the form 12494 // 12495 // class-key identifier 12496 // 12497 // if the elaborated-type-specifier is used in the 12498 // decl-specifier-seq or parameter-declaration-clause of a 12499 // function defined in namespace scope, the identifier is 12500 // declared as a class-name in the namespace that contains 12501 // the declaration; otherwise, except as a friend 12502 // declaration, the identifier is declared in the smallest 12503 // non-class, non-function-prototype scope that contains the 12504 // declaration. 12505 // 12506 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 12507 // C structs and unions. 12508 // 12509 // It is an error in C++ to declare (rather than define) an enum 12510 // type, including via an elaborated type specifier. We'll 12511 // diagnose that later; for now, declare the enum in the same 12512 // scope as we would have picked for any other tag type. 12513 // 12514 // GNU C also supports this behavior as part of its incomplete 12515 // enum types extension, while GNU C++ does not. 12516 // 12517 // Find the context where we'll be declaring the tag. 12518 // FIXME: We would like to maintain the current DeclContext as the 12519 // lexical context, 12520 SearchDC = getTagInjectionContext(SearchDC); 12521 12522 // Find the scope where we'll be declaring the tag. 12523 S = getTagInjectionScope(S, getLangOpts()); 12524 } else { 12525 assert(TUK == TUK_Friend); 12526 // C++ [namespace.memdef]p3: 12527 // If a friend declaration in a non-local class first declares a 12528 // class or function, the friend class or function is a member of 12529 // the innermost enclosing namespace. 12530 SearchDC = SearchDC->getEnclosingNamespaceContext(); 12531 } 12532 12533 // In C++, we need to do a redeclaration lookup to properly 12534 // diagnose some problems. 12535 // FIXME: redeclaration lookup is also used (with and without C++) to find a 12536 // hidden declaration so that we don't get ambiguity errors when using a 12537 // type declared by an elaborated-type-specifier. In C that is not correct 12538 // and we should instead merge compatible types found by lookup. 12539 if (getLangOpts().CPlusPlus) { 12540 Previous.setRedeclarationKind(ForRedeclaration); 12541 LookupQualifiedName(Previous, SearchDC); 12542 } else { 12543 Previous.setRedeclarationKind(ForRedeclaration); 12544 LookupName(Previous, S); 12545 } 12546 } 12547 12548 // If we have a known previous declaration to use, then use it. 12549 if (Previous.empty() && SkipBody && SkipBody->Previous) 12550 Previous.addDecl(SkipBody->Previous); 12551 12552 if (!Previous.empty()) { 12553 NamedDecl *PrevDecl = Previous.getFoundDecl(); 12554 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 12555 12556 // It's okay to have a tag decl in the same scope as a typedef 12557 // which hides a tag decl in the same scope. Finding this 12558 // insanity with a redeclaration lookup can only actually happen 12559 // in C++. 12560 // 12561 // This is also okay for elaborated-type-specifiers, which is 12562 // technically forbidden by the current standard but which is 12563 // okay according to the likely resolution of an open issue; 12564 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 12565 if (getLangOpts().CPlusPlus) { 12566 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12567 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 12568 TagDecl *Tag = TT->getDecl(); 12569 if (Tag->getDeclName() == Name && 12570 Tag->getDeclContext()->getRedeclContext() 12571 ->Equals(TD->getDeclContext()->getRedeclContext())) { 12572 PrevDecl = Tag; 12573 Previous.clear(); 12574 Previous.addDecl(Tag); 12575 Previous.resolveKind(); 12576 } 12577 } 12578 } 12579 } 12580 12581 // If this is a redeclaration of a using shadow declaration, it must 12582 // declare a tag in the same context. In MSVC mode, we allow a 12583 // redefinition if either context is within the other. 12584 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 12585 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 12586 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 12587 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 12588 !(OldTag && isAcceptableTagRedeclContext( 12589 *this, OldTag->getDeclContext(), SearchDC))) { 12590 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 12591 Diag(Shadow->getTargetDecl()->getLocation(), 12592 diag::note_using_decl_target); 12593 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 12594 << 0; 12595 // Recover by ignoring the old declaration. 12596 Previous.clear(); 12597 goto CreateNewDecl; 12598 } 12599 } 12600 12601 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 12602 // If this is a use of a previous tag, or if the tag is already declared 12603 // in the same scope (so that the definition/declaration completes or 12604 // rementions the tag), reuse the decl. 12605 if (TUK == TUK_Reference || TUK == TUK_Friend || 12606 isDeclInScope(DirectPrevDecl, SearchDC, S, 12607 SS.isNotEmpty() || isExplicitSpecialization)) { 12608 // Make sure that this wasn't declared as an enum and now used as a 12609 // struct or something similar. 12610 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 12611 TUK == TUK_Definition, KWLoc, 12612 Name)) { 12613 bool SafeToContinue 12614 = (PrevTagDecl->getTagKind() != TTK_Enum && 12615 Kind != TTK_Enum); 12616 if (SafeToContinue) 12617 Diag(KWLoc, diag::err_use_with_wrong_tag) 12618 << Name 12619 << FixItHint::CreateReplacement(SourceRange(KWLoc), 12620 PrevTagDecl->getKindName()); 12621 else 12622 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 12623 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 12624 12625 if (SafeToContinue) 12626 Kind = PrevTagDecl->getTagKind(); 12627 else { 12628 // Recover by making this an anonymous redefinition. 12629 Name = nullptr; 12630 Previous.clear(); 12631 Invalid = true; 12632 } 12633 } 12634 12635 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 12636 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 12637 12638 // If this is an elaborated-type-specifier for a scoped enumeration, 12639 // the 'class' keyword is not necessary and not permitted. 12640 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12641 if (ScopedEnum) 12642 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 12643 << PrevEnum->isScoped() 12644 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 12645 return PrevTagDecl; 12646 } 12647 12648 QualType EnumUnderlyingTy; 12649 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12650 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 12651 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 12652 EnumUnderlyingTy = QualType(T, 0); 12653 12654 // All conflicts with previous declarations are recovered by 12655 // returning the previous declaration, unless this is a definition, 12656 // in which case we want the caller to bail out. 12657 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 12658 ScopedEnum, EnumUnderlyingTy, 12659 EnumUnderlyingIsImplicit, PrevEnum)) 12660 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 12661 } 12662 12663 // C++11 [class.mem]p1: 12664 // A member shall not be declared twice in the member-specification, 12665 // except that a nested class or member class template can be declared 12666 // and then later defined. 12667 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 12668 S->isDeclScope(PrevDecl)) { 12669 Diag(NameLoc, diag::ext_member_redeclared); 12670 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 12671 } 12672 12673 if (!Invalid) { 12674 // If this is a use, just return the declaration we found, unless 12675 // we have attributes. 12676 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12677 if (Attr) { 12678 // FIXME: Diagnose these attributes. For now, we create a new 12679 // declaration to hold them. 12680 } else if (TUK == TUK_Reference && 12681 (PrevTagDecl->getFriendObjectKind() == 12682 Decl::FOK_Undeclared || 12683 PP.getModuleContainingLocation( 12684 PrevDecl->getLocation()) != 12685 PP.getModuleContainingLocation(KWLoc)) && 12686 SS.isEmpty()) { 12687 // This declaration is a reference to an existing entity, but 12688 // has different visibility from that entity: it either makes 12689 // a friend visible or it makes a type visible in a new module. 12690 // In either case, create a new declaration. We only do this if 12691 // the declaration would have meant the same thing if no prior 12692 // declaration were found, that is, if it was found in the same 12693 // scope where we would have injected a declaration. 12694 if (!getTagInjectionContext(CurContext)->getRedeclContext() 12695 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 12696 return PrevTagDecl; 12697 // This is in the injected scope, create a new declaration in 12698 // that scope. 12699 S = getTagInjectionScope(S, getLangOpts()); 12700 } else { 12701 return PrevTagDecl; 12702 } 12703 } 12704 12705 // Diagnose attempts to redefine a tag. 12706 if (TUK == TUK_Definition) { 12707 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 12708 // If we're defining a specialization and the previous definition 12709 // is from an implicit instantiation, don't emit an error 12710 // here; we'll catch this in the general case below. 12711 bool IsExplicitSpecializationAfterInstantiation = false; 12712 if (isExplicitSpecialization) { 12713 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 12714 IsExplicitSpecializationAfterInstantiation = 12715 RD->getTemplateSpecializationKind() != 12716 TSK_ExplicitSpecialization; 12717 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 12718 IsExplicitSpecializationAfterInstantiation = 12719 ED->getTemplateSpecializationKind() != 12720 TSK_ExplicitSpecialization; 12721 } 12722 12723 NamedDecl *Hidden = nullptr; 12724 if (SkipBody && getLangOpts().CPlusPlus && 12725 !hasVisibleDefinition(Def, &Hidden)) { 12726 // There is a definition of this tag, but it is not visible. We 12727 // explicitly make use of C++'s one definition rule here, and 12728 // assume that this definition is identical to the hidden one 12729 // we already have. Make the existing definition visible and 12730 // use it in place of this one. 12731 SkipBody->ShouldSkip = true; 12732 makeMergedDefinitionVisible(Hidden, KWLoc); 12733 return Def; 12734 } else if (!IsExplicitSpecializationAfterInstantiation) { 12735 // A redeclaration in function prototype scope in C isn't 12736 // visible elsewhere, so merely issue a warning. 12737 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 12738 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 12739 else 12740 Diag(NameLoc, diag::err_redefinition) << Name; 12741 Diag(Def->getLocation(), diag::note_previous_definition); 12742 // If this is a redefinition, recover by making this 12743 // struct be anonymous, which will make any later 12744 // references get the previous definition. 12745 Name = nullptr; 12746 Previous.clear(); 12747 Invalid = true; 12748 } 12749 } else { 12750 // If the type is currently being defined, complain 12751 // about a nested redefinition. 12752 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 12753 if (TD->isBeingDefined()) { 12754 Diag(NameLoc, diag::err_nested_redefinition) << Name; 12755 Diag(PrevTagDecl->getLocation(), 12756 diag::note_previous_definition); 12757 Name = nullptr; 12758 Previous.clear(); 12759 Invalid = true; 12760 } 12761 } 12762 12763 // Okay, this is definition of a previously declared or referenced 12764 // tag. We're going to create a new Decl for it. 12765 } 12766 12767 // Okay, we're going to make a redeclaration. If this is some kind 12768 // of reference, make sure we build the redeclaration in the same DC 12769 // as the original, and ignore the current access specifier. 12770 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12771 SearchDC = PrevTagDecl->getDeclContext(); 12772 AS = AS_none; 12773 } 12774 } 12775 // If we get here we have (another) forward declaration or we 12776 // have a definition. Just create a new decl. 12777 12778 } else { 12779 // If we get here, this is a definition of a new tag type in a nested 12780 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 12781 // new decl/type. We set PrevDecl to NULL so that the entities 12782 // have distinct types. 12783 Previous.clear(); 12784 } 12785 // If we get here, we're going to create a new Decl. If PrevDecl 12786 // is non-NULL, it's a definition of the tag declared by 12787 // PrevDecl. If it's NULL, we have a new definition. 12788 12789 // Otherwise, PrevDecl is not a tag, but was found with tag 12790 // lookup. This is only actually possible in C++, where a few 12791 // things like templates still live in the tag namespace. 12792 } else { 12793 // Use a better diagnostic if an elaborated-type-specifier 12794 // found the wrong kind of type on the first 12795 // (non-redeclaration) lookup. 12796 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 12797 !Previous.isForRedeclaration()) { 12798 unsigned Kind = 0; 12799 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 12800 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 12801 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 12802 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 12803 Diag(PrevDecl->getLocation(), diag::note_declared_at); 12804 Invalid = true; 12805 12806 // Otherwise, only diagnose if the declaration is in scope. 12807 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 12808 SS.isNotEmpty() || isExplicitSpecialization)) { 12809 // do nothing 12810 12811 // Diagnose implicit declarations introduced by elaborated types. 12812 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 12813 unsigned Kind = 0; 12814 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 12815 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 12816 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 12817 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 12818 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 12819 Invalid = true; 12820 12821 // Otherwise it's a declaration. Call out a particularly common 12822 // case here. 12823 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12824 unsigned Kind = 0; 12825 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 12826 Diag(NameLoc, diag::err_tag_definition_of_typedef) 12827 << Name << Kind << TND->getUnderlyingType(); 12828 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 12829 Invalid = true; 12830 12831 // Otherwise, diagnose. 12832 } else { 12833 // The tag name clashes with something else in the target scope, 12834 // issue an error and recover by making this tag be anonymous. 12835 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 12836 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12837 Name = nullptr; 12838 Invalid = true; 12839 } 12840 12841 // The existing declaration isn't relevant to us; we're in a 12842 // new scope, so clear out the previous declaration. 12843 Previous.clear(); 12844 } 12845 } 12846 12847 CreateNewDecl: 12848 12849 TagDecl *PrevDecl = nullptr; 12850 if (Previous.isSingleResult()) 12851 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 12852 12853 // If there is an identifier, use the location of the identifier as the 12854 // location of the decl, otherwise use the location of the struct/union 12855 // keyword. 12856 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 12857 12858 // Otherwise, create a new declaration. If there is a previous 12859 // declaration of the same entity, the two will be linked via 12860 // PrevDecl. 12861 TagDecl *New; 12862 12863 bool IsForwardReference = false; 12864 if (Kind == TTK_Enum) { 12865 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 12866 // enum X { A, B, C } D; D should chain to X. 12867 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 12868 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 12869 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 12870 // If this is an undefined enum, warn. 12871 if (TUK != TUK_Definition && !Invalid) { 12872 TagDecl *Def; 12873 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 12874 cast<EnumDecl>(New)->isFixed()) { 12875 // C++0x: 7.2p2: opaque-enum-declaration. 12876 // Conflicts are diagnosed above. Do nothing. 12877 } 12878 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 12879 Diag(Loc, diag::ext_forward_ref_enum_def) 12880 << New; 12881 Diag(Def->getLocation(), diag::note_previous_definition); 12882 } else { 12883 unsigned DiagID = diag::ext_forward_ref_enum; 12884 if (getLangOpts().MSVCCompat) 12885 DiagID = diag::ext_ms_forward_ref_enum; 12886 else if (getLangOpts().CPlusPlus) 12887 DiagID = diag::err_forward_ref_enum; 12888 Diag(Loc, DiagID); 12889 12890 // If this is a forward-declared reference to an enumeration, make a 12891 // note of it; we won't actually be introducing the declaration into 12892 // the declaration context. 12893 if (TUK == TUK_Reference) 12894 IsForwardReference = true; 12895 } 12896 } 12897 12898 if (EnumUnderlying) { 12899 EnumDecl *ED = cast<EnumDecl>(New); 12900 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12901 ED->setIntegerTypeSourceInfo(TI); 12902 else 12903 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 12904 ED->setPromotionType(ED->getIntegerType()); 12905 } 12906 } else { 12907 // struct/union/class 12908 12909 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 12910 // struct X { int A; } D; D should chain to X. 12911 if (getLangOpts().CPlusPlus) { 12912 // FIXME: Look for a way to use RecordDecl for simple structs. 12913 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12914 cast_or_null<CXXRecordDecl>(PrevDecl)); 12915 12916 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 12917 StdBadAlloc = cast<CXXRecordDecl>(New); 12918 } else 12919 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12920 cast_or_null<RecordDecl>(PrevDecl)); 12921 } 12922 12923 // C++11 [dcl.type]p3: 12924 // A type-specifier-seq shall not define a class or enumeration [...]. 12925 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 12926 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 12927 << Context.getTagDeclType(New); 12928 Invalid = true; 12929 } 12930 12931 // Maybe add qualifier info. 12932 if (SS.isNotEmpty()) { 12933 if (SS.isSet()) { 12934 // If this is either a declaration or a definition, check the 12935 // nested-name-specifier against the current context. We don't do this 12936 // for explicit specializations, because they have similar checking 12937 // (with more specific diagnostics) in the call to 12938 // CheckMemberSpecialization, below. 12939 if (!isExplicitSpecialization && 12940 (TUK == TUK_Definition || TUK == TUK_Declaration) && 12941 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 12942 Invalid = true; 12943 12944 New->setQualifierInfo(SS.getWithLocInContext(Context)); 12945 if (TemplateParameterLists.size() > 0) { 12946 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 12947 } 12948 } 12949 else 12950 Invalid = true; 12951 } 12952 12953 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 12954 // Add alignment attributes if necessary; these attributes are checked when 12955 // the ASTContext lays out the structure. 12956 // 12957 // It is important for implementing the correct semantics that this 12958 // happen here (in act on tag decl). The #pragma pack stack is 12959 // maintained as a result of parser callbacks which can occur at 12960 // many points during the parsing of a struct declaration (because 12961 // the #pragma tokens are effectively skipped over during the 12962 // parsing of the struct). 12963 if (TUK == TUK_Definition) { 12964 AddAlignmentAttributesForRecord(RD); 12965 AddMsStructLayoutForRecord(RD); 12966 } 12967 } 12968 12969 if (ModulePrivateLoc.isValid()) { 12970 if (isExplicitSpecialization) 12971 Diag(New->getLocation(), diag::err_module_private_specialization) 12972 << 2 12973 << FixItHint::CreateRemoval(ModulePrivateLoc); 12974 // __module_private__ does not apply to local classes. However, we only 12975 // diagnose this as an error when the declaration specifiers are 12976 // freestanding. Here, we just ignore the __module_private__. 12977 else if (!SearchDC->isFunctionOrMethod()) 12978 New->setModulePrivate(); 12979 } 12980 12981 // If this is a specialization of a member class (of a class template), 12982 // check the specialization. 12983 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 12984 Invalid = true; 12985 12986 // If we're declaring or defining a tag in function prototype scope in C, 12987 // note that this type can only be used within the function and add it to 12988 // the list of decls to inject into the function definition scope. 12989 if ((Name || Kind == TTK_Enum) && 12990 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 12991 if (getLangOpts().CPlusPlus) { 12992 // C++ [dcl.fct]p6: 12993 // Types shall not be defined in return or parameter types. 12994 if (TUK == TUK_Definition && !IsTypeSpecifier) { 12995 Diag(Loc, diag::err_type_defined_in_param_type) 12996 << Name; 12997 Invalid = true; 12998 } 12999 } else if (!PrevDecl) { 13000 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13001 } 13002 DeclsInPrototypeScope.push_back(New); 13003 } 13004 13005 if (Invalid) 13006 New->setInvalidDecl(); 13007 13008 if (Attr) 13009 ProcessDeclAttributeList(S, New, Attr); 13010 13011 // Set the lexical context. If the tag has a C++ scope specifier, the 13012 // lexical context will be different from the semantic context. 13013 New->setLexicalDeclContext(CurContext); 13014 13015 // Mark this as a friend decl if applicable. 13016 // In Microsoft mode, a friend declaration also acts as a forward 13017 // declaration so we always pass true to setObjectOfFriendDecl to make 13018 // the tag name visible. 13019 if (TUK == TUK_Friend) 13020 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13021 13022 // Set the access specifier. 13023 if (!Invalid && SearchDC->isRecord()) 13024 SetMemberAccessSpecifier(New, PrevDecl, AS); 13025 13026 if (TUK == TUK_Definition) 13027 New->startDefinition(); 13028 13029 // If this has an identifier, add it to the scope stack. 13030 if (TUK == TUK_Friend) { 13031 // We might be replacing an existing declaration in the lookup tables; 13032 // if so, borrow its access specifier. 13033 if (PrevDecl) 13034 New->setAccess(PrevDecl->getAccess()); 13035 13036 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13037 DC->makeDeclVisibleInContext(New); 13038 if (Name) // can be null along some error paths 13039 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13040 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13041 } else if (Name) { 13042 S = getNonFieldDeclScope(S); 13043 PushOnScopeChains(New, S, !IsForwardReference); 13044 if (IsForwardReference) 13045 SearchDC->makeDeclVisibleInContext(New); 13046 } else { 13047 CurContext->addDecl(New); 13048 } 13049 13050 // If this is the C FILE type, notify the AST context. 13051 if (IdentifierInfo *II = New->getIdentifier()) 13052 if (!New->isInvalidDecl() && 13053 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13054 II->isStr("FILE")) 13055 Context.setFILEDecl(New); 13056 13057 if (PrevDecl) 13058 mergeDeclAttributes(New, PrevDecl); 13059 13060 // If there's a #pragma GCC visibility in scope, set the visibility of this 13061 // record. 13062 AddPushedVisibilityAttribute(New); 13063 13064 OwnedDecl = true; 13065 // In C++, don't return an invalid declaration. We can't recover well from 13066 // the cases where we make the type anonymous. 13067 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 13068 } 13069 13070 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13071 AdjustDeclIfTemplate(TagD); 13072 TagDecl *Tag = cast<TagDecl>(TagD); 13073 13074 // Enter the tag context. 13075 PushDeclContext(S, Tag); 13076 13077 ActOnDocumentableDecl(TagD); 13078 13079 // If there's a #pragma GCC visibility in scope, set the visibility of this 13080 // record. 13081 AddPushedVisibilityAttribute(Tag); 13082 } 13083 13084 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13085 assert(isa<ObjCContainerDecl>(IDecl) && 13086 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13087 DeclContext *OCD = cast<DeclContext>(IDecl); 13088 assert(getContainingDC(OCD) == CurContext && 13089 "The next DeclContext should be lexically contained in the current one."); 13090 CurContext = OCD; 13091 return IDecl; 13092 } 13093 13094 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13095 SourceLocation FinalLoc, 13096 bool IsFinalSpelledSealed, 13097 SourceLocation LBraceLoc) { 13098 AdjustDeclIfTemplate(TagD); 13099 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13100 13101 FieldCollector->StartClass(); 13102 13103 if (!Record->getIdentifier()) 13104 return; 13105 13106 if (FinalLoc.isValid()) 13107 Record->addAttr(new (Context) 13108 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13109 13110 // C++ [class]p2: 13111 // [...] The class-name is also inserted into the scope of the 13112 // class itself; this is known as the injected-class-name. For 13113 // purposes of access checking, the injected-class-name is treated 13114 // as if it were a public member name. 13115 CXXRecordDecl *InjectedClassName 13116 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13117 Record->getLocStart(), Record->getLocation(), 13118 Record->getIdentifier(), 13119 /*PrevDecl=*/nullptr, 13120 /*DelayTypeCreation=*/true); 13121 Context.getTypeDeclType(InjectedClassName, Record); 13122 InjectedClassName->setImplicit(); 13123 InjectedClassName->setAccess(AS_public); 13124 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13125 InjectedClassName->setDescribedClassTemplate(Template); 13126 PushOnScopeChains(InjectedClassName, S); 13127 assert(InjectedClassName->isInjectedClassName() && 13128 "Broken injected-class-name"); 13129 } 13130 13131 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13132 SourceLocation RBraceLoc) { 13133 AdjustDeclIfTemplate(TagD); 13134 TagDecl *Tag = cast<TagDecl>(TagD); 13135 Tag->setRBraceLoc(RBraceLoc); 13136 13137 // Make sure we "complete" the definition even it is invalid. 13138 if (Tag->isBeingDefined()) { 13139 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13140 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13141 RD->completeDefinition(); 13142 } 13143 13144 if (isa<CXXRecordDecl>(Tag)) 13145 FieldCollector->FinishClass(); 13146 13147 // Exit this scope of this tag's definition. 13148 PopDeclContext(); 13149 13150 if (getCurLexicalContext()->isObjCContainer() && 13151 Tag->getDeclContext()->isFileContext()) 13152 Tag->setTopLevelDeclInObjCContainer(); 13153 13154 // Notify the consumer that we've defined a tag. 13155 if (!Tag->isInvalidDecl()) 13156 Consumer.HandleTagDeclDefinition(Tag); 13157 } 13158 13159 void Sema::ActOnObjCContainerFinishDefinition() { 13160 // Exit this scope of this interface definition. 13161 PopDeclContext(); 13162 } 13163 13164 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13165 assert(DC == CurContext && "Mismatch of container contexts"); 13166 OriginalLexicalContext = DC; 13167 ActOnObjCContainerFinishDefinition(); 13168 } 13169 13170 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13171 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13172 OriginalLexicalContext = nullptr; 13173 } 13174 13175 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13176 AdjustDeclIfTemplate(TagD); 13177 TagDecl *Tag = cast<TagDecl>(TagD); 13178 Tag->setInvalidDecl(); 13179 13180 // Make sure we "complete" the definition even it is invalid. 13181 if (Tag->isBeingDefined()) { 13182 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13183 RD->completeDefinition(); 13184 } 13185 13186 // We're undoing ActOnTagStartDefinition here, not 13187 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 13188 // the FieldCollector. 13189 13190 PopDeclContext(); 13191 } 13192 13193 // Note that FieldName may be null for anonymous bitfields. 13194 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 13195 IdentifierInfo *FieldName, 13196 QualType FieldTy, bool IsMsStruct, 13197 Expr *BitWidth, bool *ZeroWidth) { 13198 // Default to true; that shouldn't confuse checks for emptiness 13199 if (ZeroWidth) 13200 *ZeroWidth = true; 13201 13202 // C99 6.7.2.1p4 - verify the field type. 13203 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 13204 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 13205 // Handle incomplete types with specific error. 13206 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 13207 return ExprError(); 13208 if (FieldName) 13209 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 13210 << FieldName << FieldTy << BitWidth->getSourceRange(); 13211 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 13212 << FieldTy << BitWidth->getSourceRange(); 13213 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 13214 UPPC_BitFieldWidth)) 13215 return ExprError(); 13216 13217 // If the bit-width is type- or value-dependent, don't try to check 13218 // it now. 13219 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 13220 return BitWidth; 13221 13222 llvm::APSInt Value; 13223 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 13224 if (ICE.isInvalid()) 13225 return ICE; 13226 BitWidth = ICE.get(); 13227 13228 if (Value != 0 && ZeroWidth) 13229 *ZeroWidth = false; 13230 13231 // Zero-width bitfield is ok for anonymous field. 13232 if (Value == 0 && FieldName) 13233 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 13234 13235 if (Value.isSigned() && Value.isNegative()) { 13236 if (FieldName) 13237 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 13238 << FieldName << Value.toString(10); 13239 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 13240 << Value.toString(10); 13241 } 13242 13243 if (!FieldTy->isDependentType()) { 13244 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 13245 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 13246 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 13247 13248 // Over-wide bitfields are an error in C or when using the MSVC bitfield 13249 // ABI. 13250 bool CStdConstraintViolation = 13251 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 13252 bool MSBitfieldViolation = 13253 Value.ugt(TypeStorageSize) && 13254 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 13255 if (CStdConstraintViolation || MSBitfieldViolation) { 13256 unsigned DiagWidth = 13257 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 13258 if (FieldName) 13259 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 13260 << FieldName << (unsigned)Value.getZExtValue() 13261 << !CStdConstraintViolation << DiagWidth; 13262 13263 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 13264 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 13265 << DiagWidth; 13266 } 13267 13268 // Warn on types where the user might conceivably expect to get all 13269 // specified bits as value bits: that's all integral types other than 13270 // 'bool'. 13271 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13272 if (FieldName) 13273 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13274 << FieldName << (unsigned)Value.getZExtValue() 13275 << (unsigned)TypeWidth; 13276 else 13277 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13278 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13279 } 13280 } 13281 13282 return BitWidth; 13283 } 13284 13285 /// ActOnField - Each field of a C struct/union is passed into this in order 13286 /// to create a FieldDecl object for it. 13287 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13288 Declarator &D, Expr *BitfieldWidth) { 13289 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13290 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13291 /*InitStyle=*/ICIS_NoInit, AS_public); 13292 return Res; 13293 } 13294 13295 /// HandleField - Analyze a field of a C struct or a C++ data member. 13296 /// 13297 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13298 SourceLocation DeclStart, 13299 Declarator &D, Expr *BitWidth, 13300 InClassInitStyle InitStyle, 13301 AccessSpecifier AS) { 13302 IdentifierInfo *II = D.getIdentifier(); 13303 SourceLocation Loc = DeclStart; 13304 if (II) Loc = D.getIdentifierLoc(); 13305 13306 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13307 QualType T = TInfo->getType(); 13308 if (getLangOpts().CPlusPlus) { 13309 CheckExtraCXXDefaultArguments(D); 13310 13311 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13312 UPPC_DataMemberType)) { 13313 D.setInvalidType(); 13314 T = Context.IntTy; 13315 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13316 } 13317 } 13318 13319 // TR 18037 does not allow fields to be declared with address spaces. 13320 if (T.getQualifiers().hasAddressSpace()) { 13321 Diag(Loc, diag::err_field_with_address_space); 13322 D.setInvalidType(); 13323 } 13324 13325 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 13326 // used as structure or union field: image, sampler, event or block types. 13327 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 13328 T->isSamplerT() || T->isBlockPointerType())) { 13329 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 13330 D.setInvalidType(); 13331 } 13332 13333 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13334 13335 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13336 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13337 diag::err_invalid_thread) 13338 << DeclSpec::getSpecifierName(TSCS); 13339 13340 // Check to see if this name was declared as a member previously 13341 NamedDecl *PrevDecl = nullptr; 13342 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13343 LookupName(Previous, S); 13344 switch (Previous.getResultKind()) { 13345 case LookupResult::Found: 13346 case LookupResult::FoundUnresolvedValue: 13347 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13348 break; 13349 13350 case LookupResult::FoundOverloaded: 13351 PrevDecl = Previous.getRepresentativeDecl(); 13352 break; 13353 13354 case LookupResult::NotFound: 13355 case LookupResult::NotFoundInCurrentInstantiation: 13356 case LookupResult::Ambiguous: 13357 break; 13358 } 13359 Previous.suppressDiagnostics(); 13360 13361 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13362 // Maybe we will complain about the shadowed template parameter. 13363 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13364 // Just pretend that we didn't see the previous declaration. 13365 PrevDecl = nullptr; 13366 } 13367 13368 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13369 PrevDecl = nullptr; 13370 13371 bool Mutable 13372 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 13373 SourceLocation TSSL = D.getLocStart(); 13374 FieldDecl *NewFD 13375 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 13376 TSSL, AS, PrevDecl, &D); 13377 13378 if (NewFD->isInvalidDecl()) 13379 Record->setInvalidDecl(); 13380 13381 if (D.getDeclSpec().isModulePrivateSpecified()) 13382 NewFD->setModulePrivate(); 13383 13384 if (NewFD->isInvalidDecl() && PrevDecl) { 13385 // Don't introduce NewFD into scope; there's already something 13386 // with the same name in the same scope. 13387 } else if (II) { 13388 PushOnScopeChains(NewFD, S); 13389 } else 13390 Record->addDecl(NewFD); 13391 13392 return NewFD; 13393 } 13394 13395 /// \brief Build a new FieldDecl and check its well-formedness. 13396 /// 13397 /// This routine builds a new FieldDecl given the fields name, type, 13398 /// record, etc. \p PrevDecl should refer to any previous declaration 13399 /// with the same name and in the same scope as the field to be 13400 /// created. 13401 /// 13402 /// \returns a new FieldDecl. 13403 /// 13404 /// \todo The Declarator argument is a hack. It will be removed once 13405 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 13406 TypeSourceInfo *TInfo, 13407 RecordDecl *Record, SourceLocation Loc, 13408 bool Mutable, Expr *BitWidth, 13409 InClassInitStyle InitStyle, 13410 SourceLocation TSSL, 13411 AccessSpecifier AS, NamedDecl *PrevDecl, 13412 Declarator *D) { 13413 IdentifierInfo *II = Name.getAsIdentifierInfo(); 13414 bool InvalidDecl = false; 13415 if (D) InvalidDecl = D->isInvalidType(); 13416 13417 // If we receive a broken type, recover by assuming 'int' and 13418 // marking this declaration as invalid. 13419 if (T.isNull()) { 13420 InvalidDecl = true; 13421 T = Context.IntTy; 13422 } 13423 13424 QualType EltTy = Context.getBaseElementType(T); 13425 if (!EltTy->isDependentType()) { 13426 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 13427 // Fields of incomplete type force their record to be invalid. 13428 Record->setInvalidDecl(); 13429 InvalidDecl = true; 13430 } else { 13431 NamedDecl *Def; 13432 EltTy->isIncompleteType(&Def); 13433 if (Def && Def->isInvalidDecl()) { 13434 Record->setInvalidDecl(); 13435 InvalidDecl = true; 13436 } 13437 } 13438 } 13439 13440 // OpenCL v1.2 s6.9.c: bitfields are not supported. 13441 if (BitWidth && getLangOpts().OpenCL) { 13442 Diag(Loc, diag::err_opencl_bitfields); 13443 InvalidDecl = true; 13444 } 13445 13446 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13447 // than a variably modified type. 13448 if (!InvalidDecl && T->isVariablyModifiedType()) { 13449 bool SizeIsNegative; 13450 llvm::APSInt Oversized; 13451 13452 TypeSourceInfo *FixedTInfo = 13453 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 13454 SizeIsNegative, 13455 Oversized); 13456 if (FixedTInfo) { 13457 Diag(Loc, diag::warn_illegal_constant_array_size); 13458 TInfo = FixedTInfo; 13459 T = FixedTInfo->getType(); 13460 } else { 13461 if (SizeIsNegative) 13462 Diag(Loc, diag::err_typecheck_negative_array_size); 13463 else if (Oversized.getBoolValue()) 13464 Diag(Loc, diag::err_array_too_large) 13465 << Oversized.toString(10); 13466 else 13467 Diag(Loc, diag::err_typecheck_field_variable_size); 13468 InvalidDecl = true; 13469 } 13470 } 13471 13472 // Fields can not have abstract class types 13473 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 13474 diag::err_abstract_type_in_decl, 13475 AbstractFieldType)) 13476 InvalidDecl = true; 13477 13478 bool ZeroWidth = false; 13479 if (InvalidDecl) 13480 BitWidth = nullptr; 13481 // If this is declared as a bit-field, check the bit-field. 13482 if (BitWidth) { 13483 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 13484 &ZeroWidth).get(); 13485 if (!BitWidth) { 13486 InvalidDecl = true; 13487 BitWidth = nullptr; 13488 ZeroWidth = false; 13489 } 13490 } 13491 13492 // Check that 'mutable' is consistent with the type of the declaration. 13493 if (!InvalidDecl && Mutable) { 13494 unsigned DiagID = 0; 13495 if (T->isReferenceType()) 13496 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 13497 : diag::err_mutable_reference; 13498 else if (T.isConstQualified()) 13499 DiagID = diag::err_mutable_const; 13500 13501 if (DiagID) { 13502 SourceLocation ErrLoc = Loc; 13503 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 13504 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 13505 Diag(ErrLoc, DiagID); 13506 if (DiagID != diag::ext_mutable_reference) { 13507 Mutable = false; 13508 InvalidDecl = true; 13509 } 13510 } 13511 } 13512 13513 // C++11 [class.union]p8 (DR1460): 13514 // At most one variant member of a union may have a 13515 // brace-or-equal-initializer. 13516 if (InitStyle != ICIS_NoInit) 13517 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 13518 13519 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 13520 BitWidth, Mutable, InitStyle); 13521 if (InvalidDecl) 13522 NewFD->setInvalidDecl(); 13523 13524 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 13525 Diag(Loc, diag::err_duplicate_member) << II; 13526 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13527 NewFD->setInvalidDecl(); 13528 } 13529 13530 if (!InvalidDecl && getLangOpts().CPlusPlus) { 13531 if (Record->isUnion()) { 13532 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13533 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13534 if (RDecl->getDefinition()) { 13535 // C++ [class.union]p1: An object of a class with a non-trivial 13536 // constructor, a non-trivial copy constructor, a non-trivial 13537 // destructor, or a non-trivial copy assignment operator 13538 // cannot be a member of a union, nor can an array of such 13539 // objects. 13540 if (CheckNontrivialField(NewFD)) 13541 NewFD->setInvalidDecl(); 13542 } 13543 } 13544 13545 // C++ [class.union]p1: If a union contains a member of reference type, 13546 // the program is ill-formed, except when compiling with MSVC extensions 13547 // enabled. 13548 if (EltTy->isReferenceType()) { 13549 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 13550 diag::ext_union_member_of_reference_type : 13551 diag::err_union_member_of_reference_type) 13552 << NewFD->getDeclName() << EltTy; 13553 if (!getLangOpts().MicrosoftExt) 13554 NewFD->setInvalidDecl(); 13555 } 13556 } 13557 } 13558 13559 // FIXME: We need to pass in the attributes given an AST 13560 // representation, not a parser representation. 13561 if (D) { 13562 // FIXME: The current scope is almost... but not entirely... correct here. 13563 ProcessDeclAttributes(getCurScope(), NewFD, *D); 13564 13565 if (NewFD->hasAttrs()) 13566 CheckAlignasUnderalignment(NewFD); 13567 } 13568 13569 // In auto-retain/release, infer strong retension for fields of 13570 // retainable type. 13571 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 13572 NewFD->setInvalidDecl(); 13573 13574 if (T.isObjCGCWeak()) 13575 Diag(Loc, diag::warn_attribute_weak_on_field); 13576 13577 NewFD->setAccess(AS); 13578 return NewFD; 13579 } 13580 13581 bool Sema::CheckNontrivialField(FieldDecl *FD) { 13582 assert(FD); 13583 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 13584 13585 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 13586 return false; 13587 13588 QualType EltTy = Context.getBaseElementType(FD->getType()); 13589 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13590 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13591 if (RDecl->getDefinition()) { 13592 // We check for copy constructors before constructors 13593 // because otherwise we'll never get complaints about 13594 // copy constructors. 13595 13596 CXXSpecialMember member = CXXInvalid; 13597 // We're required to check for any non-trivial constructors. Since the 13598 // implicit default constructor is suppressed if there are any 13599 // user-declared constructors, we just need to check that there is a 13600 // trivial default constructor and a trivial copy constructor. (We don't 13601 // worry about move constructors here, since this is a C++98 check.) 13602 if (RDecl->hasNonTrivialCopyConstructor()) 13603 member = CXXCopyConstructor; 13604 else if (!RDecl->hasTrivialDefaultConstructor()) 13605 member = CXXDefaultConstructor; 13606 else if (RDecl->hasNonTrivialCopyAssignment()) 13607 member = CXXCopyAssignment; 13608 else if (RDecl->hasNonTrivialDestructor()) 13609 member = CXXDestructor; 13610 13611 if (member != CXXInvalid) { 13612 if (!getLangOpts().CPlusPlus11 && 13613 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 13614 // Objective-C++ ARC: it is an error to have a non-trivial field of 13615 // a union. However, system headers in Objective-C programs 13616 // occasionally have Objective-C lifetime objects within unions, 13617 // and rather than cause the program to fail, we make those 13618 // members unavailable. 13619 SourceLocation Loc = FD->getLocation(); 13620 if (getSourceManager().isInSystemHeader(Loc)) { 13621 if (!FD->hasAttr<UnavailableAttr>()) 13622 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13623 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 13624 return false; 13625 } 13626 } 13627 13628 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 13629 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 13630 diag::err_illegal_union_or_anon_struct_member) 13631 << FD->getParent()->isUnion() << FD->getDeclName() << member; 13632 DiagnoseNontrivial(RDecl, member); 13633 return !getLangOpts().CPlusPlus11; 13634 } 13635 } 13636 } 13637 13638 return false; 13639 } 13640 13641 /// TranslateIvarVisibility - Translate visibility from a token ID to an 13642 /// AST enum value. 13643 static ObjCIvarDecl::AccessControl 13644 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 13645 switch (ivarVisibility) { 13646 default: llvm_unreachable("Unknown visitibility kind"); 13647 case tok::objc_private: return ObjCIvarDecl::Private; 13648 case tok::objc_public: return ObjCIvarDecl::Public; 13649 case tok::objc_protected: return ObjCIvarDecl::Protected; 13650 case tok::objc_package: return ObjCIvarDecl::Package; 13651 } 13652 } 13653 13654 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 13655 /// in order to create an IvarDecl object for it. 13656 Decl *Sema::ActOnIvar(Scope *S, 13657 SourceLocation DeclStart, 13658 Declarator &D, Expr *BitfieldWidth, 13659 tok::ObjCKeywordKind Visibility) { 13660 13661 IdentifierInfo *II = D.getIdentifier(); 13662 Expr *BitWidth = (Expr*)BitfieldWidth; 13663 SourceLocation Loc = DeclStart; 13664 if (II) Loc = D.getIdentifierLoc(); 13665 13666 // FIXME: Unnamed fields can be handled in various different ways, for 13667 // example, unnamed unions inject all members into the struct namespace! 13668 13669 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13670 QualType T = TInfo->getType(); 13671 13672 if (BitWidth) { 13673 // 6.7.2.1p3, 6.7.2.1p4 13674 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 13675 if (!BitWidth) 13676 D.setInvalidType(); 13677 } else { 13678 // Not a bitfield. 13679 13680 // validate II. 13681 13682 } 13683 if (T->isReferenceType()) { 13684 Diag(Loc, diag::err_ivar_reference_type); 13685 D.setInvalidType(); 13686 } 13687 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13688 // than a variably modified type. 13689 else if (T->isVariablyModifiedType()) { 13690 Diag(Loc, diag::err_typecheck_ivar_variable_size); 13691 D.setInvalidType(); 13692 } 13693 13694 // Get the visibility (access control) for this ivar. 13695 ObjCIvarDecl::AccessControl ac = 13696 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 13697 : ObjCIvarDecl::None; 13698 // Must set ivar's DeclContext to its enclosing interface. 13699 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 13700 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 13701 return nullptr; 13702 ObjCContainerDecl *EnclosingContext; 13703 if (ObjCImplementationDecl *IMPDecl = 13704 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13705 if (LangOpts.ObjCRuntime.isFragile()) { 13706 // Case of ivar declared in an implementation. Context is that of its class. 13707 EnclosingContext = IMPDecl->getClassInterface(); 13708 assert(EnclosingContext && "Implementation has no class interface!"); 13709 } 13710 else 13711 EnclosingContext = EnclosingDecl; 13712 } else { 13713 if (ObjCCategoryDecl *CDecl = 13714 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13715 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 13716 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 13717 return nullptr; 13718 } 13719 } 13720 EnclosingContext = EnclosingDecl; 13721 } 13722 13723 // Construct the decl. 13724 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 13725 DeclStart, Loc, II, T, 13726 TInfo, ac, (Expr *)BitfieldWidth); 13727 13728 if (II) { 13729 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 13730 ForRedeclaration); 13731 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 13732 && !isa<TagDecl>(PrevDecl)) { 13733 Diag(Loc, diag::err_duplicate_member) << II; 13734 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13735 NewID->setInvalidDecl(); 13736 } 13737 } 13738 13739 // Process attributes attached to the ivar. 13740 ProcessDeclAttributes(S, NewID, D); 13741 13742 if (D.isInvalidType()) 13743 NewID->setInvalidDecl(); 13744 13745 // In ARC, infer 'retaining' for ivars of retainable type. 13746 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 13747 NewID->setInvalidDecl(); 13748 13749 if (D.getDeclSpec().isModulePrivateSpecified()) 13750 NewID->setModulePrivate(); 13751 13752 if (II) { 13753 // FIXME: When interfaces are DeclContexts, we'll need to add 13754 // these to the interface. 13755 S->AddDecl(NewID); 13756 IdResolver.AddDecl(NewID); 13757 } 13758 13759 if (LangOpts.ObjCRuntime.isNonFragile() && 13760 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 13761 Diag(Loc, diag::warn_ivars_in_interface); 13762 13763 return NewID; 13764 } 13765 13766 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 13767 /// class and class extensions. For every class \@interface and class 13768 /// extension \@interface, if the last ivar is a bitfield of any type, 13769 /// then add an implicit `char :0` ivar to the end of that interface. 13770 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 13771 SmallVectorImpl<Decl *> &AllIvarDecls) { 13772 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 13773 return; 13774 13775 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 13776 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 13777 13778 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 13779 return; 13780 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 13781 if (!ID) { 13782 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 13783 if (!CD->IsClassExtension()) 13784 return; 13785 } 13786 // No need to add this to end of @implementation. 13787 else 13788 return; 13789 } 13790 // All conditions are met. Add a new bitfield to the tail end of ivars. 13791 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 13792 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 13793 13794 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 13795 DeclLoc, DeclLoc, nullptr, 13796 Context.CharTy, 13797 Context.getTrivialTypeSourceInfo(Context.CharTy, 13798 DeclLoc), 13799 ObjCIvarDecl::Private, BW, 13800 true); 13801 AllIvarDecls.push_back(Ivar); 13802 } 13803 13804 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 13805 ArrayRef<Decl *> Fields, SourceLocation LBrac, 13806 SourceLocation RBrac, AttributeList *Attr) { 13807 assert(EnclosingDecl && "missing record or interface decl"); 13808 13809 // If this is an Objective-C @implementation or category and we have 13810 // new fields here we should reset the layout of the interface since 13811 // it will now change. 13812 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 13813 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 13814 switch (DC->getKind()) { 13815 default: break; 13816 case Decl::ObjCCategory: 13817 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 13818 break; 13819 case Decl::ObjCImplementation: 13820 Context. 13821 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 13822 break; 13823 } 13824 } 13825 13826 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 13827 13828 // Start counting up the number of named members; make sure to include 13829 // members of anonymous structs and unions in the total. 13830 unsigned NumNamedMembers = 0; 13831 if (Record) { 13832 for (const auto *I : Record->decls()) { 13833 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 13834 if (IFD->getDeclName()) 13835 ++NumNamedMembers; 13836 } 13837 } 13838 13839 // Verify that all the fields are okay. 13840 SmallVector<FieldDecl*, 32> RecFields; 13841 13842 bool ARCErrReported = false; 13843 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 13844 i != end; ++i) { 13845 FieldDecl *FD = cast<FieldDecl>(*i); 13846 13847 // Get the type for the field. 13848 const Type *FDTy = FD->getType().getTypePtr(); 13849 13850 if (!FD->isAnonymousStructOrUnion()) { 13851 // Remember all fields written by the user. 13852 RecFields.push_back(FD); 13853 } 13854 13855 // If the field is already invalid for some reason, don't emit more 13856 // diagnostics about it. 13857 if (FD->isInvalidDecl()) { 13858 EnclosingDecl->setInvalidDecl(); 13859 continue; 13860 } 13861 13862 // C99 6.7.2.1p2: 13863 // A structure or union shall not contain a member with 13864 // incomplete or function type (hence, a structure shall not 13865 // contain an instance of itself, but may contain a pointer to 13866 // an instance of itself), except that the last member of a 13867 // structure with more than one named member may have incomplete 13868 // array type; such a structure (and any union containing, 13869 // possibly recursively, a member that is such a structure) 13870 // shall not be a member of a structure or an element of an 13871 // array. 13872 if (FDTy->isFunctionType()) { 13873 // Field declared as a function. 13874 Diag(FD->getLocation(), diag::err_field_declared_as_function) 13875 << FD->getDeclName(); 13876 FD->setInvalidDecl(); 13877 EnclosingDecl->setInvalidDecl(); 13878 continue; 13879 } else if (FDTy->isIncompleteArrayType() && Record && 13880 ((i + 1 == Fields.end() && !Record->isUnion()) || 13881 ((getLangOpts().MicrosoftExt || 13882 getLangOpts().CPlusPlus) && 13883 (i + 1 == Fields.end() || Record->isUnion())))) { 13884 // Flexible array member. 13885 // Microsoft and g++ is more permissive regarding flexible array. 13886 // It will accept flexible array in union and also 13887 // as the sole element of a struct/class. 13888 unsigned DiagID = 0; 13889 if (Record->isUnion()) 13890 DiagID = getLangOpts().MicrosoftExt 13891 ? diag::ext_flexible_array_union_ms 13892 : getLangOpts().CPlusPlus 13893 ? diag::ext_flexible_array_union_gnu 13894 : diag::err_flexible_array_union; 13895 else if (Fields.size() == 1) 13896 DiagID = getLangOpts().MicrosoftExt 13897 ? diag::ext_flexible_array_empty_aggregate_ms 13898 : getLangOpts().CPlusPlus 13899 ? diag::ext_flexible_array_empty_aggregate_gnu 13900 : NumNamedMembers < 1 13901 ? diag::err_flexible_array_empty_aggregate 13902 : 0; 13903 13904 if (DiagID) 13905 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 13906 << Record->getTagKind(); 13907 // While the layout of types that contain virtual bases is not specified 13908 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 13909 // virtual bases after the derived members. This would make a flexible 13910 // array member declared at the end of an object not adjacent to the end 13911 // of the type. 13912 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 13913 if (RD->getNumVBases() != 0) 13914 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 13915 << FD->getDeclName() << Record->getTagKind(); 13916 if (!getLangOpts().C99) 13917 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 13918 << FD->getDeclName() << Record->getTagKind(); 13919 13920 // If the element type has a non-trivial destructor, we would not 13921 // implicitly destroy the elements, so disallow it for now. 13922 // 13923 // FIXME: GCC allows this. We should probably either implicitly delete 13924 // the destructor of the containing class, or just allow this. 13925 QualType BaseElem = Context.getBaseElementType(FD->getType()); 13926 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 13927 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 13928 << FD->getDeclName() << FD->getType(); 13929 FD->setInvalidDecl(); 13930 EnclosingDecl->setInvalidDecl(); 13931 continue; 13932 } 13933 // Okay, we have a legal flexible array member at the end of the struct. 13934 Record->setHasFlexibleArrayMember(true); 13935 } else if (!FDTy->isDependentType() && 13936 RequireCompleteType(FD->getLocation(), FD->getType(), 13937 diag::err_field_incomplete)) { 13938 // Incomplete type 13939 FD->setInvalidDecl(); 13940 EnclosingDecl->setInvalidDecl(); 13941 continue; 13942 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 13943 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 13944 // A type which contains a flexible array member is considered to be a 13945 // flexible array member. 13946 Record->setHasFlexibleArrayMember(true); 13947 if (!Record->isUnion()) { 13948 // If this is a struct/class and this is not the last element, reject 13949 // it. Note that GCC supports variable sized arrays in the middle of 13950 // structures. 13951 if (i + 1 != Fields.end()) 13952 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 13953 << FD->getDeclName() << FD->getType(); 13954 else { 13955 // We support flexible arrays at the end of structs in 13956 // other structs as an extension. 13957 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 13958 << FD->getDeclName(); 13959 } 13960 } 13961 } 13962 if (isa<ObjCContainerDecl>(EnclosingDecl) && 13963 RequireNonAbstractType(FD->getLocation(), FD->getType(), 13964 diag::err_abstract_type_in_decl, 13965 AbstractIvarType)) { 13966 // Ivars can not have abstract class types 13967 FD->setInvalidDecl(); 13968 } 13969 if (Record && FDTTy->getDecl()->hasObjectMember()) 13970 Record->setHasObjectMember(true); 13971 if (Record && FDTTy->getDecl()->hasVolatileMember()) 13972 Record->setHasVolatileMember(true); 13973 } else if (FDTy->isObjCObjectType()) { 13974 /// A field cannot be an Objective-c object 13975 Diag(FD->getLocation(), diag::err_statically_allocated_object) 13976 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 13977 QualType T = Context.getObjCObjectPointerType(FD->getType()); 13978 FD->setType(T); 13979 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 13980 (!getLangOpts().CPlusPlus || Record->isUnion())) { 13981 // It's an error in ARC if a field has lifetime. 13982 // We don't want to report this in a system header, though, 13983 // so we just make the field unavailable. 13984 // FIXME: that's really not sufficient; we need to make the type 13985 // itself invalid to, say, initialize or copy. 13986 QualType T = FD->getType(); 13987 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 13988 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 13989 SourceLocation loc = FD->getLocation(); 13990 if (getSourceManager().isInSystemHeader(loc)) { 13991 if (!FD->hasAttr<UnavailableAttr>()) { 13992 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13993 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 13994 } 13995 } else { 13996 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 13997 << T->isBlockPointerType() << Record->getTagKind(); 13998 } 13999 ARCErrReported = true; 14000 } 14001 } else if (getLangOpts().ObjC1 && 14002 getLangOpts().getGC() != LangOptions::NonGC && 14003 Record && !Record->hasObjectMember()) { 14004 if (FD->getType()->isObjCObjectPointerType() || 14005 FD->getType().isObjCGCStrong()) 14006 Record->setHasObjectMember(true); 14007 else if (Context.getAsArrayType(FD->getType())) { 14008 QualType BaseType = Context.getBaseElementType(FD->getType()); 14009 if (BaseType->isRecordType() && 14010 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14011 Record->setHasObjectMember(true); 14012 else if (BaseType->isObjCObjectPointerType() || 14013 BaseType.isObjCGCStrong()) 14014 Record->setHasObjectMember(true); 14015 } 14016 } 14017 if (Record && FD->getType().isVolatileQualified()) 14018 Record->setHasVolatileMember(true); 14019 // Keep track of the number of named members. 14020 if (FD->getIdentifier()) 14021 ++NumNamedMembers; 14022 } 14023 14024 // Okay, we successfully defined 'Record'. 14025 if (Record) { 14026 bool Completed = false; 14027 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14028 if (!CXXRecord->isInvalidDecl()) { 14029 // Set access bits correctly on the directly-declared conversions. 14030 for (CXXRecordDecl::conversion_iterator 14031 I = CXXRecord->conversion_begin(), 14032 E = CXXRecord->conversion_end(); I != E; ++I) 14033 I.setAccess((*I)->getAccess()); 14034 } 14035 14036 if (!CXXRecord->isDependentType()) { 14037 if (CXXRecord->hasUserDeclaredDestructor()) { 14038 // Adjust user-defined destructor exception spec. 14039 if (getLangOpts().CPlusPlus11) 14040 AdjustDestructorExceptionSpec(CXXRecord, 14041 CXXRecord->getDestructor()); 14042 } 14043 14044 if (!CXXRecord->isInvalidDecl()) { 14045 // Add any implicitly-declared members to this class. 14046 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14047 14048 // If we have virtual base classes, we may end up finding multiple 14049 // final overriders for a given virtual function. Check for this 14050 // problem now. 14051 if (CXXRecord->getNumVBases()) { 14052 CXXFinalOverriderMap FinalOverriders; 14053 CXXRecord->getFinalOverriders(FinalOverriders); 14054 14055 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14056 MEnd = FinalOverriders.end(); 14057 M != MEnd; ++M) { 14058 for (OverridingMethods::iterator SO = M->second.begin(), 14059 SOEnd = M->second.end(); 14060 SO != SOEnd; ++SO) { 14061 assert(SO->second.size() > 0 && 14062 "Virtual function without overridding functions?"); 14063 if (SO->second.size() == 1) 14064 continue; 14065 14066 // C++ [class.virtual]p2: 14067 // In a derived class, if a virtual member function of a base 14068 // class subobject has more than one final overrider the 14069 // program is ill-formed. 14070 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14071 << (const NamedDecl *)M->first << Record; 14072 Diag(M->first->getLocation(), 14073 diag::note_overridden_virtual_function); 14074 for (OverridingMethods::overriding_iterator 14075 OM = SO->second.begin(), 14076 OMEnd = SO->second.end(); 14077 OM != OMEnd; ++OM) 14078 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14079 << (const NamedDecl *)M->first << OM->Method->getParent(); 14080 14081 Record->setInvalidDecl(); 14082 } 14083 } 14084 CXXRecord->completeDefinition(&FinalOverriders); 14085 Completed = true; 14086 } 14087 } 14088 } 14089 } 14090 14091 if (!Completed) 14092 Record->completeDefinition(); 14093 14094 if (Record->hasAttrs()) { 14095 CheckAlignasUnderalignment(Record); 14096 14097 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14098 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14099 IA->getRange(), IA->getBestCase(), 14100 IA->getSemanticSpelling()); 14101 } 14102 14103 // Check if the structure/union declaration is a type that can have zero 14104 // size in C. For C this is a language extension, for C++ it may cause 14105 // compatibility problems. 14106 bool CheckForZeroSize; 14107 if (!getLangOpts().CPlusPlus) { 14108 CheckForZeroSize = true; 14109 } else { 14110 // For C++ filter out types that cannot be referenced in C code. 14111 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14112 CheckForZeroSize = 14113 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14114 !CXXRecord->isDependentType() && 14115 CXXRecord->isCLike(); 14116 } 14117 if (CheckForZeroSize) { 14118 bool ZeroSize = true; 14119 bool IsEmpty = true; 14120 unsigned NonBitFields = 0; 14121 for (RecordDecl::field_iterator I = Record->field_begin(), 14122 E = Record->field_end(); 14123 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14124 IsEmpty = false; 14125 if (I->isUnnamedBitfield()) { 14126 if (I->getBitWidthValue(Context) > 0) 14127 ZeroSize = false; 14128 } else { 14129 ++NonBitFields; 14130 QualType FieldType = I->getType(); 14131 if (FieldType->isIncompleteType() || 14132 !Context.getTypeSizeInChars(FieldType).isZero()) 14133 ZeroSize = false; 14134 } 14135 } 14136 14137 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14138 // allowed in C++, but warn if its declaration is inside 14139 // extern "C" block. 14140 if (ZeroSize) { 14141 Diag(RecLoc, getLangOpts().CPlusPlus ? 14142 diag::warn_zero_size_struct_union_in_extern_c : 14143 diag::warn_zero_size_struct_union_compat) 14144 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14145 } 14146 14147 // Structs without named members are extension in C (C99 6.7.2.1p7), 14148 // but are accepted by GCC. 14149 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14150 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14151 diag::ext_no_named_members_in_struct_union) 14152 << Record->isUnion(); 14153 } 14154 } 14155 } else { 14156 ObjCIvarDecl **ClsFields = 14157 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14158 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14159 ID->setEndOfDefinitionLoc(RBrac); 14160 // Add ivar's to class's DeclContext. 14161 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14162 ClsFields[i]->setLexicalDeclContext(ID); 14163 ID->addDecl(ClsFields[i]); 14164 } 14165 // Must enforce the rule that ivars in the base classes may not be 14166 // duplicates. 14167 if (ID->getSuperClass()) 14168 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 14169 } else if (ObjCImplementationDecl *IMPDecl = 14170 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14171 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 14172 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 14173 // Ivar declared in @implementation never belongs to the implementation. 14174 // Only it is in implementation's lexical context. 14175 ClsFields[I]->setLexicalDeclContext(IMPDecl); 14176 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 14177 IMPDecl->setIvarLBraceLoc(LBrac); 14178 IMPDecl->setIvarRBraceLoc(RBrac); 14179 } else if (ObjCCategoryDecl *CDecl = 14180 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14181 // case of ivars in class extension; all other cases have been 14182 // reported as errors elsewhere. 14183 // FIXME. Class extension does not have a LocEnd field. 14184 // CDecl->setLocEnd(RBrac); 14185 // Add ivar's to class extension's DeclContext. 14186 // Diagnose redeclaration of private ivars. 14187 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 14188 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14189 if (IDecl) { 14190 if (const ObjCIvarDecl *ClsIvar = 14191 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 14192 Diag(ClsFields[i]->getLocation(), 14193 diag::err_duplicate_ivar_declaration); 14194 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 14195 continue; 14196 } 14197 for (const auto *Ext : IDecl->known_extensions()) { 14198 if (const ObjCIvarDecl *ClsExtIvar 14199 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 14200 Diag(ClsFields[i]->getLocation(), 14201 diag::err_duplicate_ivar_declaration); 14202 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 14203 continue; 14204 } 14205 } 14206 } 14207 ClsFields[i]->setLexicalDeclContext(CDecl); 14208 CDecl->addDecl(ClsFields[i]); 14209 } 14210 CDecl->setIvarLBraceLoc(LBrac); 14211 CDecl->setIvarRBraceLoc(RBrac); 14212 } 14213 } 14214 14215 if (Attr) 14216 ProcessDeclAttributeList(S, Record, Attr); 14217 } 14218 14219 /// \brief Determine whether the given integral value is representable within 14220 /// the given type T. 14221 static bool isRepresentableIntegerValue(ASTContext &Context, 14222 llvm::APSInt &Value, 14223 QualType T) { 14224 assert(T->isIntegralType(Context) && "Integral type required!"); 14225 unsigned BitWidth = Context.getIntWidth(T); 14226 14227 if (Value.isUnsigned() || Value.isNonNegative()) { 14228 if (T->isSignedIntegerOrEnumerationType()) 14229 --BitWidth; 14230 return Value.getActiveBits() <= BitWidth; 14231 } 14232 return Value.getMinSignedBits() <= BitWidth; 14233 } 14234 14235 // \brief Given an integral type, return the next larger integral type 14236 // (or a NULL type of no such type exists). 14237 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 14238 // FIXME: Int128/UInt128 support, which also needs to be introduced into 14239 // enum checking below. 14240 assert(T->isIntegralType(Context) && "Integral type required!"); 14241 const unsigned NumTypes = 4; 14242 QualType SignedIntegralTypes[NumTypes] = { 14243 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 14244 }; 14245 QualType UnsignedIntegralTypes[NumTypes] = { 14246 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 14247 Context.UnsignedLongLongTy 14248 }; 14249 14250 unsigned BitWidth = Context.getTypeSize(T); 14251 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 14252 : UnsignedIntegralTypes; 14253 for (unsigned I = 0; I != NumTypes; ++I) 14254 if (Context.getTypeSize(Types[I]) > BitWidth) 14255 return Types[I]; 14256 14257 return QualType(); 14258 } 14259 14260 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 14261 EnumConstantDecl *LastEnumConst, 14262 SourceLocation IdLoc, 14263 IdentifierInfo *Id, 14264 Expr *Val) { 14265 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14266 llvm::APSInt EnumVal(IntWidth); 14267 QualType EltTy; 14268 14269 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 14270 Val = nullptr; 14271 14272 if (Val) 14273 Val = DefaultLvalueConversion(Val).get(); 14274 14275 if (Val) { 14276 if (Enum->isDependentType() || Val->isTypeDependent()) 14277 EltTy = Context.DependentTy; 14278 else { 14279 SourceLocation ExpLoc; 14280 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14281 !getLangOpts().MSVCCompat) { 14282 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14283 // constant-expression in the enumerator-definition shall be a converted 14284 // constant expression of the underlying type. 14285 EltTy = Enum->getIntegerType(); 14286 ExprResult Converted = 14287 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14288 CCEK_Enumerator); 14289 if (Converted.isInvalid()) 14290 Val = nullptr; 14291 else 14292 Val = Converted.get(); 14293 } else if (!Val->isValueDependent() && 14294 !(Val = VerifyIntegerConstantExpression(Val, 14295 &EnumVal).get())) { 14296 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14297 } else { 14298 if (Enum->isFixed()) { 14299 EltTy = Enum->getIntegerType(); 14300 14301 // In Obj-C and Microsoft mode, require the enumeration value to be 14302 // representable in the underlying type of the enumeration. In C++11, 14303 // we perform a non-narrowing conversion as part of converted constant 14304 // expression checking. 14305 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14306 if (getLangOpts().MSVCCompat) { 14307 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14308 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14309 } else 14310 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14311 } else 14312 Val = ImpCastExprToType(Val, EltTy, 14313 EltTy->isBooleanType() ? 14314 CK_IntegralToBoolean : CK_IntegralCast) 14315 .get(); 14316 } else if (getLangOpts().CPlusPlus) { 14317 // C++11 [dcl.enum]p5: 14318 // If the underlying type is not fixed, the type of each enumerator 14319 // is the type of its initializing value: 14320 // - If an initializer is specified for an enumerator, the 14321 // initializing value has the same type as the expression. 14322 EltTy = Val->getType(); 14323 } else { 14324 // C99 6.7.2.2p2: 14325 // The expression that defines the value of an enumeration constant 14326 // shall be an integer constant expression that has a value 14327 // representable as an int. 14328 14329 // Complain if the value is not representable in an int. 14330 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14331 Diag(IdLoc, diag::ext_enum_value_not_int) 14332 << EnumVal.toString(10) << Val->getSourceRange() 14333 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14334 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14335 // Force the type of the expression to 'int'. 14336 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14337 } 14338 EltTy = Val->getType(); 14339 } 14340 } 14341 } 14342 } 14343 14344 if (!Val) { 14345 if (Enum->isDependentType()) 14346 EltTy = Context.DependentTy; 14347 else if (!LastEnumConst) { 14348 // C++0x [dcl.enum]p5: 14349 // If the underlying type is not fixed, the type of each enumerator 14350 // is the type of its initializing value: 14351 // - If no initializer is specified for the first enumerator, the 14352 // initializing value has an unspecified integral type. 14353 // 14354 // GCC uses 'int' for its unspecified integral type, as does 14355 // C99 6.7.2.2p3. 14356 if (Enum->isFixed()) { 14357 EltTy = Enum->getIntegerType(); 14358 } 14359 else { 14360 EltTy = Context.IntTy; 14361 } 14362 } else { 14363 // Assign the last value + 1. 14364 EnumVal = LastEnumConst->getInitVal(); 14365 ++EnumVal; 14366 EltTy = LastEnumConst->getType(); 14367 14368 // Check for overflow on increment. 14369 if (EnumVal < LastEnumConst->getInitVal()) { 14370 // C++0x [dcl.enum]p5: 14371 // If the underlying type is not fixed, the type of each enumerator 14372 // is the type of its initializing value: 14373 // 14374 // - Otherwise the type of the initializing value is the same as 14375 // the type of the initializing value of the preceding enumerator 14376 // unless the incremented value is not representable in that type, 14377 // in which case the type is an unspecified integral type 14378 // sufficient to contain the incremented value. If no such type 14379 // exists, the program is ill-formed. 14380 QualType T = getNextLargerIntegralType(Context, EltTy); 14381 if (T.isNull() || Enum->isFixed()) { 14382 // There is no integral type larger enough to represent this 14383 // value. Complain, then allow the value to wrap around. 14384 EnumVal = LastEnumConst->getInitVal(); 14385 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 14386 ++EnumVal; 14387 if (Enum->isFixed()) 14388 // When the underlying type is fixed, this is ill-formed. 14389 Diag(IdLoc, diag::err_enumerator_wrapped) 14390 << EnumVal.toString(10) 14391 << EltTy; 14392 else 14393 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 14394 << EnumVal.toString(10); 14395 } else { 14396 EltTy = T; 14397 } 14398 14399 // Retrieve the last enumerator's value, extent that type to the 14400 // type that is supposed to be large enough to represent the incremented 14401 // value, then increment. 14402 EnumVal = LastEnumConst->getInitVal(); 14403 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14404 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 14405 ++EnumVal; 14406 14407 // If we're not in C++, diagnose the overflow of enumerator values, 14408 // which in C99 means that the enumerator value is not representable in 14409 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 14410 // permits enumerator values that are representable in some larger 14411 // integral type. 14412 if (!getLangOpts().CPlusPlus && !T.isNull()) 14413 Diag(IdLoc, diag::warn_enum_value_overflow); 14414 } else if (!getLangOpts().CPlusPlus && 14415 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14416 // Enforce C99 6.7.2.2p2 even when we compute the next value. 14417 Diag(IdLoc, diag::ext_enum_value_not_int) 14418 << EnumVal.toString(10) << 1; 14419 } 14420 } 14421 } 14422 14423 if (!EltTy->isDependentType()) { 14424 // Make the enumerator value match the signedness and size of the 14425 // enumerator's type. 14426 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 14427 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14428 } 14429 14430 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 14431 Val, EnumVal); 14432 } 14433 14434 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 14435 SourceLocation IILoc) { 14436 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 14437 !getLangOpts().CPlusPlus) 14438 return SkipBodyInfo(); 14439 14440 // We have an anonymous enum definition. Look up the first enumerator to 14441 // determine if we should merge the definition with an existing one and 14442 // skip the body. 14443 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 14444 ForRedeclaration); 14445 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 14446 if (!PrevECD) 14447 return SkipBodyInfo(); 14448 14449 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 14450 NamedDecl *Hidden; 14451 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 14452 SkipBodyInfo Skip; 14453 Skip.Previous = Hidden; 14454 return Skip; 14455 } 14456 14457 return SkipBodyInfo(); 14458 } 14459 14460 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 14461 SourceLocation IdLoc, IdentifierInfo *Id, 14462 AttributeList *Attr, 14463 SourceLocation EqualLoc, Expr *Val) { 14464 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 14465 EnumConstantDecl *LastEnumConst = 14466 cast_or_null<EnumConstantDecl>(lastEnumConst); 14467 14468 // The scope passed in may not be a decl scope. Zip up the scope tree until 14469 // we find one that is. 14470 S = getNonFieldDeclScope(S); 14471 14472 // Verify that there isn't already something declared with this name in this 14473 // scope. 14474 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 14475 ForRedeclaration); 14476 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14477 // Maybe we will complain about the shadowed template parameter. 14478 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 14479 // Just pretend that we didn't see the previous declaration. 14480 PrevDecl = nullptr; 14481 } 14482 14483 // C++ [class.mem]p15: 14484 // If T is the name of a class, then each of the following shall have a name 14485 // different from T: 14486 // - every enumerator of every member of class T that is an unscoped 14487 // enumerated type 14488 if (!TheEnumDecl->isScoped()) 14489 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 14490 DeclarationNameInfo(Id, IdLoc)); 14491 14492 EnumConstantDecl *New = 14493 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 14494 if (!New) 14495 return nullptr; 14496 14497 if (PrevDecl) { 14498 // When in C++, we may get a TagDecl with the same name; in this case the 14499 // enum constant will 'hide' the tag. 14500 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 14501 "Received TagDecl when not in C++!"); 14502 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 14503 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 14504 if (isa<EnumConstantDecl>(PrevDecl)) 14505 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 14506 else 14507 Diag(IdLoc, diag::err_redefinition) << Id; 14508 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14509 return nullptr; 14510 } 14511 } 14512 14513 // Process attributes. 14514 if (Attr) ProcessDeclAttributeList(S, New, Attr); 14515 14516 // Register this decl in the current scope stack. 14517 New->setAccess(TheEnumDecl->getAccess()); 14518 PushOnScopeChains(New, S); 14519 14520 ActOnDocumentableDecl(New); 14521 14522 return New; 14523 } 14524 14525 // Returns true when the enum initial expression does not trigger the 14526 // duplicate enum warning. A few common cases are exempted as follows: 14527 // Element2 = Element1 14528 // Element2 = Element1 + 1 14529 // Element2 = Element1 - 1 14530 // Where Element2 and Element1 are from the same enum. 14531 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 14532 Expr *InitExpr = ECD->getInitExpr(); 14533 if (!InitExpr) 14534 return true; 14535 InitExpr = InitExpr->IgnoreImpCasts(); 14536 14537 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 14538 if (!BO->isAdditiveOp()) 14539 return true; 14540 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 14541 if (!IL) 14542 return true; 14543 if (IL->getValue() != 1) 14544 return true; 14545 14546 InitExpr = BO->getLHS(); 14547 } 14548 14549 // This checks if the elements are from the same enum. 14550 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 14551 if (!DRE) 14552 return true; 14553 14554 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 14555 if (!EnumConstant) 14556 return true; 14557 14558 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 14559 Enum) 14560 return true; 14561 14562 return false; 14563 } 14564 14565 namespace { 14566 struct DupKey { 14567 int64_t val; 14568 bool isTombstoneOrEmptyKey; 14569 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 14570 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 14571 }; 14572 14573 static DupKey GetDupKey(const llvm::APSInt& Val) { 14574 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 14575 false); 14576 } 14577 14578 struct DenseMapInfoDupKey { 14579 static DupKey getEmptyKey() { return DupKey(0, true); } 14580 static DupKey getTombstoneKey() { return DupKey(1, true); } 14581 static unsigned getHashValue(const DupKey Key) { 14582 return (unsigned)(Key.val * 37); 14583 } 14584 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 14585 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 14586 LHS.val == RHS.val; 14587 } 14588 }; 14589 } // end anonymous namespace 14590 14591 // Emits a warning when an element is implicitly set a value that 14592 // a previous element has already been set to. 14593 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 14594 EnumDecl *Enum, 14595 QualType EnumType) { 14596 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 14597 return; 14598 // Avoid anonymous enums 14599 if (!Enum->getIdentifier()) 14600 return; 14601 14602 // Only check for small enums. 14603 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 14604 return; 14605 14606 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 14607 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 14608 14609 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 14610 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 14611 ValueToVectorMap; 14612 14613 DuplicatesVector DupVector; 14614 ValueToVectorMap EnumMap; 14615 14616 // Populate the EnumMap with all values represented by enum constants without 14617 // an initialier. 14618 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14619 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 14620 14621 // Null EnumConstantDecl means a previous diagnostic has been emitted for 14622 // this constant. Skip this enum since it may be ill-formed. 14623 if (!ECD) { 14624 return; 14625 } 14626 14627 if (ECD->getInitExpr()) 14628 continue; 14629 14630 DupKey Key = GetDupKey(ECD->getInitVal()); 14631 DeclOrVector &Entry = EnumMap[Key]; 14632 14633 // First time encountering this value. 14634 if (Entry.isNull()) 14635 Entry = ECD; 14636 } 14637 14638 // Create vectors for any values that has duplicates. 14639 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14640 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 14641 if (!ValidDuplicateEnum(ECD, Enum)) 14642 continue; 14643 14644 DupKey Key = GetDupKey(ECD->getInitVal()); 14645 14646 DeclOrVector& Entry = EnumMap[Key]; 14647 if (Entry.isNull()) 14648 continue; 14649 14650 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 14651 // Ensure constants are different. 14652 if (D == ECD) 14653 continue; 14654 14655 // Create new vector and push values onto it. 14656 ECDVector *Vec = new ECDVector(); 14657 Vec->push_back(D); 14658 Vec->push_back(ECD); 14659 14660 // Update entry to point to the duplicates vector. 14661 Entry = Vec; 14662 14663 // Store the vector somewhere we can consult later for quick emission of 14664 // diagnostics. 14665 DupVector.push_back(Vec); 14666 continue; 14667 } 14668 14669 ECDVector *Vec = Entry.get<ECDVector*>(); 14670 // Make sure constants are not added more than once. 14671 if (*Vec->begin() == ECD) 14672 continue; 14673 14674 Vec->push_back(ECD); 14675 } 14676 14677 // Emit diagnostics. 14678 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 14679 DupVectorEnd = DupVector.end(); 14680 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 14681 ECDVector *Vec = *DupVectorIter; 14682 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 14683 14684 // Emit warning for one enum constant. 14685 ECDVector::iterator I = Vec->begin(); 14686 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 14687 << (*I)->getName() << (*I)->getInitVal().toString(10) 14688 << (*I)->getSourceRange(); 14689 ++I; 14690 14691 // Emit one note for each of the remaining enum constants with 14692 // the same value. 14693 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 14694 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 14695 << (*I)->getName() << (*I)->getInitVal().toString(10) 14696 << (*I)->getSourceRange(); 14697 delete Vec; 14698 } 14699 } 14700 14701 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 14702 bool AllowMask) const { 14703 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 14704 assert(ED->isCompleteDefinition() && "expected enum definition"); 14705 14706 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 14707 llvm::APInt &FlagBits = R.first->second; 14708 14709 if (R.second) { 14710 for (auto *E : ED->enumerators()) { 14711 const auto &EVal = E->getInitVal(); 14712 // Only single-bit enumerators introduce new flag values. 14713 if (EVal.isPowerOf2()) 14714 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 14715 } 14716 } 14717 14718 // A value is in a flag enum if either its bits are a subset of the enum's 14719 // flag bits (the first condition) or we are allowing masks and the same is 14720 // true of its complement (the second condition). When masks are allowed, we 14721 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 14722 // 14723 // While it's true that any value could be used as a mask, the assumption is 14724 // that a mask will have all of the insignificant bits set. Anything else is 14725 // likely a logic error. 14726 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 14727 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 14728 } 14729 14730 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 14731 SourceLocation RBraceLoc, Decl *EnumDeclX, 14732 ArrayRef<Decl *> Elements, 14733 Scope *S, AttributeList *Attr) { 14734 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 14735 QualType EnumType = Context.getTypeDeclType(Enum); 14736 14737 if (Attr) 14738 ProcessDeclAttributeList(S, Enum, Attr); 14739 14740 if (Enum->isDependentType()) { 14741 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14742 EnumConstantDecl *ECD = 14743 cast_or_null<EnumConstantDecl>(Elements[i]); 14744 if (!ECD) continue; 14745 14746 ECD->setType(EnumType); 14747 } 14748 14749 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 14750 return; 14751 } 14752 14753 // TODO: If the result value doesn't fit in an int, it must be a long or long 14754 // long value. ISO C does not support this, but GCC does as an extension, 14755 // emit a warning. 14756 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14757 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 14758 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 14759 14760 // Verify that all the values are okay, compute the size of the values, and 14761 // reverse the list. 14762 unsigned NumNegativeBits = 0; 14763 unsigned NumPositiveBits = 0; 14764 14765 // Keep track of whether all elements have type int. 14766 bool AllElementsInt = true; 14767 14768 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14769 EnumConstantDecl *ECD = 14770 cast_or_null<EnumConstantDecl>(Elements[i]); 14771 if (!ECD) continue; // Already issued a diagnostic. 14772 14773 const llvm::APSInt &InitVal = ECD->getInitVal(); 14774 14775 // Keep track of the size of positive and negative values. 14776 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 14777 NumPositiveBits = std::max(NumPositiveBits, 14778 (unsigned)InitVal.getActiveBits()); 14779 else 14780 NumNegativeBits = std::max(NumNegativeBits, 14781 (unsigned)InitVal.getMinSignedBits()); 14782 14783 // Keep track of whether every enum element has type int (very commmon). 14784 if (AllElementsInt) 14785 AllElementsInt = ECD->getType() == Context.IntTy; 14786 } 14787 14788 // Figure out the type that should be used for this enum. 14789 QualType BestType; 14790 unsigned BestWidth; 14791 14792 // C++0x N3000 [conv.prom]p3: 14793 // An rvalue of an unscoped enumeration type whose underlying 14794 // type is not fixed can be converted to an rvalue of the first 14795 // of the following types that can represent all the values of 14796 // the enumeration: int, unsigned int, long int, unsigned long 14797 // int, long long int, or unsigned long long int. 14798 // C99 6.4.4.3p2: 14799 // An identifier declared as an enumeration constant has type int. 14800 // The C99 rule is modified by a gcc extension 14801 QualType BestPromotionType; 14802 14803 bool Packed = Enum->hasAttr<PackedAttr>(); 14804 // -fshort-enums is the equivalent to specifying the packed attribute on all 14805 // enum definitions. 14806 if (LangOpts.ShortEnums) 14807 Packed = true; 14808 14809 if (Enum->isFixed()) { 14810 BestType = Enum->getIntegerType(); 14811 if (BestType->isPromotableIntegerType()) 14812 BestPromotionType = Context.getPromotedIntegerType(BestType); 14813 else 14814 BestPromotionType = BestType; 14815 14816 BestWidth = Context.getIntWidth(BestType); 14817 } 14818 else if (NumNegativeBits) { 14819 // If there is a negative value, figure out the smallest integer type (of 14820 // int/long/longlong) that fits. 14821 // If it's packed, check also if it fits a char or a short. 14822 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 14823 BestType = Context.SignedCharTy; 14824 BestWidth = CharWidth; 14825 } else if (Packed && NumNegativeBits <= ShortWidth && 14826 NumPositiveBits < ShortWidth) { 14827 BestType = Context.ShortTy; 14828 BestWidth = ShortWidth; 14829 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 14830 BestType = Context.IntTy; 14831 BestWidth = IntWidth; 14832 } else { 14833 BestWidth = Context.getTargetInfo().getLongWidth(); 14834 14835 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 14836 BestType = Context.LongTy; 14837 } else { 14838 BestWidth = Context.getTargetInfo().getLongLongWidth(); 14839 14840 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 14841 Diag(Enum->getLocation(), diag::ext_enum_too_large); 14842 BestType = Context.LongLongTy; 14843 } 14844 } 14845 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 14846 } else { 14847 // If there is no negative value, figure out the smallest type that fits 14848 // all of the enumerator values. 14849 // If it's packed, check also if it fits a char or a short. 14850 if (Packed && NumPositiveBits <= CharWidth) { 14851 BestType = Context.UnsignedCharTy; 14852 BestPromotionType = Context.IntTy; 14853 BestWidth = CharWidth; 14854 } else if (Packed && NumPositiveBits <= ShortWidth) { 14855 BestType = Context.UnsignedShortTy; 14856 BestPromotionType = Context.IntTy; 14857 BestWidth = ShortWidth; 14858 } else if (NumPositiveBits <= IntWidth) { 14859 BestType = Context.UnsignedIntTy; 14860 BestWidth = IntWidth; 14861 BestPromotionType 14862 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14863 ? Context.UnsignedIntTy : Context.IntTy; 14864 } else if (NumPositiveBits <= 14865 (BestWidth = Context.getTargetInfo().getLongWidth())) { 14866 BestType = Context.UnsignedLongTy; 14867 BestPromotionType 14868 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14869 ? Context.UnsignedLongTy : Context.LongTy; 14870 } else { 14871 BestWidth = Context.getTargetInfo().getLongLongWidth(); 14872 assert(NumPositiveBits <= BestWidth && 14873 "How could an initializer get larger than ULL?"); 14874 BestType = Context.UnsignedLongLongTy; 14875 BestPromotionType 14876 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14877 ? Context.UnsignedLongLongTy : Context.LongLongTy; 14878 } 14879 } 14880 14881 // Loop over all of the enumerator constants, changing their types to match 14882 // the type of the enum if needed. 14883 for (auto *D : Elements) { 14884 auto *ECD = cast_or_null<EnumConstantDecl>(D); 14885 if (!ECD) continue; // Already issued a diagnostic. 14886 14887 // Standard C says the enumerators have int type, but we allow, as an 14888 // extension, the enumerators to be larger than int size. If each 14889 // enumerator value fits in an int, type it as an int, otherwise type it the 14890 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 14891 // that X has type 'int', not 'unsigned'. 14892 14893 // Determine whether the value fits into an int. 14894 llvm::APSInt InitVal = ECD->getInitVal(); 14895 14896 // If it fits into an integer type, force it. Otherwise force it to match 14897 // the enum decl type. 14898 QualType NewTy; 14899 unsigned NewWidth; 14900 bool NewSign; 14901 if (!getLangOpts().CPlusPlus && 14902 !Enum->isFixed() && 14903 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 14904 NewTy = Context.IntTy; 14905 NewWidth = IntWidth; 14906 NewSign = true; 14907 } else if (ECD->getType() == BestType) { 14908 // Already the right type! 14909 if (getLangOpts().CPlusPlus) 14910 // C++ [dcl.enum]p4: Following the closing brace of an 14911 // enum-specifier, each enumerator has the type of its 14912 // enumeration. 14913 ECD->setType(EnumType); 14914 continue; 14915 } else { 14916 NewTy = BestType; 14917 NewWidth = BestWidth; 14918 NewSign = BestType->isSignedIntegerOrEnumerationType(); 14919 } 14920 14921 // Adjust the APSInt value. 14922 InitVal = InitVal.extOrTrunc(NewWidth); 14923 InitVal.setIsSigned(NewSign); 14924 ECD->setInitVal(InitVal); 14925 14926 // Adjust the Expr initializer and type. 14927 if (ECD->getInitExpr() && 14928 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 14929 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 14930 CK_IntegralCast, 14931 ECD->getInitExpr(), 14932 /*base paths*/ nullptr, 14933 VK_RValue)); 14934 if (getLangOpts().CPlusPlus) 14935 // C++ [dcl.enum]p4: Following the closing brace of an 14936 // enum-specifier, each enumerator has the type of its 14937 // enumeration. 14938 ECD->setType(EnumType); 14939 else 14940 ECD->setType(NewTy); 14941 } 14942 14943 Enum->completeDefinition(BestType, BestPromotionType, 14944 NumPositiveBits, NumNegativeBits); 14945 14946 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 14947 14948 if (Enum->hasAttr<FlagEnumAttr>()) { 14949 for (Decl *D : Elements) { 14950 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 14951 if (!ECD) continue; // Already issued a diagnostic. 14952 14953 llvm::APSInt InitVal = ECD->getInitVal(); 14954 if (InitVal != 0 && !InitVal.isPowerOf2() && 14955 !IsValueInFlagEnum(Enum, InitVal, true)) 14956 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 14957 << ECD << Enum; 14958 } 14959 } 14960 14961 // Now that the enum type is defined, ensure it's not been underaligned. 14962 if (Enum->hasAttrs()) 14963 CheckAlignasUnderalignment(Enum); 14964 } 14965 14966 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 14967 SourceLocation StartLoc, 14968 SourceLocation EndLoc) { 14969 StringLiteral *AsmString = cast<StringLiteral>(expr); 14970 14971 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 14972 AsmString, StartLoc, 14973 EndLoc); 14974 CurContext->addDecl(New); 14975 return New; 14976 } 14977 14978 static void checkModuleImportContext(Sema &S, Module *M, 14979 SourceLocation ImportLoc, DeclContext *DC, 14980 bool FromInclude = false) { 14981 SourceLocation ExternCLoc; 14982 14983 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 14984 switch (LSD->getLanguage()) { 14985 case LinkageSpecDecl::lang_c: 14986 if (ExternCLoc.isInvalid()) 14987 ExternCLoc = LSD->getLocStart(); 14988 break; 14989 case LinkageSpecDecl::lang_cxx: 14990 break; 14991 } 14992 DC = LSD->getParent(); 14993 } 14994 14995 while (isa<LinkageSpecDecl>(DC)) 14996 DC = DC->getParent(); 14997 14998 if (!isa<TranslationUnitDecl>(DC)) { 14999 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15000 ? diag::ext_module_import_not_at_top_level_noop 15001 : diag::err_module_import_not_at_top_level_fatal) 15002 << M->getFullModuleName() << DC; 15003 S.Diag(cast<Decl>(DC)->getLocStart(), 15004 diag::note_module_import_not_at_top_level) << DC; 15005 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15006 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15007 << M->getFullModuleName(); 15008 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c); 15009 } 15010 } 15011 15012 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) { 15013 return checkModuleImportContext(*this, M, ImportLoc, CurContext); 15014 } 15015 15016 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 15017 SourceLocation ImportLoc, 15018 ModuleIdPath Path) { 15019 Module *Mod = 15020 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15021 /*IsIncludeDirective=*/false); 15022 if (!Mod) 15023 return true; 15024 15025 VisibleModules.setVisible(Mod, ImportLoc); 15026 15027 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15028 15029 // FIXME: we should support importing a submodule within a different submodule 15030 // of the same top-level module. Until we do, make it an error rather than 15031 // silently ignoring the import. 15032 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 15033 Diag(ImportLoc, getLangOpts().CompilingModule 15034 ? diag::err_module_self_import 15035 : diag::err_module_import_in_implementation) 15036 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15037 15038 SmallVector<SourceLocation, 2> IdentifierLocs; 15039 Module *ModCheck = Mod; 15040 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15041 // If we've run out of module parents, just drop the remaining identifiers. 15042 // We need the length to be consistent. 15043 if (!ModCheck) 15044 break; 15045 ModCheck = ModCheck->Parent; 15046 15047 IdentifierLocs.push_back(Path[I].second); 15048 } 15049 15050 ImportDecl *Import = ImportDecl::Create(Context, 15051 Context.getTranslationUnitDecl(), 15052 AtLoc.isValid()? AtLoc : ImportLoc, 15053 Mod, IdentifierLocs); 15054 Context.getTranslationUnitDecl()->addDecl(Import); 15055 return Import; 15056 } 15057 15058 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15059 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15060 15061 // Determine whether we're in the #include buffer for a module. The #includes 15062 // in that buffer do not qualify as module imports; they're just an 15063 // implementation detail of us building the module. 15064 // 15065 // FIXME: Should we even get ActOnModuleInclude calls for those? 15066 bool IsInModuleIncludes = 15067 TUKind == TU_Module && 15068 getSourceManager().isWrittenInMainFile(DirectiveLoc); 15069 15070 // Similarly, if we're in the implementation of a module, don't 15071 // synthesize an illegal module import. FIXME: Why not? 15072 bool ShouldAddImport = 15073 !IsInModuleIncludes && 15074 (getLangOpts().CompilingModule || 15075 getLangOpts().CurrentModule.empty() || 15076 getLangOpts().CurrentModule != Mod->getTopLevelModuleName()); 15077 15078 // If this module import was due to an inclusion directive, create an 15079 // implicit import declaration to capture it in the AST. 15080 if (ShouldAddImport) { 15081 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15082 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15083 DirectiveLoc, Mod, 15084 DirectiveLoc); 15085 TU->addDecl(ImportD); 15086 Consumer.HandleImplicitImportDecl(ImportD); 15087 } 15088 15089 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 15090 VisibleModules.setVisible(Mod, DirectiveLoc); 15091 } 15092 15093 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 15094 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 15095 15096 if (getLangOpts().ModulesLocalVisibility) 15097 VisibleModulesStack.push_back(std::move(VisibleModules)); 15098 VisibleModules.setVisible(Mod, DirectiveLoc); 15099 } 15100 15101 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) { 15102 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 15103 15104 if (getLangOpts().ModulesLocalVisibility) { 15105 VisibleModules = std::move(VisibleModulesStack.back()); 15106 VisibleModulesStack.pop_back(); 15107 VisibleModules.setVisible(Mod, DirectiveLoc); 15108 // Leaving a module hides namespace names, so our visible namespace cache 15109 // is now out of date. 15110 VisibleNamespaceCache.clear(); 15111 } 15112 } 15113 15114 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 15115 Module *Mod) { 15116 // Bail if we're not allowed to implicitly import a module here. 15117 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 15118 return; 15119 15120 // Create the implicit import declaration. 15121 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15122 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15123 Loc, Mod, Loc); 15124 TU->addDecl(ImportD); 15125 Consumer.HandleImplicitImportDecl(ImportD); 15126 15127 // Make the module visible. 15128 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 15129 VisibleModules.setVisible(Mod, Loc); 15130 } 15131 15132 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 15133 IdentifierInfo* AliasName, 15134 SourceLocation PragmaLoc, 15135 SourceLocation NameLoc, 15136 SourceLocation AliasNameLoc) { 15137 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 15138 LookupOrdinaryName); 15139 AsmLabelAttr *Attr = 15140 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 15141 15142 // If a declaration that: 15143 // 1) declares a function or a variable 15144 // 2) has external linkage 15145 // already exists, add a label attribute to it. 15146 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15147 if (isDeclExternC(PrevDecl)) 15148 PrevDecl->addAttr(Attr); 15149 else 15150 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 15151 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 15152 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 15153 } else 15154 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 15155 } 15156 15157 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 15158 SourceLocation PragmaLoc, 15159 SourceLocation NameLoc) { 15160 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 15161 15162 if (PrevDecl) { 15163 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 15164 } else { 15165 (void)WeakUndeclaredIdentifiers.insert( 15166 std::pair<IdentifierInfo*,WeakInfo> 15167 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 15168 } 15169 } 15170 15171 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 15172 IdentifierInfo* AliasName, 15173 SourceLocation PragmaLoc, 15174 SourceLocation NameLoc, 15175 SourceLocation AliasNameLoc) { 15176 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 15177 LookupOrdinaryName); 15178 WeakInfo W = WeakInfo(Name, NameLoc); 15179 15180 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15181 if (!PrevDecl->hasAttr<AliasAttr>()) 15182 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 15183 DeclApplyPragmaWeak(TUScope, ND, W); 15184 } else { 15185 (void)WeakUndeclaredIdentifiers.insert( 15186 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 15187 } 15188 } 15189 15190 Decl *Sema::getObjCDeclContext() const { 15191 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 15192 } 15193 15194 AvailabilityResult Sema::getCurContextAvailability() const { 15195 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 15196 if (!D) 15197 return AR_Available; 15198 15199 // If we are within an Objective-C method, we should consult 15200 // both the availability of the method as well as the 15201 // enclosing class. If the class is (say) deprecated, 15202 // the entire method is considered deprecated from the 15203 // purpose of checking if the current context is deprecated. 15204 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 15205 AvailabilityResult R = MD->getAvailability(); 15206 if (R != AR_Available) 15207 return R; 15208 D = MD->getClassInterface(); 15209 } 15210 // If we are within an Objective-c @implementation, it 15211 // gets the same availability context as the @interface. 15212 else if (const ObjCImplementationDecl *ID = 15213 dyn_cast<ObjCImplementationDecl>(D)) { 15214 D = ID->getClassInterface(); 15215 } 15216 // Recover from user error. 15217 return D ? D->getAvailability() : AR_Available; 15218 } 15219