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 "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.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 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 784 BuildCXXNestedNameSpecifier(S, IdInfo, 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 1461 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1462 return false; 1463 } else { 1464 return false; 1465 } 1466 1467 // Only warn for unused decls internal to the translation unit. 1468 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1469 // for inline functions defined in the main source file, for instance. 1470 return mightHaveNonExternalLinkage(D); 1471 } 1472 1473 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1474 if (!D) 1475 return; 1476 1477 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1478 const FunctionDecl *First = FD->getFirstDecl(); 1479 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1480 return; // First should already be in the vector. 1481 } 1482 1483 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1484 const VarDecl *First = VD->getFirstDecl(); 1485 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1486 return; // First should already be in the vector. 1487 } 1488 1489 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1490 UnusedFileScopedDecls.push_back(D); 1491 } 1492 1493 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1494 if (D->isInvalidDecl()) 1495 return false; 1496 1497 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1498 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1499 return false; 1500 1501 if (isa<LabelDecl>(D)) 1502 return true; 1503 1504 // Except for labels, we only care about unused decls that are local to 1505 // functions. 1506 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1507 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1508 // For dependent types, the diagnostic is deferred. 1509 WithinFunction = 1510 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1511 if (!WithinFunction) 1512 return false; 1513 1514 if (isa<TypedefNameDecl>(D)) 1515 return true; 1516 1517 // White-list anything that isn't a local variable. 1518 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1519 return false; 1520 1521 // Types of valid local variables should be complete, so this should succeed. 1522 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1523 1524 // White-list anything with an __attribute__((unused)) type. 1525 const auto *Ty = VD->getType().getTypePtr(); 1526 1527 // Only look at the outermost level of typedef. 1528 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1529 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1530 return false; 1531 } 1532 1533 // If we failed to complete the type for some reason, or if the type is 1534 // dependent, don't diagnose the variable. 1535 if (Ty->isIncompleteType() || Ty->isDependentType()) 1536 return false; 1537 1538 // Look at the element type to ensure that the warning behaviour is 1539 // consistent for both scalars and arrays. 1540 Ty = Ty->getBaseElementTypeUnsafe(); 1541 1542 if (const TagType *TT = Ty->getAs<TagType>()) { 1543 const TagDecl *Tag = TT->getDecl(); 1544 if (Tag->hasAttr<UnusedAttr>()) 1545 return false; 1546 1547 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1548 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1549 return false; 1550 1551 if (const Expr *Init = VD->getInit()) { 1552 if (const ExprWithCleanups *Cleanups = 1553 dyn_cast<ExprWithCleanups>(Init)) 1554 Init = Cleanups->getSubExpr(); 1555 const CXXConstructExpr *Construct = 1556 dyn_cast<CXXConstructExpr>(Init); 1557 if (Construct && !Construct->isElidable()) { 1558 CXXConstructorDecl *CD = Construct->getConstructor(); 1559 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1560 return false; 1561 } 1562 } 1563 } 1564 } 1565 1566 // TODO: __attribute__((unused)) templates? 1567 } 1568 1569 return true; 1570 } 1571 1572 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1573 FixItHint &Hint) { 1574 if (isa<LabelDecl>(D)) { 1575 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1576 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1577 if (AfterColon.isInvalid()) 1578 return; 1579 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1580 getCharRange(D->getLocStart(), AfterColon)); 1581 } 1582 } 1583 1584 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1585 if (D->getTypeForDecl()->isDependentType()) 1586 return; 1587 1588 for (auto *TmpD : D->decls()) { 1589 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1590 DiagnoseUnusedDecl(T); 1591 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1592 DiagnoseUnusedNestedTypedefs(R); 1593 } 1594 } 1595 1596 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1597 /// unless they are marked attr(unused). 1598 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1599 if (!ShouldDiagnoseUnusedDecl(D)) 1600 return; 1601 1602 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1603 // typedefs can be referenced later on, so the diagnostics are emitted 1604 // at end-of-translation-unit. 1605 UnusedLocalTypedefNameCandidates.insert(TD); 1606 return; 1607 } 1608 1609 FixItHint Hint; 1610 GenerateFixForUnusedDecl(D, Context, Hint); 1611 1612 unsigned DiagID; 1613 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1614 DiagID = diag::warn_unused_exception_param; 1615 else if (isa<LabelDecl>(D)) 1616 DiagID = diag::warn_unused_label; 1617 else 1618 DiagID = diag::warn_unused_variable; 1619 1620 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1621 } 1622 1623 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1624 // Verify that we have no forward references left. If so, there was a goto 1625 // or address of a label taken, but no definition of it. Label fwd 1626 // definitions are indicated with a null substmt which is also not a resolved 1627 // MS inline assembly label name. 1628 bool Diagnose = false; 1629 if (L->isMSAsmLabel()) 1630 Diagnose = !L->isResolvedMSAsmLabel(); 1631 else 1632 Diagnose = L->getStmt() == nullptr; 1633 if (Diagnose) 1634 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1635 } 1636 1637 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1638 S->mergeNRVOIntoParent(); 1639 1640 if (S->decl_empty()) return; 1641 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1642 "Scope shouldn't contain decls!"); 1643 1644 for (auto *TmpD : S->decls()) { 1645 assert(TmpD && "This decl didn't get pushed??"); 1646 1647 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1648 NamedDecl *D = cast<NamedDecl>(TmpD); 1649 1650 if (!D->getDeclName()) continue; 1651 1652 // Diagnose unused variables in this scope. 1653 if (!S->hasUnrecoverableErrorOccurred()) { 1654 DiagnoseUnusedDecl(D); 1655 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1656 DiagnoseUnusedNestedTypedefs(RD); 1657 } 1658 1659 // If this was a forward reference to a label, verify it was defined. 1660 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1661 CheckPoppedLabel(LD, *this); 1662 1663 // Remove this name from our lexical scope, and warn on it if we haven't 1664 // already. 1665 IdResolver.RemoveDecl(D); 1666 auto ShadowI = ShadowingDecls.find(D); 1667 if (ShadowI != ShadowingDecls.end()) { 1668 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1669 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1670 << D << FD << FD->getParent(); 1671 Diag(FD->getLocation(), diag::note_previous_declaration); 1672 } 1673 ShadowingDecls.erase(ShadowI); 1674 } 1675 } 1676 } 1677 1678 /// \brief Look for an Objective-C class in the translation unit. 1679 /// 1680 /// \param Id The name of the Objective-C class we're looking for. If 1681 /// typo-correction fixes this name, the Id will be updated 1682 /// to the fixed name. 1683 /// 1684 /// \param IdLoc The location of the name in the translation unit. 1685 /// 1686 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1687 /// if there is no class with the given name. 1688 /// 1689 /// \returns The declaration of the named Objective-C class, or NULL if the 1690 /// class could not be found. 1691 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1692 SourceLocation IdLoc, 1693 bool DoTypoCorrection) { 1694 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1695 // creation from this context. 1696 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1697 1698 if (!IDecl && DoTypoCorrection) { 1699 // Perform typo correction at the given location, but only if we 1700 // find an Objective-C class name. 1701 if (TypoCorrection C = CorrectTypo( 1702 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1703 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1704 CTK_ErrorRecovery)) { 1705 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1706 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1707 Id = IDecl->getIdentifier(); 1708 } 1709 } 1710 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1711 // This routine must always return a class definition, if any. 1712 if (Def && Def->getDefinition()) 1713 Def = Def->getDefinition(); 1714 return Def; 1715 } 1716 1717 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1718 /// from S, where a non-field would be declared. This routine copes 1719 /// with the difference between C and C++ scoping rules in structs and 1720 /// unions. For example, the following code is well-formed in C but 1721 /// ill-formed in C++: 1722 /// @code 1723 /// struct S6 { 1724 /// enum { BAR } e; 1725 /// }; 1726 /// 1727 /// void test_S6() { 1728 /// struct S6 a; 1729 /// a.e = BAR; 1730 /// } 1731 /// @endcode 1732 /// For the declaration of BAR, this routine will return a different 1733 /// scope. The scope S will be the scope of the unnamed enumeration 1734 /// within S6. In C++, this routine will return the scope associated 1735 /// with S6, because the enumeration's scope is a transparent 1736 /// context but structures can contain non-field names. In C, this 1737 /// routine will return the translation unit scope, since the 1738 /// enumeration's scope is a transparent context and structures cannot 1739 /// contain non-field names. 1740 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1741 while (((S->getFlags() & Scope::DeclScope) == 0) || 1742 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1743 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1744 S = S->getParent(); 1745 return S; 1746 } 1747 1748 /// \brief Looks up the declaration of "struct objc_super" and 1749 /// saves it for later use in building builtin declaration of 1750 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1751 /// pre-existing declaration exists no action takes place. 1752 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1753 IdentifierInfo *II) { 1754 if (!II->isStr("objc_msgSendSuper")) 1755 return; 1756 ASTContext &Context = ThisSema.Context; 1757 1758 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1759 SourceLocation(), Sema::LookupTagName); 1760 ThisSema.LookupName(Result, S); 1761 if (Result.getResultKind() == LookupResult::Found) 1762 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1763 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1764 } 1765 1766 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1767 switch (Error) { 1768 case ASTContext::GE_None: 1769 return ""; 1770 case ASTContext::GE_Missing_stdio: 1771 return "stdio.h"; 1772 case ASTContext::GE_Missing_setjmp: 1773 return "setjmp.h"; 1774 case ASTContext::GE_Missing_ucontext: 1775 return "ucontext.h"; 1776 } 1777 llvm_unreachable("unhandled error kind"); 1778 } 1779 1780 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1781 /// file scope. lazily create a decl for it. ForRedeclaration is true 1782 /// if we're creating this built-in in anticipation of redeclaring the 1783 /// built-in. 1784 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1785 Scope *S, bool ForRedeclaration, 1786 SourceLocation Loc) { 1787 LookupPredefedObjCSuperType(*this, S, II); 1788 1789 ASTContext::GetBuiltinTypeError Error; 1790 QualType R = Context.GetBuiltinType(ID, Error); 1791 if (Error) { 1792 if (ForRedeclaration) 1793 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1794 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1795 return nullptr; 1796 } 1797 1798 if (!ForRedeclaration && 1799 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1800 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1801 Diag(Loc, diag::ext_implicit_lib_function_decl) 1802 << Context.BuiltinInfo.getName(ID) << R; 1803 if (Context.BuiltinInfo.getHeaderName(ID) && 1804 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1805 Diag(Loc, diag::note_include_header_or_declare) 1806 << Context.BuiltinInfo.getHeaderName(ID) 1807 << Context.BuiltinInfo.getName(ID); 1808 } 1809 1810 if (R.isNull()) 1811 return nullptr; 1812 1813 DeclContext *Parent = Context.getTranslationUnitDecl(); 1814 if (getLangOpts().CPlusPlus) { 1815 LinkageSpecDecl *CLinkageDecl = 1816 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1817 LinkageSpecDecl::lang_c, false); 1818 CLinkageDecl->setImplicit(); 1819 Parent->addDecl(CLinkageDecl); 1820 Parent = CLinkageDecl; 1821 } 1822 1823 FunctionDecl *New = FunctionDecl::Create(Context, 1824 Parent, 1825 Loc, Loc, II, R, /*TInfo=*/nullptr, 1826 SC_Extern, 1827 false, 1828 R->isFunctionProtoType()); 1829 New->setImplicit(); 1830 1831 // Create Decl objects for each parameter, adding them to the 1832 // FunctionDecl. 1833 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1834 SmallVector<ParmVarDecl*, 16> Params; 1835 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1836 ParmVarDecl *parm = 1837 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1838 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1839 SC_None, nullptr); 1840 parm->setScopeInfo(0, i); 1841 Params.push_back(parm); 1842 } 1843 New->setParams(Params); 1844 } 1845 1846 AddKnownFunctionAttributes(New); 1847 RegisterLocallyScopedExternCDecl(New, S); 1848 1849 // TUScope is the translation-unit scope to insert this function into. 1850 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1851 // relate Scopes to DeclContexts, and probably eliminate CurContext 1852 // entirely, but we're not there yet. 1853 DeclContext *SavedContext = CurContext; 1854 CurContext = Parent; 1855 PushOnScopeChains(New, TUScope); 1856 CurContext = SavedContext; 1857 return New; 1858 } 1859 1860 /// Typedef declarations don't have linkage, but they still denote the same 1861 /// entity if their types are the same. 1862 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1863 /// isSameEntity. 1864 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1865 TypedefNameDecl *Decl, 1866 LookupResult &Previous) { 1867 // This is only interesting when modules are enabled. 1868 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1869 return; 1870 1871 // Empty sets are uninteresting. 1872 if (Previous.empty()) 1873 return; 1874 1875 LookupResult::Filter Filter = Previous.makeFilter(); 1876 while (Filter.hasNext()) { 1877 NamedDecl *Old = Filter.next(); 1878 1879 // Non-hidden declarations are never ignored. 1880 if (S.isVisible(Old)) 1881 continue; 1882 1883 // Declarations of the same entity are not ignored, even if they have 1884 // different linkages. 1885 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1886 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1887 Decl->getUnderlyingType())) 1888 continue; 1889 1890 // If both declarations give a tag declaration a typedef name for linkage 1891 // purposes, then they declare the same entity. 1892 if (S.getLangOpts().CPlusPlus && 1893 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1894 Decl->getAnonDeclWithTypedefName()) 1895 continue; 1896 } 1897 1898 Filter.erase(); 1899 } 1900 1901 Filter.done(); 1902 } 1903 1904 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1905 QualType OldType; 1906 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1907 OldType = OldTypedef->getUnderlyingType(); 1908 else 1909 OldType = Context.getTypeDeclType(Old); 1910 QualType NewType = New->getUnderlyingType(); 1911 1912 if (NewType->isVariablyModifiedType()) { 1913 // Must not redefine a typedef with a variably-modified type. 1914 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1915 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1916 << Kind << NewType; 1917 if (Old->getLocation().isValid()) 1918 Diag(Old->getLocation(), diag::note_previous_definition); 1919 New->setInvalidDecl(); 1920 return true; 1921 } 1922 1923 if (OldType != NewType && 1924 !OldType->isDependentType() && 1925 !NewType->isDependentType() && 1926 !Context.hasSameType(OldType, NewType)) { 1927 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1928 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1929 << Kind << NewType << OldType; 1930 if (Old->getLocation().isValid()) 1931 Diag(Old->getLocation(), diag::note_previous_definition); 1932 New->setInvalidDecl(); 1933 return true; 1934 } 1935 return false; 1936 } 1937 1938 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1939 /// same name and scope as a previous declaration 'Old'. Figure out 1940 /// how to resolve this situation, merging decls or emitting 1941 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1942 /// 1943 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 1944 LookupResult &OldDecls) { 1945 // If the new decl is known invalid already, don't bother doing any 1946 // merging checks. 1947 if (New->isInvalidDecl()) return; 1948 1949 // Allow multiple definitions for ObjC built-in typedefs. 1950 // FIXME: Verify the underlying types are equivalent! 1951 if (getLangOpts().ObjC1) { 1952 const IdentifierInfo *TypeID = New->getIdentifier(); 1953 switch (TypeID->getLength()) { 1954 default: break; 1955 case 2: 1956 { 1957 if (!TypeID->isStr("id")) 1958 break; 1959 QualType T = New->getUnderlyingType(); 1960 if (!T->isPointerType()) 1961 break; 1962 if (!T->isVoidPointerType()) { 1963 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1964 if (!PT->isStructureType()) 1965 break; 1966 } 1967 Context.setObjCIdRedefinitionType(T); 1968 // Install the built-in type for 'id', ignoring the current definition. 1969 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1970 return; 1971 } 1972 case 5: 1973 if (!TypeID->isStr("Class")) 1974 break; 1975 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1976 // Install the built-in type for 'Class', ignoring the current definition. 1977 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1978 return; 1979 case 3: 1980 if (!TypeID->isStr("SEL")) 1981 break; 1982 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1983 // Install the built-in type for 'SEL', ignoring the current definition. 1984 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1985 return; 1986 } 1987 // Fall through - the typedef name was not a builtin type. 1988 } 1989 1990 // Verify the old decl was also a type. 1991 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1992 if (!Old) { 1993 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1994 << New->getDeclName(); 1995 1996 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1997 if (OldD->getLocation().isValid()) 1998 Diag(OldD->getLocation(), diag::note_previous_definition); 1999 2000 return New->setInvalidDecl(); 2001 } 2002 2003 // If the old declaration is invalid, just give up here. 2004 if (Old->isInvalidDecl()) 2005 return New->setInvalidDecl(); 2006 2007 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2008 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2009 auto *NewTag = New->getAnonDeclWithTypedefName(); 2010 NamedDecl *Hidden = nullptr; 2011 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2012 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2013 !hasVisibleDefinition(OldTag, &Hidden)) { 2014 // There is a definition of this tag, but it is not visible. Use it 2015 // instead of our tag. 2016 New->setTypeForDecl(OldTD->getTypeForDecl()); 2017 if (OldTD->isModed()) 2018 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2019 OldTD->getUnderlyingType()); 2020 else 2021 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2022 2023 // Make the old tag definition visible. 2024 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 2025 2026 // If this was an unscoped enumeration, yank all of its enumerators 2027 // out of the scope. 2028 if (isa<EnumDecl>(NewTag)) { 2029 Scope *EnumScope = getNonFieldDeclScope(S); 2030 for (auto *D : NewTag->decls()) { 2031 auto *ED = cast<EnumConstantDecl>(D); 2032 assert(EnumScope->isDeclScope(ED)); 2033 EnumScope->RemoveDecl(ED); 2034 IdResolver.RemoveDecl(ED); 2035 ED->getLexicalDeclContext()->removeDecl(ED); 2036 } 2037 } 2038 } 2039 } 2040 2041 // If the typedef types are not identical, reject them in all languages and 2042 // with any extensions enabled. 2043 if (isIncompatibleTypedef(Old, New)) 2044 return; 2045 2046 // The types match. Link up the redeclaration chain and merge attributes if 2047 // the old declaration was a typedef. 2048 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2049 New->setPreviousDecl(Typedef); 2050 mergeDeclAttributes(New, Old); 2051 } 2052 2053 if (getLangOpts().MicrosoftExt) 2054 return; 2055 2056 if (getLangOpts().CPlusPlus) { 2057 // C++ [dcl.typedef]p2: 2058 // In a given non-class scope, a typedef specifier can be used to 2059 // redefine the name of any type declared in that scope to refer 2060 // to the type to which it already refers. 2061 if (!isa<CXXRecordDecl>(CurContext)) 2062 return; 2063 2064 // C++0x [dcl.typedef]p4: 2065 // In a given class scope, a typedef specifier can be used to redefine 2066 // any class-name declared in that scope that is not also a typedef-name 2067 // to refer to the type to which it already refers. 2068 // 2069 // This wording came in via DR424, which was a correction to the 2070 // wording in DR56, which accidentally banned code like: 2071 // 2072 // struct S { 2073 // typedef struct A { } A; 2074 // }; 2075 // 2076 // in the C++03 standard. We implement the C++0x semantics, which 2077 // allow the above but disallow 2078 // 2079 // struct S { 2080 // typedef int I; 2081 // typedef int I; 2082 // }; 2083 // 2084 // since that was the intent of DR56. 2085 if (!isa<TypedefNameDecl>(Old)) 2086 return; 2087 2088 Diag(New->getLocation(), diag::err_redefinition) 2089 << New->getDeclName(); 2090 Diag(Old->getLocation(), diag::note_previous_definition); 2091 return New->setInvalidDecl(); 2092 } 2093 2094 // Modules always permit redefinition of typedefs, as does C11. 2095 if (getLangOpts().Modules || getLangOpts().C11) 2096 return; 2097 2098 // If we have a redefinition of a typedef in C, emit a warning. This warning 2099 // is normally mapped to an error, but can be controlled with 2100 // -Wtypedef-redefinition. If either the original or the redefinition is 2101 // in a system header, don't emit this for compatibility with GCC. 2102 if (getDiagnostics().getSuppressSystemWarnings() && 2103 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2104 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2105 return; 2106 2107 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2108 << New->getDeclName(); 2109 Diag(Old->getLocation(), diag::note_previous_definition); 2110 } 2111 2112 /// DeclhasAttr - returns true if decl Declaration already has the target 2113 /// attribute. 2114 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2115 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2116 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2117 for (const auto *i : D->attrs()) 2118 if (i->getKind() == A->getKind()) { 2119 if (Ann) { 2120 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2121 return true; 2122 continue; 2123 } 2124 // FIXME: Don't hardcode this check 2125 if (OA && isa<OwnershipAttr>(i)) 2126 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2127 return true; 2128 } 2129 2130 return false; 2131 } 2132 2133 static bool isAttributeTargetADefinition(Decl *D) { 2134 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2135 return VD->isThisDeclarationADefinition(); 2136 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2137 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2138 return true; 2139 } 2140 2141 /// Merge alignment attributes from \p Old to \p New, taking into account the 2142 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2143 /// 2144 /// \return \c true if any attributes were added to \p New. 2145 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2146 // Look for alignas attributes on Old, and pick out whichever attribute 2147 // specifies the strictest alignment requirement. 2148 AlignedAttr *OldAlignasAttr = nullptr; 2149 AlignedAttr *OldStrictestAlignAttr = nullptr; 2150 unsigned OldAlign = 0; 2151 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2152 // FIXME: We have no way of representing inherited dependent alignments 2153 // in a case like: 2154 // template<int A, int B> struct alignas(A) X; 2155 // template<int A, int B> struct alignas(B) X {}; 2156 // For now, we just ignore any alignas attributes which are not on the 2157 // definition in such a case. 2158 if (I->isAlignmentDependent()) 2159 return false; 2160 2161 if (I->isAlignas()) 2162 OldAlignasAttr = I; 2163 2164 unsigned Align = I->getAlignment(S.Context); 2165 if (Align > OldAlign) { 2166 OldAlign = Align; 2167 OldStrictestAlignAttr = I; 2168 } 2169 } 2170 2171 // Look for alignas attributes on New. 2172 AlignedAttr *NewAlignasAttr = nullptr; 2173 unsigned NewAlign = 0; 2174 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2175 if (I->isAlignmentDependent()) 2176 return false; 2177 2178 if (I->isAlignas()) 2179 NewAlignasAttr = I; 2180 2181 unsigned Align = I->getAlignment(S.Context); 2182 if (Align > NewAlign) 2183 NewAlign = Align; 2184 } 2185 2186 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2187 // Both declarations have 'alignas' attributes. We require them to match. 2188 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2189 // fall short. (If two declarations both have alignas, they must both match 2190 // every definition, and so must match each other if there is a definition.) 2191 2192 // If either declaration only contains 'alignas(0)' specifiers, then it 2193 // specifies the natural alignment for the type. 2194 if (OldAlign == 0 || NewAlign == 0) { 2195 QualType Ty; 2196 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2197 Ty = VD->getType(); 2198 else 2199 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2200 2201 if (OldAlign == 0) 2202 OldAlign = S.Context.getTypeAlign(Ty); 2203 if (NewAlign == 0) 2204 NewAlign = S.Context.getTypeAlign(Ty); 2205 } 2206 2207 if (OldAlign != NewAlign) { 2208 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2209 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2210 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2211 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2212 } 2213 } 2214 2215 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2216 // C++11 [dcl.align]p6: 2217 // if any declaration of an entity has an alignment-specifier, 2218 // every defining declaration of that entity shall specify an 2219 // equivalent alignment. 2220 // C11 6.7.5/7: 2221 // If the definition of an object does not have an alignment 2222 // specifier, any other declaration of that object shall also 2223 // have no alignment specifier. 2224 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2225 << OldAlignasAttr; 2226 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2227 << OldAlignasAttr; 2228 } 2229 2230 bool AnyAdded = false; 2231 2232 // Ensure we have an attribute representing the strictest alignment. 2233 if (OldAlign > NewAlign) { 2234 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2235 Clone->setInherited(true); 2236 New->addAttr(Clone); 2237 AnyAdded = true; 2238 } 2239 2240 // Ensure we have an alignas attribute if the old declaration had one. 2241 if (OldAlignasAttr && !NewAlignasAttr && 2242 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2243 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2244 Clone->setInherited(true); 2245 New->addAttr(Clone); 2246 AnyAdded = true; 2247 } 2248 2249 return AnyAdded; 2250 } 2251 2252 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2253 const InheritableAttr *Attr, 2254 Sema::AvailabilityMergeKind AMK) { 2255 // This function copies an attribute Attr from a previous declaration to the 2256 // new declaration D if the new declaration doesn't itself have that attribute 2257 // yet or if that attribute allows duplicates. 2258 // If you're adding a new attribute that requires logic different from 2259 // "use explicit attribute on decl if present, else use attribute from 2260 // previous decl", for example if the attribute needs to be consistent 2261 // between redeclarations, you need to call a custom merge function here. 2262 InheritableAttr *NewAttr = nullptr; 2263 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2264 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2265 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2266 AA->isImplicit(), AA->getIntroduced(), 2267 AA->getDeprecated(), 2268 AA->getObsoleted(), AA->getUnavailable(), 2269 AA->getMessage(), AA->getStrict(), 2270 AA->getReplacement(), AMK, 2271 AttrSpellingListIndex); 2272 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2273 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2274 AttrSpellingListIndex); 2275 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2276 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2277 AttrSpellingListIndex); 2278 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2279 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2280 AttrSpellingListIndex); 2281 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2282 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2283 AttrSpellingListIndex); 2284 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2285 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2286 FA->getFormatIdx(), FA->getFirstArg(), 2287 AttrSpellingListIndex); 2288 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2289 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2290 AttrSpellingListIndex); 2291 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2292 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2293 AttrSpellingListIndex, 2294 IA->getSemanticSpelling()); 2295 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2296 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2297 &S.Context.Idents.get(AA->getSpelling()), 2298 AttrSpellingListIndex); 2299 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2300 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2301 isa<CUDAGlobalAttr>(Attr))) { 2302 // CUDA target attributes are part of function signature for 2303 // overloading purposes and must not be merged. 2304 return false; 2305 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2306 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2307 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2308 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2309 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2310 NewAttr = S.mergeInternalLinkageAttr( 2311 D, InternalLinkageA->getRange(), 2312 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2313 AttrSpellingListIndex); 2314 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2315 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2316 &S.Context.Idents.get(CommonA->getSpelling()), 2317 AttrSpellingListIndex); 2318 else if (isa<AlignedAttr>(Attr)) 2319 // AlignedAttrs are handled separately, because we need to handle all 2320 // such attributes on a declaration at the same time. 2321 NewAttr = nullptr; 2322 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2323 (AMK == Sema::AMK_Override || 2324 AMK == Sema::AMK_ProtocolImplementation)) 2325 NewAttr = nullptr; 2326 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2327 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2328 UA->getGuid()); 2329 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2330 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2331 2332 if (NewAttr) { 2333 NewAttr->setInherited(true); 2334 D->addAttr(NewAttr); 2335 if (isa<MSInheritanceAttr>(NewAttr)) 2336 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2337 return true; 2338 } 2339 2340 return false; 2341 } 2342 2343 static const Decl *getDefinition(const Decl *D) { 2344 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2345 return TD->getDefinition(); 2346 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2347 const VarDecl *Def = VD->getDefinition(); 2348 if (Def) 2349 return Def; 2350 return VD->getActingDefinition(); 2351 } 2352 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2353 return FD->getDefinition(); 2354 return nullptr; 2355 } 2356 2357 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2358 for (const auto *Attribute : D->attrs()) 2359 if (Attribute->getKind() == Kind) 2360 return true; 2361 return false; 2362 } 2363 2364 /// checkNewAttributesAfterDef - If we already have a definition, check that 2365 /// there are no new attributes in this declaration. 2366 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2367 if (!New->hasAttrs()) 2368 return; 2369 2370 const Decl *Def = getDefinition(Old); 2371 if (!Def || Def == New) 2372 return; 2373 2374 AttrVec &NewAttributes = New->getAttrs(); 2375 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2376 const Attr *NewAttribute = NewAttributes[I]; 2377 2378 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2379 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2380 Sema::SkipBodyInfo SkipBody; 2381 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2382 2383 // If we're skipping this definition, drop the "alias" attribute. 2384 if (SkipBody.ShouldSkip) { 2385 NewAttributes.erase(NewAttributes.begin() + I); 2386 --E; 2387 continue; 2388 } 2389 } else { 2390 VarDecl *VD = cast<VarDecl>(New); 2391 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2392 VarDecl::TentativeDefinition 2393 ? diag::err_alias_after_tentative 2394 : diag::err_redefinition; 2395 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2396 S.Diag(Def->getLocation(), diag::note_previous_definition); 2397 VD->setInvalidDecl(); 2398 } 2399 ++I; 2400 continue; 2401 } 2402 2403 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2404 // Tentative definitions are only interesting for the alias check above. 2405 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2406 ++I; 2407 continue; 2408 } 2409 } 2410 2411 if (hasAttribute(Def, NewAttribute->getKind())) { 2412 ++I; 2413 continue; // regular attr merging will take care of validating this. 2414 } 2415 2416 if (isa<C11NoReturnAttr>(NewAttribute)) { 2417 // C's _Noreturn is allowed to be added to a function after it is defined. 2418 ++I; 2419 continue; 2420 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2421 if (AA->isAlignas()) { 2422 // C++11 [dcl.align]p6: 2423 // if any declaration of an entity has an alignment-specifier, 2424 // every defining declaration of that entity shall specify an 2425 // equivalent alignment. 2426 // C11 6.7.5/7: 2427 // If the definition of an object does not have an alignment 2428 // specifier, any other declaration of that object shall also 2429 // have no alignment specifier. 2430 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2431 << AA; 2432 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2433 << AA; 2434 NewAttributes.erase(NewAttributes.begin() + I); 2435 --E; 2436 continue; 2437 } 2438 } 2439 2440 S.Diag(NewAttribute->getLocation(), 2441 diag::warn_attribute_precede_definition); 2442 S.Diag(Def->getLocation(), diag::note_previous_definition); 2443 NewAttributes.erase(NewAttributes.begin() + I); 2444 --E; 2445 } 2446 } 2447 2448 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2449 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2450 AvailabilityMergeKind AMK) { 2451 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2452 UsedAttr *NewAttr = OldAttr->clone(Context); 2453 NewAttr->setInherited(true); 2454 New->addAttr(NewAttr); 2455 } 2456 2457 if (!Old->hasAttrs() && !New->hasAttrs()) 2458 return; 2459 2460 // Attributes declared post-definition are currently ignored. 2461 checkNewAttributesAfterDef(*this, New, Old); 2462 2463 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2464 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2465 if (OldA->getLabel() != NewA->getLabel()) { 2466 // This redeclaration changes __asm__ label. 2467 Diag(New->getLocation(), diag::err_different_asm_label); 2468 Diag(OldA->getLocation(), diag::note_previous_declaration); 2469 } 2470 } else if (Old->isUsed()) { 2471 // This redeclaration adds an __asm__ label to a declaration that has 2472 // already been ODR-used. 2473 Diag(New->getLocation(), diag::err_late_asm_label_name) 2474 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2475 } 2476 } 2477 2478 // Re-declaration cannot add abi_tag's. 2479 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2480 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2481 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2482 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2483 NewTag) == OldAbiTagAttr->tags_end()) { 2484 Diag(NewAbiTagAttr->getLocation(), 2485 diag::err_new_abi_tag_on_redeclaration) 2486 << NewTag; 2487 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2488 } 2489 } 2490 } else { 2491 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2492 Diag(Old->getLocation(), diag::note_previous_declaration); 2493 } 2494 } 2495 2496 if (!Old->hasAttrs()) 2497 return; 2498 2499 bool foundAny = New->hasAttrs(); 2500 2501 // Ensure that any moving of objects within the allocated map is done before 2502 // we process them. 2503 if (!foundAny) New->setAttrs(AttrVec()); 2504 2505 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2506 // Ignore deprecated/unavailable/availability attributes if requested. 2507 AvailabilityMergeKind LocalAMK = AMK_None; 2508 if (isa<DeprecatedAttr>(I) || 2509 isa<UnavailableAttr>(I) || 2510 isa<AvailabilityAttr>(I)) { 2511 switch (AMK) { 2512 case AMK_None: 2513 continue; 2514 2515 case AMK_Redeclaration: 2516 case AMK_Override: 2517 case AMK_ProtocolImplementation: 2518 LocalAMK = AMK; 2519 break; 2520 } 2521 } 2522 2523 // Already handled. 2524 if (isa<UsedAttr>(I)) 2525 continue; 2526 2527 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2528 foundAny = true; 2529 } 2530 2531 if (mergeAlignedAttrs(*this, New, Old)) 2532 foundAny = true; 2533 2534 if (!foundAny) New->dropAttrs(); 2535 } 2536 2537 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2538 /// to the new one. 2539 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2540 const ParmVarDecl *oldDecl, 2541 Sema &S) { 2542 // C++11 [dcl.attr.depend]p2: 2543 // The first declaration of a function shall specify the 2544 // carries_dependency attribute for its declarator-id if any declaration 2545 // of the function specifies the carries_dependency attribute. 2546 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2547 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2548 S.Diag(CDA->getLocation(), 2549 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2550 // Find the first declaration of the parameter. 2551 // FIXME: Should we build redeclaration chains for function parameters? 2552 const FunctionDecl *FirstFD = 2553 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2554 const ParmVarDecl *FirstVD = 2555 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2556 S.Diag(FirstVD->getLocation(), 2557 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2558 } 2559 2560 if (!oldDecl->hasAttrs()) 2561 return; 2562 2563 bool foundAny = newDecl->hasAttrs(); 2564 2565 // Ensure that any moving of objects within the allocated map is 2566 // done before we process them. 2567 if (!foundAny) newDecl->setAttrs(AttrVec()); 2568 2569 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2570 if (!DeclHasAttr(newDecl, I)) { 2571 InheritableAttr *newAttr = 2572 cast<InheritableParamAttr>(I->clone(S.Context)); 2573 newAttr->setInherited(true); 2574 newDecl->addAttr(newAttr); 2575 foundAny = true; 2576 } 2577 } 2578 2579 if (!foundAny) newDecl->dropAttrs(); 2580 } 2581 2582 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2583 const ParmVarDecl *OldParam, 2584 Sema &S) { 2585 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2586 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2587 if (*Oldnullability != *Newnullability) { 2588 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2589 << DiagNullabilityKind( 2590 *Newnullability, 2591 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2592 != 0)) 2593 << DiagNullabilityKind( 2594 *Oldnullability, 2595 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2596 != 0)); 2597 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2598 } 2599 } else { 2600 QualType NewT = NewParam->getType(); 2601 NewT = S.Context.getAttributedType( 2602 AttributedType::getNullabilityAttrKind(*Oldnullability), 2603 NewT, NewT); 2604 NewParam->setType(NewT); 2605 } 2606 } 2607 } 2608 2609 namespace { 2610 2611 /// Used in MergeFunctionDecl to keep track of function parameters in 2612 /// C. 2613 struct GNUCompatibleParamWarning { 2614 ParmVarDecl *OldParm; 2615 ParmVarDecl *NewParm; 2616 QualType PromotedType; 2617 }; 2618 2619 } // end anonymous namespace 2620 2621 /// getSpecialMember - get the special member enum for a method. 2622 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2623 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2624 if (Ctor->isDefaultConstructor()) 2625 return Sema::CXXDefaultConstructor; 2626 2627 if (Ctor->isCopyConstructor()) 2628 return Sema::CXXCopyConstructor; 2629 2630 if (Ctor->isMoveConstructor()) 2631 return Sema::CXXMoveConstructor; 2632 } else if (isa<CXXDestructorDecl>(MD)) { 2633 return Sema::CXXDestructor; 2634 } else if (MD->isCopyAssignmentOperator()) { 2635 return Sema::CXXCopyAssignment; 2636 } else if (MD->isMoveAssignmentOperator()) { 2637 return Sema::CXXMoveAssignment; 2638 } 2639 2640 return Sema::CXXInvalid; 2641 } 2642 2643 // Determine whether the previous declaration was a definition, implicit 2644 // declaration, or a declaration. 2645 template <typename T> 2646 static std::pair<diag::kind, SourceLocation> 2647 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2648 diag::kind PrevDiag; 2649 SourceLocation OldLocation = Old->getLocation(); 2650 if (Old->isThisDeclarationADefinition()) 2651 PrevDiag = diag::note_previous_definition; 2652 else if (Old->isImplicit()) { 2653 PrevDiag = diag::note_previous_implicit_declaration; 2654 if (OldLocation.isInvalid()) 2655 OldLocation = New->getLocation(); 2656 } else 2657 PrevDiag = diag::note_previous_declaration; 2658 return std::make_pair(PrevDiag, OldLocation); 2659 } 2660 2661 /// canRedefineFunction - checks if a function can be redefined. Currently, 2662 /// only extern inline functions can be redefined, and even then only in 2663 /// GNU89 mode. 2664 static bool canRedefineFunction(const FunctionDecl *FD, 2665 const LangOptions& LangOpts) { 2666 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2667 !LangOpts.CPlusPlus && 2668 FD->isInlineSpecified() && 2669 FD->getStorageClass() == SC_Extern); 2670 } 2671 2672 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2673 const AttributedType *AT = T->getAs<AttributedType>(); 2674 while (AT && !AT->isCallingConv()) 2675 AT = AT->getModifiedType()->getAs<AttributedType>(); 2676 return AT; 2677 } 2678 2679 template <typename T> 2680 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2681 const DeclContext *DC = Old->getDeclContext(); 2682 if (DC->isRecord()) 2683 return false; 2684 2685 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2686 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2687 return true; 2688 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2689 return true; 2690 return false; 2691 } 2692 2693 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2694 static bool isExternC(VarTemplateDecl *) { return false; } 2695 2696 /// \brief Check whether a redeclaration of an entity introduced by a 2697 /// using-declaration is valid, given that we know it's not an overload 2698 /// (nor a hidden tag declaration). 2699 template<typename ExpectedDecl> 2700 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2701 ExpectedDecl *New) { 2702 // C++11 [basic.scope.declarative]p4: 2703 // Given a set of declarations in a single declarative region, each of 2704 // which specifies the same unqualified name, 2705 // -- they shall all refer to the same entity, or all refer to functions 2706 // and function templates; or 2707 // -- exactly one declaration shall declare a class name or enumeration 2708 // name that is not a typedef name and the other declarations shall all 2709 // refer to the same variable or enumerator, or all refer to functions 2710 // and function templates; in this case the class name or enumeration 2711 // name is hidden (3.3.10). 2712 2713 // C++11 [namespace.udecl]p14: 2714 // If a function declaration in namespace scope or block scope has the 2715 // same name and the same parameter-type-list as a function introduced 2716 // by a using-declaration, and the declarations do not declare the same 2717 // function, the program is ill-formed. 2718 2719 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2720 if (Old && 2721 !Old->getDeclContext()->getRedeclContext()->Equals( 2722 New->getDeclContext()->getRedeclContext()) && 2723 !(isExternC(Old) && isExternC(New))) 2724 Old = nullptr; 2725 2726 if (!Old) { 2727 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2728 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2729 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2730 return true; 2731 } 2732 return false; 2733 } 2734 2735 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2736 const FunctionDecl *B) { 2737 assert(A->getNumParams() == B->getNumParams()); 2738 2739 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2740 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2741 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2742 if (AttrA == AttrB) 2743 return true; 2744 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2745 }; 2746 2747 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2748 } 2749 2750 /// MergeFunctionDecl - We just parsed a function 'New' from 2751 /// declarator D which has the same name and scope as a previous 2752 /// declaration 'Old'. Figure out how to resolve this situation, 2753 /// merging decls or emitting diagnostics as appropriate. 2754 /// 2755 /// In C++, New and Old must be declarations that are not 2756 /// overloaded. Use IsOverload to determine whether New and Old are 2757 /// overloaded, and to select the Old declaration that New should be 2758 /// merged with. 2759 /// 2760 /// Returns true if there was an error, false otherwise. 2761 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2762 Scope *S, bool MergeTypeWithOld) { 2763 // Verify the old decl was also a function. 2764 FunctionDecl *Old = OldD->getAsFunction(); 2765 if (!Old) { 2766 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2767 if (New->getFriendObjectKind()) { 2768 Diag(New->getLocation(), diag::err_using_decl_friend); 2769 Diag(Shadow->getTargetDecl()->getLocation(), 2770 diag::note_using_decl_target); 2771 Diag(Shadow->getUsingDecl()->getLocation(), 2772 diag::note_using_decl) << 0; 2773 return true; 2774 } 2775 2776 // Check whether the two declarations might declare the same function. 2777 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2778 return true; 2779 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2780 } else { 2781 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2782 << New->getDeclName(); 2783 Diag(OldD->getLocation(), diag::note_previous_definition); 2784 return true; 2785 } 2786 } 2787 2788 // If the old declaration is invalid, just give up here. 2789 if (Old->isInvalidDecl()) 2790 return true; 2791 2792 diag::kind PrevDiag; 2793 SourceLocation OldLocation; 2794 std::tie(PrevDiag, OldLocation) = 2795 getNoteDiagForInvalidRedeclaration(Old, New); 2796 2797 // Don't complain about this if we're in GNU89 mode and the old function 2798 // is an extern inline function. 2799 // Don't complain about specializations. They are not supposed to have 2800 // storage classes. 2801 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2802 New->getStorageClass() == SC_Static && 2803 Old->hasExternalFormalLinkage() && 2804 !New->getTemplateSpecializationInfo() && 2805 !canRedefineFunction(Old, getLangOpts())) { 2806 if (getLangOpts().MicrosoftExt) { 2807 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2808 Diag(OldLocation, PrevDiag); 2809 } else { 2810 Diag(New->getLocation(), diag::err_static_non_static) << New; 2811 Diag(OldLocation, PrevDiag); 2812 return true; 2813 } 2814 } 2815 2816 if (New->hasAttr<InternalLinkageAttr>() && 2817 !Old->hasAttr<InternalLinkageAttr>()) { 2818 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2819 << New->getDeclName(); 2820 Diag(Old->getLocation(), diag::note_previous_definition); 2821 New->dropAttr<InternalLinkageAttr>(); 2822 } 2823 2824 // If a function is first declared with a calling convention, but is later 2825 // declared or defined without one, all following decls assume the calling 2826 // convention of the first. 2827 // 2828 // It's OK if a function is first declared without a calling convention, 2829 // but is later declared or defined with the default calling convention. 2830 // 2831 // To test if either decl has an explicit calling convention, we look for 2832 // AttributedType sugar nodes on the type as written. If they are missing or 2833 // were canonicalized away, we assume the calling convention was implicit. 2834 // 2835 // Note also that we DO NOT return at this point, because we still have 2836 // other tests to run. 2837 QualType OldQType = Context.getCanonicalType(Old->getType()); 2838 QualType NewQType = Context.getCanonicalType(New->getType()); 2839 const FunctionType *OldType = cast<FunctionType>(OldQType); 2840 const FunctionType *NewType = cast<FunctionType>(NewQType); 2841 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2842 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2843 bool RequiresAdjustment = false; 2844 2845 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2846 FunctionDecl *First = Old->getFirstDecl(); 2847 const FunctionType *FT = 2848 First->getType().getCanonicalType()->castAs<FunctionType>(); 2849 FunctionType::ExtInfo FI = FT->getExtInfo(); 2850 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2851 if (!NewCCExplicit) { 2852 // Inherit the CC from the previous declaration if it was specified 2853 // there but not here. 2854 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2855 RequiresAdjustment = true; 2856 } else { 2857 // Calling conventions aren't compatible, so complain. 2858 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2859 Diag(New->getLocation(), diag::err_cconv_change) 2860 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2861 << !FirstCCExplicit 2862 << (!FirstCCExplicit ? "" : 2863 FunctionType::getNameForCallConv(FI.getCC())); 2864 2865 // Put the note on the first decl, since it is the one that matters. 2866 Diag(First->getLocation(), diag::note_previous_declaration); 2867 return true; 2868 } 2869 } 2870 2871 // FIXME: diagnose the other way around? 2872 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2873 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2874 RequiresAdjustment = true; 2875 } 2876 2877 // Merge regparm attribute. 2878 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2879 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2880 if (NewTypeInfo.getHasRegParm()) { 2881 Diag(New->getLocation(), diag::err_regparm_mismatch) 2882 << NewType->getRegParmType() 2883 << OldType->getRegParmType(); 2884 Diag(OldLocation, diag::note_previous_declaration); 2885 return true; 2886 } 2887 2888 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2889 RequiresAdjustment = true; 2890 } 2891 2892 // Merge ns_returns_retained attribute. 2893 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2894 if (NewTypeInfo.getProducesResult()) { 2895 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2896 Diag(OldLocation, diag::note_previous_declaration); 2897 return true; 2898 } 2899 2900 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2901 RequiresAdjustment = true; 2902 } 2903 2904 if (RequiresAdjustment) { 2905 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2906 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2907 New->setType(QualType(AdjustedType, 0)); 2908 NewQType = Context.getCanonicalType(New->getType()); 2909 NewType = cast<FunctionType>(NewQType); 2910 } 2911 2912 // If this redeclaration makes the function inline, we may need to add it to 2913 // UndefinedButUsed. 2914 if (!Old->isInlined() && New->isInlined() && 2915 !New->hasAttr<GNUInlineAttr>() && 2916 !getLangOpts().GNUInline && 2917 Old->isUsed(false) && 2918 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2919 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2920 SourceLocation())); 2921 2922 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2923 // about it. 2924 if (New->hasAttr<GNUInlineAttr>() && 2925 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2926 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2927 } 2928 2929 // If pass_object_size params don't match up perfectly, this isn't a valid 2930 // redeclaration. 2931 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 2932 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 2933 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 2934 << New->getDeclName(); 2935 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2936 return true; 2937 } 2938 2939 if (getLangOpts().CPlusPlus) { 2940 // C++1z [over.load]p2 2941 // Certain function declarations cannot be overloaded: 2942 // -- Function declarations that differ only in the return type, 2943 // the exception specification, or both cannot be overloaded. 2944 2945 // Check the exception specifications match. This may recompute the type of 2946 // both Old and New if it resolved exception specifications, so grab the 2947 // types again after this. Because this updates the type, we do this before 2948 // any of the other checks below, which may update the "de facto" NewQType 2949 // but do not necessarily update the type of New. 2950 if (CheckEquivalentExceptionSpec(Old, New)) 2951 return true; 2952 OldQType = Context.getCanonicalType(Old->getType()); 2953 NewQType = Context.getCanonicalType(New->getType()); 2954 2955 // Go back to the type source info to compare the declared return types, 2956 // per C++1y [dcl.type.auto]p13: 2957 // Redeclarations or specializations of a function or function template 2958 // with a declared return type that uses a placeholder type shall also 2959 // use that placeholder, not a deduced type. 2960 QualType OldDeclaredReturnType = 2961 (Old->getTypeSourceInfo() 2962 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2963 : OldType)->getReturnType(); 2964 QualType NewDeclaredReturnType = 2965 (New->getTypeSourceInfo() 2966 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2967 : NewType)->getReturnType(); 2968 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2969 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2970 New->isLocalExternDecl())) { 2971 QualType ResQT; 2972 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2973 OldDeclaredReturnType->isObjCObjectPointerType()) 2974 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2975 if (ResQT.isNull()) { 2976 if (New->isCXXClassMember() && New->isOutOfLine()) 2977 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2978 << New << New->getReturnTypeSourceRange(); 2979 else 2980 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2981 << New->getReturnTypeSourceRange(); 2982 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2983 << Old->getReturnTypeSourceRange(); 2984 return true; 2985 } 2986 else 2987 NewQType = ResQT; 2988 } 2989 2990 QualType OldReturnType = OldType->getReturnType(); 2991 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2992 if (OldReturnType != NewReturnType) { 2993 // If this function has a deduced return type and has already been 2994 // defined, copy the deduced value from the old declaration. 2995 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2996 if (OldAT && OldAT->isDeduced()) { 2997 New->setType( 2998 SubstAutoType(New->getType(), 2999 OldAT->isDependentType() ? Context.DependentTy 3000 : OldAT->getDeducedType())); 3001 NewQType = Context.getCanonicalType( 3002 SubstAutoType(NewQType, 3003 OldAT->isDependentType() ? Context.DependentTy 3004 : OldAT->getDeducedType())); 3005 } 3006 } 3007 3008 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3009 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3010 if (OldMethod && NewMethod) { 3011 // Preserve triviality. 3012 NewMethod->setTrivial(OldMethod->isTrivial()); 3013 3014 // MSVC allows explicit template specialization at class scope: 3015 // 2 CXXMethodDecls referring to the same function will be injected. 3016 // We don't want a redeclaration error. 3017 bool IsClassScopeExplicitSpecialization = 3018 OldMethod->isFunctionTemplateSpecialization() && 3019 NewMethod->isFunctionTemplateSpecialization(); 3020 bool isFriend = NewMethod->getFriendObjectKind(); 3021 3022 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3023 !IsClassScopeExplicitSpecialization) { 3024 // -- Member function declarations with the same name and the 3025 // same parameter types cannot be overloaded if any of them 3026 // is a static member function declaration. 3027 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3028 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3029 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3030 return true; 3031 } 3032 3033 // C++ [class.mem]p1: 3034 // [...] A member shall not be declared twice in the 3035 // member-specification, except that a nested class or member 3036 // class template can be declared and then later defined. 3037 if (ActiveTemplateInstantiations.empty()) { 3038 unsigned NewDiag; 3039 if (isa<CXXConstructorDecl>(OldMethod)) 3040 NewDiag = diag::err_constructor_redeclared; 3041 else if (isa<CXXDestructorDecl>(NewMethod)) 3042 NewDiag = diag::err_destructor_redeclared; 3043 else if (isa<CXXConversionDecl>(NewMethod)) 3044 NewDiag = diag::err_conv_function_redeclared; 3045 else 3046 NewDiag = diag::err_member_redeclared; 3047 3048 Diag(New->getLocation(), NewDiag); 3049 } else { 3050 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3051 << New << New->getType(); 3052 } 3053 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3054 return true; 3055 3056 // Complain if this is an explicit declaration of a special 3057 // member that was initially declared implicitly. 3058 // 3059 // As an exception, it's okay to befriend such methods in order 3060 // to permit the implicit constructor/destructor/operator calls. 3061 } else if (OldMethod->isImplicit()) { 3062 if (isFriend) { 3063 NewMethod->setImplicit(); 3064 } else { 3065 Diag(NewMethod->getLocation(), 3066 diag::err_definition_of_implicitly_declared_member) 3067 << New << getSpecialMember(OldMethod); 3068 return true; 3069 } 3070 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3071 Diag(NewMethod->getLocation(), 3072 diag::err_definition_of_explicitly_defaulted_member) 3073 << getSpecialMember(OldMethod); 3074 return true; 3075 } 3076 } 3077 3078 // C++11 [dcl.attr.noreturn]p1: 3079 // The first declaration of a function shall specify the noreturn 3080 // attribute if any declaration of that function specifies the noreturn 3081 // attribute. 3082 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3083 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3084 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3085 Diag(Old->getFirstDecl()->getLocation(), 3086 diag::note_noreturn_missing_first_decl); 3087 } 3088 3089 // C++11 [dcl.attr.depend]p2: 3090 // The first declaration of a function shall specify the 3091 // carries_dependency attribute for its declarator-id if any declaration 3092 // of the function specifies the carries_dependency attribute. 3093 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3094 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3095 Diag(CDA->getLocation(), 3096 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3097 Diag(Old->getFirstDecl()->getLocation(), 3098 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3099 } 3100 3101 // (C++98 8.3.5p3): 3102 // All declarations for a function shall agree exactly in both the 3103 // return type and the parameter-type-list. 3104 // We also want to respect all the extended bits except noreturn. 3105 3106 // noreturn should now match unless the old type info didn't have it. 3107 QualType OldQTypeForComparison = OldQType; 3108 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3109 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3110 const FunctionType *OldTypeForComparison 3111 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3112 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3113 assert(OldQTypeForComparison.isCanonical()); 3114 } 3115 3116 if (haveIncompatibleLanguageLinkages(Old, New)) { 3117 // As a special case, retain the language linkage from previous 3118 // declarations of a friend function as an extension. 3119 // 3120 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3121 // and is useful because there's otherwise no way to specify language 3122 // linkage within class scope. 3123 // 3124 // Check cautiously as the friend object kind isn't yet complete. 3125 if (New->getFriendObjectKind() != Decl::FOK_None) { 3126 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3127 Diag(OldLocation, PrevDiag); 3128 } else { 3129 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3130 Diag(OldLocation, PrevDiag); 3131 return true; 3132 } 3133 } 3134 3135 if (OldQTypeForComparison == NewQType) 3136 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3137 3138 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3139 New->isLocalExternDecl()) { 3140 // It's OK if we couldn't merge types for a local function declaraton 3141 // if either the old or new type is dependent. We'll merge the types 3142 // when we instantiate the function. 3143 return false; 3144 } 3145 3146 // Fall through for conflicting redeclarations and redefinitions. 3147 } 3148 3149 // C: Function types need to be compatible, not identical. This handles 3150 // duplicate function decls like "void f(int); void f(enum X);" properly. 3151 if (!getLangOpts().CPlusPlus && 3152 Context.typesAreCompatible(OldQType, NewQType)) { 3153 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3154 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3155 const FunctionProtoType *OldProto = nullptr; 3156 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3157 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3158 // The old declaration provided a function prototype, but the 3159 // new declaration does not. Merge in the prototype. 3160 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3161 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3162 NewQType = 3163 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3164 OldProto->getExtProtoInfo()); 3165 New->setType(NewQType); 3166 New->setHasInheritedPrototype(); 3167 3168 // Synthesize parameters with the same types. 3169 SmallVector<ParmVarDecl*, 16> Params; 3170 for (const auto &ParamType : OldProto->param_types()) { 3171 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3172 SourceLocation(), nullptr, 3173 ParamType, /*TInfo=*/nullptr, 3174 SC_None, nullptr); 3175 Param->setScopeInfo(0, Params.size()); 3176 Param->setImplicit(); 3177 Params.push_back(Param); 3178 } 3179 3180 New->setParams(Params); 3181 } 3182 3183 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3184 } 3185 3186 // GNU C permits a K&R definition to follow a prototype declaration 3187 // if the declared types of the parameters in the K&R definition 3188 // match the types in the prototype declaration, even when the 3189 // promoted types of the parameters from the K&R definition differ 3190 // from the types in the prototype. GCC then keeps the types from 3191 // the prototype. 3192 // 3193 // If a variadic prototype is followed by a non-variadic K&R definition, 3194 // the K&R definition becomes variadic. This is sort of an edge case, but 3195 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3196 // C99 6.9.1p8. 3197 if (!getLangOpts().CPlusPlus && 3198 Old->hasPrototype() && !New->hasPrototype() && 3199 New->getType()->getAs<FunctionProtoType>() && 3200 Old->getNumParams() == New->getNumParams()) { 3201 SmallVector<QualType, 16> ArgTypes; 3202 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3203 const FunctionProtoType *OldProto 3204 = Old->getType()->getAs<FunctionProtoType>(); 3205 const FunctionProtoType *NewProto 3206 = New->getType()->getAs<FunctionProtoType>(); 3207 3208 // Determine whether this is the GNU C extension. 3209 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3210 NewProto->getReturnType()); 3211 bool LooseCompatible = !MergedReturn.isNull(); 3212 for (unsigned Idx = 0, End = Old->getNumParams(); 3213 LooseCompatible && Idx != End; ++Idx) { 3214 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3215 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3216 if (Context.typesAreCompatible(OldParm->getType(), 3217 NewProto->getParamType(Idx))) { 3218 ArgTypes.push_back(NewParm->getType()); 3219 } else if (Context.typesAreCompatible(OldParm->getType(), 3220 NewParm->getType(), 3221 /*CompareUnqualified=*/true)) { 3222 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3223 NewProto->getParamType(Idx) }; 3224 Warnings.push_back(Warn); 3225 ArgTypes.push_back(NewParm->getType()); 3226 } else 3227 LooseCompatible = false; 3228 } 3229 3230 if (LooseCompatible) { 3231 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3232 Diag(Warnings[Warn].NewParm->getLocation(), 3233 diag::ext_param_promoted_not_compatible_with_prototype) 3234 << Warnings[Warn].PromotedType 3235 << Warnings[Warn].OldParm->getType(); 3236 if (Warnings[Warn].OldParm->getLocation().isValid()) 3237 Diag(Warnings[Warn].OldParm->getLocation(), 3238 diag::note_previous_declaration); 3239 } 3240 3241 if (MergeTypeWithOld) 3242 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3243 OldProto->getExtProtoInfo())); 3244 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3245 } 3246 3247 // Fall through to diagnose conflicting types. 3248 } 3249 3250 // A function that has already been declared has been redeclared or 3251 // defined with a different type; show an appropriate diagnostic. 3252 3253 // If the previous declaration was an implicitly-generated builtin 3254 // declaration, then at the very least we should use a specialized note. 3255 unsigned BuiltinID; 3256 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3257 // If it's actually a library-defined builtin function like 'malloc' 3258 // or 'printf', just warn about the incompatible redeclaration. 3259 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3260 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3261 Diag(OldLocation, diag::note_previous_builtin_declaration) 3262 << Old << Old->getType(); 3263 3264 // If this is a global redeclaration, just forget hereafter 3265 // about the "builtin-ness" of the function. 3266 // 3267 // Doing this for local extern declarations is problematic. If 3268 // the builtin declaration remains visible, a second invalid 3269 // local declaration will produce a hard error; if it doesn't 3270 // remain visible, a single bogus local redeclaration (which is 3271 // actually only a warning) could break all the downstream code. 3272 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3273 New->getIdentifier()->revertBuiltin(); 3274 3275 return false; 3276 } 3277 3278 PrevDiag = diag::note_previous_builtin_declaration; 3279 } 3280 3281 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3282 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3283 return true; 3284 } 3285 3286 /// \brief Completes the merge of two function declarations that are 3287 /// known to be compatible. 3288 /// 3289 /// This routine handles the merging of attributes and other 3290 /// properties of function declarations from the old declaration to 3291 /// the new declaration, once we know that New is in fact a 3292 /// redeclaration of Old. 3293 /// 3294 /// \returns false 3295 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3296 Scope *S, bool MergeTypeWithOld) { 3297 // Merge the attributes 3298 mergeDeclAttributes(New, Old); 3299 3300 // Merge "pure" flag. 3301 if (Old->isPure()) 3302 New->setPure(); 3303 3304 // Merge "used" flag. 3305 if (Old->getMostRecentDecl()->isUsed(false)) 3306 New->setIsUsed(); 3307 3308 // Merge attributes from the parameters. These can mismatch with K&R 3309 // declarations. 3310 if (New->getNumParams() == Old->getNumParams()) 3311 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3312 ParmVarDecl *NewParam = New->getParamDecl(i); 3313 ParmVarDecl *OldParam = Old->getParamDecl(i); 3314 mergeParamDeclAttributes(NewParam, OldParam, *this); 3315 mergeParamDeclTypes(NewParam, OldParam, *this); 3316 } 3317 3318 if (getLangOpts().CPlusPlus) 3319 return MergeCXXFunctionDecl(New, Old, S); 3320 3321 // Merge the function types so the we get the composite types for the return 3322 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3323 // was visible. 3324 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3325 if (!Merged.isNull() && MergeTypeWithOld) 3326 New->setType(Merged); 3327 3328 return false; 3329 } 3330 3331 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3332 ObjCMethodDecl *oldMethod) { 3333 // Merge the attributes, including deprecated/unavailable 3334 AvailabilityMergeKind MergeKind = 3335 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3336 ? AMK_ProtocolImplementation 3337 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3338 : AMK_Override; 3339 3340 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3341 3342 // Merge attributes from the parameters. 3343 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3344 oe = oldMethod->param_end(); 3345 for (ObjCMethodDecl::param_iterator 3346 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3347 ni != ne && oi != oe; ++ni, ++oi) 3348 mergeParamDeclAttributes(*ni, *oi, *this); 3349 3350 CheckObjCMethodOverride(newMethod, oldMethod); 3351 } 3352 3353 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3354 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3355 3356 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3357 ? diag::err_redefinition_different_type 3358 : diag::err_redeclaration_different_type) 3359 << New->getDeclName() << New->getType() << Old->getType(); 3360 3361 diag::kind PrevDiag; 3362 SourceLocation OldLocation; 3363 std::tie(PrevDiag, OldLocation) 3364 = getNoteDiagForInvalidRedeclaration(Old, New); 3365 S.Diag(OldLocation, PrevDiag); 3366 New->setInvalidDecl(); 3367 } 3368 3369 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3370 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3371 /// emitting diagnostics as appropriate. 3372 /// 3373 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3374 /// to here in AddInitializerToDecl. We can't check them before the initializer 3375 /// is attached. 3376 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3377 bool MergeTypeWithOld) { 3378 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3379 return; 3380 3381 QualType MergedT; 3382 if (getLangOpts().CPlusPlus) { 3383 if (New->getType()->isUndeducedType()) { 3384 // We don't know what the new type is until the initializer is attached. 3385 return; 3386 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3387 // These could still be something that needs exception specs checked. 3388 return MergeVarDeclExceptionSpecs(New, Old); 3389 } 3390 // C++ [basic.link]p10: 3391 // [...] the types specified by all declarations referring to a given 3392 // object or function shall be identical, except that declarations for an 3393 // array object can specify array types that differ by the presence or 3394 // absence of a major array bound (8.3.4). 3395 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3396 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3397 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3398 3399 // We are merging a variable declaration New into Old. If it has an array 3400 // bound, and that bound differs from Old's bound, we should diagnose the 3401 // mismatch. 3402 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3403 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3404 PrevVD = PrevVD->getPreviousDecl()) { 3405 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3406 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3407 continue; 3408 3409 if (!Context.hasSameType(NewArray, PrevVDTy)) 3410 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3411 } 3412 } 3413 3414 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3415 if (Context.hasSameType(OldArray->getElementType(), 3416 NewArray->getElementType())) 3417 MergedT = New->getType(); 3418 } 3419 // FIXME: Check visibility. New is hidden but has a complete type. If New 3420 // has no array bound, it should not inherit one from Old, if Old is not 3421 // visible. 3422 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3423 if (Context.hasSameType(OldArray->getElementType(), 3424 NewArray->getElementType())) 3425 MergedT = Old->getType(); 3426 } 3427 } 3428 else if (New->getType()->isObjCObjectPointerType() && 3429 Old->getType()->isObjCObjectPointerType()) { 3430 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3431 Old->getType()); 3432 } 3433 } else { 3434 // C 6.2.7p2: 3435 // All declarations that refer to the same object or function shall have 3436 // compatible type. 3437 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3438 } 3439 if (MergedT.isNull()) { 3440 // It's OK if we couldn't merge types if either type is dependent, for a 3441 // block-scope variable. In other cases (static data members of class 3442 // templates, variable templates, ...), we require the types to be 3443 // equivalent. 3444 // FIXME: The C++ standard doesn't say anything about this. 3445 if ((New->getType()->isDependentType() || 3446 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3447 // If the old type was dependent, we can't merge with it, so the new type 3448 // becomes dependent for now. We'll reproduce the original type when we 3449 // instantiate the TypeSourceInfo for the variable. 3450 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3451 New->setType(Context.DependentTy); 3452 return; 3453 } 3454 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3455 } 3456 3457 // Don't actually update the type on the new declaration if the old 3458 // declaration was an extern declaration in a different scope. 3459 if (MergeTypeWithOld) 3460 New->setType(MergedT); 3461 } 3462 3463 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3464 LookupResult &Previous) { 3465 // C11 6.2.7p4: 3466 // For an identifier with internal or external linkage declared 3467 // in a scope in which a prior declaration of that identifier is 3468 // visible, if the prior declaration specifies internal or 3469 // external linkage, the type of the identifier at the later 3470 // declaration becomes the composite type. 3471 // 3472 // If the variable isn't visible, we do not merge with its type. 3473 if (Previous.isShadowed()) 3474 return false; 3475 3476 if (S.getLangOpts().CPlusPlus) { 3477 // C++11 [dcl.array]p3: 3478 // If there is a preceding declaration of the entity in the same 3479 // scope in which the bound was specified, an omitted array bound 3480 // is taken to be the same as in that earlier declaration. 3481 return NewVD->isPreviousDeclInSameBlockScope() || 3482 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3483 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3484 } else { 3485 // If the old declaration was function-local, don't merge with its 3486 // type unless we're in the same function. 3487 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3488 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3489 } 3490 } 3491 3492 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3493 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3494 /// situation, merging decls or emitting diagnostics as appropriate. 3495 /// 3496 /// Tentative definition rules (C99 6.9.2p2) are checked by 3497 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3498 /// definitions here, since the initializer hasn't been attached. 3499 /// 3500 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3501 // If the new decl is already invalid, don't do any other checking. 3502 if (New->isInvalidDecl()) 3503 return; 3504 3505 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3506 return; 3507 3508 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3509 3510 // Verify the old decl was also a variable or variable template. 3511 VarDecl *Old = nullptr; 3512 VarTemplateDecl *OldTemplate = nullptr; 3513 if (Previous.isSingleResult()) { 3514 if (NewTemplate) { 3515 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3516 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3517 3518 if (auto *Shadow = 3519 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3520 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3521 return New->setInvalidDecl(); 3522 } else { 3523 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3524 3525 if (auto *Shadow = 3526 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3527 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3528 return New->setInvalidDecl(); 3529 } 3530 } 3531 if (!Old) { 3532 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3533 << New->getDeclName(); 3534 Diag(Previous.getRepresentativeDecl()->getLocation(), 3535 diag::note_previous_definition); 3536 return New->setInvalidDecl(); 3537 } 3538 3539 // Ensure the template parameters are compatible. 3540 if (NewTemplate && 3541 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3542 OldTemplate->getTemplateParameters(), 3543 /*Complain=*/true, TPL_TemplateMatch)) 3544 return New->setInvalidDecl(); 3545 3546 // C++ [class.mem]p1: 3547 // A member shall not be declared twice in the member-specification [...] 3548 // 3549 // Here, we need only consider static data members. 3550 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3551 Diag(New->getLocation(), diag::err_duplicate_member) 3552 << New->getIdentifier(); 3553 Diag(Old->getLocation(), diag::note_previous_declaration); 3554 New->setInvalidDecl(); 3555 } 3556 3557 mergeDeclAttributes(New, Old); 3558 // Warn if an already-declared variable is made a weak_import in a subsequent 3559 // declaration 3560 if (New->hasAttr<WeakImportAttr>() && 3561 Old->getStorageClass() == SC_None && 3562 !Old->hasAttr<WeakImportAttr>()) { 3563 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3564 Diag(Old->getLocation(), diag::note_previous_definition); 3565 // Remove weak_import attribute on new declaration. 3566 New->dropAttr<WeakImportAttr>(); 3567 } 3568 3569 if (New->hasAttr<InternalLinkageAttr>() && 3570 !Old->hasAttr<InternalLinkageAttr>()) { 3571 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3572 << New->getDeclName(); 3573 Diag(Old->getLocation(), diag::note_previous_definition); 3574 New->dropAttr<InternalLinkageAttr>(); 3575 } 3576 3577 // Merge the types. 3578 VarDecl *MostRecent = Old->getMostRecentDecl(); 3579 if (MostRecent != Old) { 3580 MergeVarDeclTypes(New, MostRecent, 3581 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3582 if (New->isInvalidDecl()) 3583 return; 3584 } 3585 3586 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3587 if (New->isInvalidDecl()) 3588 return; 3589 3590 diag::kind PrevDiag; 3591 SourceLocation OldLocation; 3592 std::tie(PrevDiag, OldLocation) = 3593 getNoteDiagForInvalidRedeclaration(Old, New); 3594 3595 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3596 if (New->getStorageClass() == SC_Static && 3597 !New->isStaticDataMember() && 3598 Old->hasExternalFormalLinkage()) { 3599 if (getLangOpts().MicrosoftExt) { 3600 Diag(New->getLocation(), diag::ext_static_non_static) 3601 << New->getDeclName(); 3602 Diag(OldLocation, PrevDiag); 3603 } else { 3604 Diag(New->getLocation(), diag::err_static_non_static) 3605 << New->getDeclName(); 3606 Diag(OldLocation, PrevDiag); 3607 return New->setInvalidDecl(); 3608 } 3609 } 3610 // C99 6.2.2p4: 3611 // For an identifier declared with the storage-class specifier 3612 // extern in a scope in which a prior declaration of that 3613 // identifier is visible,23) if the prior declaration specifies 3614 // internal or external linkage, the linkage of the identifier at 3615 // the later declaration is the same as the linkage specified at 3616 // the prior declaration. If no prior declaration is visible, or 3617 // if the prior declaration specifies no linkage, then the 3618 // identifier has external linkage. 3619 if (New->hasExternalStorage() && Old->hasLinkage()) 3620 /* Okay */; 3621 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3622 !New->isStaticDataMember() && 3623 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3624 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3625 Diag(OldLocation, PrevDiag); 3626 return New->setInvalidDecl(); 3627 } 3628 3629 // Check if extern is followed by non-extern and vice-versa. 3630 if (New->hasExternalStorage() && 3631 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3632 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3633 Diag(OldLocation, PrevDiag); 3634 return New->setInvalidDecl(); 3635 } 3636 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3637 !New->hasExternalStorage()) { 3638 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3639 Diag(OldLocation, PrevDiag); 3640 return New->setInvalidDecl(); 3641 } 3642 3643 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3644 3645 // FIXME: The test for external storage here seems wrong? We still 3646 // need to check for mismatches. 3647 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3648 // Don't complain about out-of-line definitions of static members. 3649 !(Old->getLexicalDeclContext()->isRecord() && 3650 !New->getLexicalDeclContext()->isRecord())) { 3651 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3652 Diag(OldLocation, PrevDiag); 3653 return New->setInvalidDecl(); 3654 } 3655 3656 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3657 if (VarDecl *Def = Old->getDefinition()) { 3658 // C++1z [dcl.fcn.spec]p4: 3659 // If the definition of a variable appears in a translation unit before 3660 // its first declaration as inline, the program is ill-formed. 3661 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3662 Diag(Def->getLocation(), diag::note_previous_definition); 3663 } 3664 } 3665 3666 // If this redeclaration makes the function inline, we may need to add it to 3667 // UndefinedButUsed. 3668 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3669 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3670 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3671 SourceLocation())); 3672 3673 if (New->getTLSKind() != Old->getTLSKind()) { 3674 if (!Old->getTLSKind()) { 3675 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3676 Diag(OldLocation, PrevDiag); 3677 } else if (!New->getTLSKind()) { 3678 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3679 Diag(OldLocation, PrevDiag); 3680 } else { 3681 // Do not allow redeclaration to change the variable between requiring 3682 // static and dynamic initialization. 3683 // FIXME: GCC allows this, but uses the TLS keyword on the first 3684 // declaration to determine the kind. Do we need to be compatible here? 3685 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3686 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3687 Diag(OldLocation, PrevDiag); 3688 } 3689 } 3690 3691 // C++ doesn't have tentative definitions, so go right ahead and check here. 3692 if (getLangOpts().CPlusPlus && 3693 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3694 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3695 Old->getCanonicalDecl()->isConstexpr()) { 3696 // This definition won't be a definition any more once it's been merged. 3697 Diag(New->getLocation(), 3698 diag::warn_deprecated_redundant_constexpr_static_def); 3699 } else if (VarDecl *Def = Old->getDefinition()) { 3700 if (checkVarDeclRedefinition(Def, New)) 3701 return; 3702 } 3703 } 3704 3705 if (haveIncompatibleLanguageLinkages(Old, New)) { 3706 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3707 Diag(OldLocation, PrevDiag); 3708 New->setInvalidDecl(); 3709 return; 3710 } 3711 3712 // Merge "used" flag. 3713 if (Old->getMostRecentDecl()->isUsed(false)) 3714 New->setIsUsed(); 3715 3716 // Keep a chain of previous declarations. 3717 New->setPreviousDecl(Old); 3718 if (NewTemplate) 3719 NewTemplate->setPreviousDecl(OldTemplate); 3720 3721 // Inherit access appropriately. 3722 New->setAccess(Old->getAccess()); 3723 if (NewTemplate) 3724 NewTemplate->setAccess(New->getAccess()); 3725 3726 if (Old->isInline()) 3727 New->setImplicitlyInline(); 3728 } 3729 3730 /// We've just determined that \p Old and \p New both appear to be definitions 3731 /// of the same variable. Either diagnose or fix the problem. 3732 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3733 if (!hasVisibleDefinition(Old) && 3734 (New->getFormalLinkage() == InternalLinkage || 3735 New->isInline() || 3736 New->getDescribedVarTemplate() || 3737 New->getNumTemplateParameterLists() || 3738 New->getDeclContext()->isDependentContext())) { 3739 // The previous definition is hidden, and multiple definitions are 3740 // permitted (in separate TUs). Demote this to a declaration. 3741 New->demoteThisDefinitionToDeclaration(); 3742 3743 // Make the canonical definition visible. 3744 if (auto *OldTD = Old->getDescribedVarTemplate()) 3745 makeMergedDefinitionVisible(OldTD, New->getLocation()); 3746 makeMergedDefinitionVisible(Old, New->getLocation()); 3747 return false; 3748 } else { 3749 Diag(New->getLocation(), diag::err_redefinition) << New; 3750 Diag(Old->getLocation(), diag::note_previous_definition); 3751 New->setInvalidDecl(); 3752 return true; 3753 } 3754 } 3755 3756 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3757 /// no declarator (e.g. "struct foo;") is parsed. 3758 Decl * 3759 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3760 RecordDecl *&AnonRecord) { 3761 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3762 AnonRecord); 3763 } 3764 3765 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3766 // disambiguate entities defined in different scopes. 3767 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3768 // compatibility. 3769 // We will pick our mangling number depending on which version of MSVC is being 3770 // targeted. 3771 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3772 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3773 ? S->getMSCurManglingNumber() 3774 : S->getMSLastManglingNumber(); 3775 } 3776 3777 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3778 if (!Context.getLangOpts().CPlusPlus) 3779 return; 3780 3781 if (isa<CXXRecordDecl>(Tag->getParent())) { 3782 // If this tag is the direct child of a class, number it if 3783 // it is anonymous. 3784 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3785 return; 3786 MangleNumberingContext &MCtx = 3787 Context.getManglingNumberContext(Tag->getParent()); 3788 Context.setManglingNumber( 3789 Tag, MCtx.getManglingNumber( 3790 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3791 return; 3792 } 3793 3794 // If this tag isn't a direct child of a class, number it if it is local. 3795 Decl *ManglingContextDecl; 3796 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3797 Tag->getDeclContext(), ManglingContextDecl)) { 3798 Context.setManglingNumber( 3799 Tag, MCtx->getManglingNumber( 3800 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3801 } 3802 } 3803 3804 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3805 TypedefNameDecl *NewTD) { 3806 if (TagFromDeclSpec->isInvalidDecl()) 3807 return; 3808 3809 // Do nothing if the tag already has a name for linkage purposes. 3810 if (TagFromDeclSpec->hasNameForLinkage()) 3811 return; 3812 3813 // A well-formed anonymous tag must always be a TUK_Definition. 3814 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3815 3816 // The type must match the tag exactly; no qualifiers allowed. 3817 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3818 Context.getTagDeclType(TagFromDeclSpec))) { 3819 if (getLangOpts().CPlusPlus) 3820 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3821 return; 3822 } 3823 3824 // If we've already computed linkage for the anonymous tag, then 3825 // adding a typedef name for the anonymous decl can change that 3826 // linkage, which might be a serious problem. Diagnose this as 3827 // unsupported and ignore the typedef name. TODO: we should 3828 // pursue this as a language defect and establish a formal rule 3829 // for how to handle it. 3830 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3831 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3832 3833 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3834 tagLoc = getLocForEndOfToken(tagLoc); 3835 3836 llvm::SmallString<40> textToInsert; 3837 textToInsert += ' '; 3838 textToInsert += NewTD->getIdentifier()->getName(); 3839 Diag(tagLoc, diag::note_typedef_changes_linkage) 3840 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3841 return; 3842 } 3843 3844 // Otherwise, set this is the anon-decl typedef for the tag. 3845 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3846 } 3847 3848 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3849 switch (T) { 3850 case DeclSpec::TST_class: 3851 return 0; 3852 case DeclSpec::TST_struct: 3853 return 1; 3854 case DeclSpec::TST_interface: 3855 return 2; 3856 case DeclSpec::TST_union: 3857 return 3; 3858 case DeclSpec::TST_enum: 3859 return 4; 3860 default: 3861 llvm_unreachable("unexpected type specifier"); 3862 } 3863 } 3864 3865 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3866 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3867 /// parameters to cope with template friend declarations. 3868 Decl * 3869 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3870 MultiTemplateParamsArg TemplateParams, 3871 bool IsExplicitInstantiation, 3872 RecordDecl *&AnonRecord) { 3873 Decl *TagD = nullptr; 3874 TagDecl *Tag = nullptr; 3875 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3876 DS.getTypeSpecType() == DeclSpec::TST_struct || 3877 DS.getTypeSpecType() == DeclSpec::TST_interface || 3878 DS.getTypeSpecType() == DeclSpec::TST_union || 3879 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3880 TagD = DS.getRepAsDecl(); 3881 3882 if (!TagD) // We probably had an error 3883 return nullptr; 3884 3885 // Note that the above type specs guarantee that the 3886 // type rep is a Decl, whereas in many of the others 3887 // it's a Type. 3888 if (isa<TagDecl>(TagD)) 3889 Tag = cast<TagDecl>(TagD); 3890 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3891 Tag = CTD->getTemplatedDecl(); 3892 } 3893 3894 if (Tag) { 3895 handleTagNumbering(Tag, S); 3896 Tag->setFreeStanding(); 3897 if (Tag->isInvalidDecl()) 3898 return Tag; 3899 } 3900 3901 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3902 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3903 // or incomplete types shall not be restrict-qualified." 3904 if (TypeQuals & DeclSpec::TQ_restrict) 3905 Diag(DS.getRestrictSpecLoc(), 3906 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3907 << DS.getSourceRange(); 3908 } 3909 3910 if (DS.isInlineSpecified()) 3911 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 3912 << getLangOpts().CPlusPlus1z; 3913 3914 if (DS.isConstexprSpecified()) { 3915 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3916 // and definitions of functions and variables. 3917 if (Tag) 3918 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3919 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3920 else 3921 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3922 // Don't emit warnings after this error. 3923 return TagD; 3924 } 3925 3926 if (DS.isConceptSpecified()) { 3927 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3928 // either a function concept and its definition or a variable concept and 3929 // its initializer. 3930 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3931 return TagD; 3932 } 3933 3934 DiagnoseFunctionSpecifiers(DS); 3935 3936 if (DS.isFriendSpecified()) { 3937 // If we're dealing with a decl but not a TagDecl, assume that 3938 // whatever routines created it handled the friendship aspect. 3939 if (TagD && !Tag) 3940 return nullptr; 3941 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3942 } 3943 3944 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3945 bool IsExplicitSpecialization = 3946 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3947 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3948 !IsExplicitInstantiation && !IsExplicitSpecialization && 3949 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 3950 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3951 // nested-name-specifier unless it is an explicit instantiation 3952 // or an explicit specialization. 3953 // 3954 // FIXME: We allow class template partial specializations here too, per the 3955 // obvious intent of DR1819. 3956 // 3957 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3958 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3959 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 3960 return nullptr; 3961 } 3962 3963 // Track whether this decl-specifier declares anything. 3964 bool DeclaresAnything = true; 3965 3966 // Handle anonymous struct definitions. 3967 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3968 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3969 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3970 if (getLangOpts().CPlusPlus || 3971 Record->getDeclContext()->isRecord()) { 3972 // If CurContext is a DeclContext that can contain statements, 3973 // RecursiveASTVisitor won't visit the decls that 3974 // BuildAnonymousStructOrUnion() will put into CurContext. 3975 // Also store them here so that they can be part of the 3976 // DeclStmt that gets created in this case. 3977 // FIXME: Also return the IndirectFieldDecls created by 3978 // BuildAnonymousStructOr union, for the same reason? 3979 if (CurContext->isFunctionOrMethod()) 3980 AnonRecord = Record; 3981 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3982 Context.getPrintingPolicy()); 3983 } 3984 3985 DeclaresAnything = false; 3986 } 3987 } 3988 3989 // C11 6.7.2.1p2: 3990 // A struct-declaration that does not declare an anonymous structure or 3991 // anonymous union shall contain a struct-declarator-list. 3992 // 3993 // This rule also existed in C89 and C99; the grammar for struct-declaration 3994 // did not permit a struct-declaration without a struct-declarator-list. 3995 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3996 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3997 // Check for Microsoft C extension: anonymous struct/union member. 3998 // Handle 2 kinds of anonymous struct/union: 3999 // struct STRUCT; 4000 // union UNION; 4001 // and 4002 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4003 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4004 if ((Tag && Tag->getDeclName()) || 4005 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4006 RecordDecl *Record = nullptr; 4007 if (Tag) 4008 Record = dyn_cast<RecordDecl>(Tag); 4009 else if (const RecordType *RT = 4010 DS.getRepAsType().get()->getAsStructureType()) 4011 Record = RT->getDecl(); 4012 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4013 Record = UT->getDecl(); 4014 4015 if (Record && getLangOpts().MicrosoftExt) { 4016 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4017 << Record->isUnion() << DS.getSourceRange(); 4018 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4019 } 4020 4021 DeclaresAnything = false; 4022 } 4023 } 4024 4025 // Skip all the checks below if we have a type error. 4026 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4027 (TagD && TagD->isInvalidDecl())) 4028 return TagD; 4029 4030 if (getLangOpts().CPlusPlus && 4031 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4032 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4033 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4034 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4035 DeclaresAnything = false; 4036 4037 if (!DS.isMissingDeclaratorOk()) { 4038 // Customize diagnostic for a typedef missing a name. 4039 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4040 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4041 << DS.getSourceRange(); 4042 else 4043 DeclaresAnything = false; 4044 } 4045 4046 if (DS.isModulePrivateSpecified() && 4047 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4048 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4049 << Tag->getTagKind() 4050 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4051 4052 ActOnDocumentableDecl(TagD); 4053 4054 // C 6.7/2: 4055 // A declaration [...] shall declare at least a declarator [...], a tag, 4056 // or the members of an enumeration. 4057 // C++ [dcl.dcl]p3: 4058 // [If there are no declarators], and except for the declaration of an 4059 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4060 // names into the program, or shall redeclare a name introduced by a 4061 // previous declaration. 4062 if (!DeclaresAnything) { 4063 // In C, we allow this as a (popular) extension / bug. Don't bother 4064 // producing further diagnostics for redundant qualifiers after this. 4065 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4066 return TagD; 4067 } 4068 4069 // C++ [dcl.stc]p1: 4070 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4071 // init-declarator-list of the declaration shall not be empty. 4072 // C++ [dcl.fct.spec]p1: 4073 // If a cv-qualifier appears in a decl-specifier-seq, the 4074 // init-declarator-list of the declaration shall not be empty. 4075 // 4076 // Spurious qualifiers here appear to be valid in C. 4077 unsigned DiagID = diag::warn_standalone_specifier; 4078 if (getLangOpts().CPlusPlus) 4079 DiagID = diag::ext_standalone_specifier; 4080 4081 // Note that a linkage-specification sets a storage class, but 4082 // 'extern "C" struct foo;' is actually valid and not theoretically 4083 // useless. 4084 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4085 if (SCS == DeclSpec::SCS_mutable) 4086 // Since mutable is not a viable storage class specifier in C, there is 4087 // no reason to treat it as an extension. Instead, diagnose as an error. 4088 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4089 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4090 Diag(DS.getStorageClassSpecLoc(), DiagID) 4091 << DeclSpec::getSpecifierName(SCS); 4092 } 4093 4094 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4095 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4096 << DeclSpec::getSpecifierName(TSCS); 4097 if (DS.getTypeQualifiers()) { 4098 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4099 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4100 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4101 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4102 // Restrict is covered above. 4103 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4104 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4105 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4106 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4107 } 4108 4109 // Warn about ignored type attributes, for example: 4110 // __attribute__((aligned)) struct A; 4111 // Attributes should be placed after tag to apply to type declaration. 4112 if (!DS.getAttributes().empty()) { 4113 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4114 if (TypeSpecType == DeclSpec::TST_class || 4115 TypeSpecType == DeclSpec::TST_struct || 4116 TypeSpecType == DeclSpec::TST_interface || 4117 TypeSpecType == DeclSpec::TST_union || 4118 TypeSpecType == DeclSpec::TST_enum) { 4119 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4120 attrs = attrs->getNext()) 4121 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4122 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4123 } 4124 } 4125 4126 return TagD; 4127 } 4128 4129 /// We are trying to inject an anonymous member into the given scope; 4130 /// check if there's an existing declaration that can't be overloaded. 4131 /// 4132 /// \return true if this is a forbidden redeclaration 4133 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4134 Scope *S, 4135 DeclContext *Owner, 4136 DeclarationName Name, 4137 SourceLocation NameLoc, 4138 bool IsUnion) { 4139 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4140 Sema::ForRedeclaration); 4141 if (!SemaRef.LookupName(R, S)) return false; 4142 4143 // Pick a representative declaration. 4144 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4145 assert(PrevDecl && "Expected a non-null Decl"); 4146 4147 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4148 return false; 4149 4150 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4151 << IsUnion << Name; 4152 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4153 4154 return true; 4155 } 4156 4157 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4158 /// anonymous struct or union AnonRecord into the owning context Owner 4159 /// and scope S. This routine will be invoked just after we realize 4160 /// that an unnamed union or struct is actually an anonymous union or 4161 /// struct, e.g., 4162 /// 4163 /// @code 4164 /// union { 4165 /// int i; 4166 /// float f; 4167 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4168 /// // f into the surrounding scope.x 4169 /// @endcode 4170 /// 4171 /// This routine is recursive, injecting the names of nested anonymous 4172 /// structs/unions into the owning context and scope as well. 4173 static bool 4174 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4175 RecordDecl *AnonRecord, AccessSpecifier AS, 4176 SmallVectorImpl<NamedDecl *> &Chaining) { 4177 bool Invalid = false; 4178 4179 // Look every FieldDecl and IndirectFieldDecl with a name. 4180 for (auto *D : AnonRecord->decls()) { 4181 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4182 cast<NamedDecl>(D)->getDeclName()) { 4183 ValueDecl *VD = cast<ValueDecl>(D); 4184 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4185 VD->getLocation(), 4186 AnonRecord->isUnion())) { 4187 // C++ [class.union]p2: 4188 // The names of the members of an anonymous union shall be 4189 // distinct from the names of any other entity in the 4190 // scope in which the anonymous union is declared. 4191 Invalid = true; 4192 } else { 4193 // C++ [class.union]p2: 4194 // For the purpose of name lookup, after the anonymous union 4195 // definition, the members of the anonymous union are 4196 // considered to have been defined in the scope in which the 4197 // anonymous union is declared. 4198 unsigned OldChainingSize = Chaining.size(); 4199 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4200 Chaining.append(IF->chain_begin(), IF->chain_end()); 4201 else 4202 Chaining.push_back(VD); 4203 4204 assert(Chaining.size() >= 2); 4205 NamedDecl **NamedChain = 4206 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4207 for (unsigned i = 0; i < Chaining.size(); i++) 4208 NamedChain[i] = Chaining[i]; 4209 4210 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4211 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4212 VD->getType(), {NamedChain, Chaining.size()}); 4213 4214 for (const auto *Attr : VD->attrs()) 4215 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4216 4217 IndirectField->setAccess(AS); 4218 IndirectField->setImplicit(); 4219 SemaRef.PushOnScopeChains(IndirectField, S); 4220 4221 // That includes picking up the appropriate access specifier. 4222 if (AS != AS_none) IndirectField->setAccess(AS); 4223 4224 Chaining.resize(OldChainingSize); 4225 } 4226 } 4227 } 4228 4229 return Invalid; 4230 } 4231 4232 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4233 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4234 /// illegal input values are mapped to SC_None. 4235 static StorageClass 4236 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4237 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4238 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4239 "Parser allowed 'typedef' as storage class VarDecl."); 4240 switch (StorageClassSpec) { 4241 case DeclSpec::SCS_unspecified: return SC_None; 4242 case DeclSpec::SCS_extern: 4243 if (DS.isExternInLinkageSpec()) 4244 return SC_None; 4245 return SC_Extern; 4246 case DeclSpec::SCS_static: return SC_Static; 4247 case DeclSpec::SCS_auto: return SC_Auto; 4248 case DeclSpec::SCS_register: return SC_Register; 4249 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4250 // Illegal SCSs map to None: error reporting is up to the caller. 4251 case DeclSpec::SCS_mutable: // Fall through. 4252 case DeclSpec::SCS_typedef: return SC_None; 4253 } 4254 llvm_unreachable("unknown storage class specifier"); 4255 } 4256 4257 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4258 assert(Record->hasInClassInitializer()); 4259 4260 for (const auto *I : Record->decls()) { 4261 const auto *FD = dyn_cast<FieldDecl>(I); 4262 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4263 FD = IFD->getAnonField(); 4264 if (FD && FD->hasInClassInitializer()) 4265 return FD->getLocation(); 4266 } 4267 4268 llvm_unreachable("couldn't find in-class initializer"); 4269 } 4270 4271 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4272 SourceLocation DefaultInitLoc) { 4273 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4274 return; 4275 4276 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4277 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4278 } 4279 4280 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4281 CXXRecordDecl *AnonUnion) { 4282 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4283 return; 4284 4285 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4286 } 4287 4288 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4289 /// anonymous structure or union. Anonymous unions are a C++ feature 4290 /// (C++ [class.union]) and a C11 feature; anonymous structures 4291 /// are a C11 feature and GNU C++ extension. 4292 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4293 AccessSpecifier AS, 4294 RecordDecl *Record, 4295 const PrintingPolicy &Policy) { 4296 DeclContext *Owner = Record->getDeclContext(); 4297 4298 // Diagnose whether this anonymous struct/union is an extension. 4299 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4300 Diag(Record->getLocation(), diag::ext_anonymous_union); 4301 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4302 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4303 else if (!Record->isUnion() && !getLangOpts().C11) 4304 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4305 4306 // C and C++ require different kinds of checks for anonymous 4307 // structs/unions. 4308 bool Invalid = false; 4309 if (getLangOpts().CPlusPlus) { 4310 const char *PrevSpec = nullptr; 4311 unsigned DiagID; 4312 if (Record->isUnion()) { 4313 // C++ [class.union]p6: 4314 // Anonymous unions declared in a named namespace or in the 4315 // global namespace shall be declared static. 4316 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4317 (isa<TranslationUnitDecl>(Owner) || 4318 (isa<NamespaceDecl>(Owner) && 4319 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4320 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4321 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4322 4323 // Recover by adding 'static'. 4324 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4325 PrevSpec, DiagID, Policy); 4326 } 4327 // C++ [class.union]p6: 4328 // A storage class is not allowed in a declaration of an 4329 // anonymous union in a class scope. 4330 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4331 isa<RecordDecl>(Owner)) { 4332 Diag(DS.getStorageClassSpecLoc(), 4333 diag::err_anonymous_union_with_storage_spec) 4334 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4335 4336 // Recover by removing the storage specifier. 4337 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4338 SourceLocation(), 4339 PrevSpec, DiagID, Context.getPrintingPolicy()); 4340 } 4341 } 4342 4343 // Ignore const/volatile/restrict qualifiers. 4344 if (DS.getTypeQualifiers()) { 4345 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4346 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4347 << Record->isUnion() << "const" 4348 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4349 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4350 Diag(DS.getVolatileSpecLoc(), 4351 diag::ext_anonymous_struct_union_qualified) 4352 << Record->isUnion() << "volatile" 4353 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4354 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4355 Diag(DS.getRestrictSpecLoc(), 4356 diag::ext_anonymous_struct_union_qualified) 4357 << Record->isUnion() << "restrict" 4358 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4359 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4360 Diag(DS.getAtomicSpecLoc(), 4361 diag::ext_anonymous_struct_union_qualified) 4362 << Record->isUnion() << "_Atomic" 4363 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4364 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4365 Diag(DS.getUnalignedSpecLoc(), 4366 diag::ext_anonymous_struct_union_qualified) 4367 << Record->isUnion() << "__unaligned" 4368 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4369 4370 DS.ClearTypeQualifiers(); 4371 } 4372 4373 // C++ [class.union]p2: 4374 // The member-specification of an anonymous union shall only 4375 // define non-static data members. [Note: nested types and 4376 // functions cannot be declared within an anonymous union. ] 4377 for (auto *Mem : Record->decls()) { 4378 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4379 // C++ [class.union]p3: 4380 // An anonymous union shall not have private or protected 4381 // members (clause 11). 4382 assert(FD->getAccess() != AS_none); 4383 if (FD->getAccess() != AS_public) { 4384 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4385 << Record->isUnion() << (FD->getAccess() == AS_protected); 4386 Invalid = true; 4387 } 4388 4389 // C++ [class.union]p1 4390 // An object of a class with a non-trivial constructor, a non-trivial 4391 // copy constructor, a non-trivial destructor, or a non-trivial copy 4392 // assignment operator cannot be a member of a union, nor can an 4393 // array of such objects. 4394 if (CheckNontrivialField(FD)) 4395 Invalid = true; 4396 } else if (Mem->isImplicit()) { 4397 // Any implicit members are fine. 4398 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4399 // This is a type that showed up in an 4400 // elaborated-type-specifier inside the anonymous struct or 4401 // union, but which actually declares a type outside of the 4402 // anonymous struct or union. It's okay. 4403 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4404 if (!MemRecord->isAnonymousStructOrUnion() && 4405 MemRecord->getDeclName()) { 4406 // Visual C++ allows type definition in anonymous struct or union. 4407 if (getLangOpts().MicrosoftExt) 4408 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4409 << Record->isUnion(); 4410 else { 4411 // This is a nested type declaration. 4412 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4413 << Record->isUnion(); 4414 Invalid = true; 4415 } 4416 } else { 4417 // This is an anonymous type definition within another anonymous type. 4418 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4419 // not part of standard C++. 4420 Diag(MemRecord->getLocation(), 4421 diag::ext_anonymous_record_with_anonymous_type) 4422 << Record->isUnion(); 4423 } 4424 } else if (isa<AccessSpecDecl>(Mem)) { 4425 // Any access specifier is fine. 4426 } else if (isa<StaticAssertDecl>(Mem)) { 4427 // In C++1z, static_assert declarations are also fine. 4428 } else { 4429 // We have something that isn't a non-static data 4430 // member. Complain about it. 4431 unsigned DK = diag::err_anonymous_record_bad_member; 4432 if (isa<TypeDecl>(Mem)) 4433 DK = diag::err_anonymous_record_with_type; 4434 else if (isa<FunctionDecl>(Mem)) 4435 DK = diag::err_anonymous_record_with_function; 4436 else if (isa<VarDecl>(Mem)) 4437 DK = diag::err_anonymous_record_with_static; 4438 4439 // Visual C++ allows type definition in anonymous struct or union. 4440 if (getLangOpts().MicrosoftExt && 4441 DK == diag::err_anonymous_record_with_type) 4442 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4443 << Record->isUnion(); 4444 else { 4445 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4446 Invalid = true; 4447 } 4448 } 4449 } 4450 4451 // C++11 [class.union]p8 (DR1460): 4452 // At most one variant member of a union may have a 4453 // brace-or-equal-initializer. 4454 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4455 Owner->isRecord()) 4456 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4457 cast<CXXRecordDecl>(Record)); 4458 } 4459 4460 if (!Record->isUnion() && !Owner->isRecord()) { 4461 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4462 << getLangOpts().CPlusPlus; 4463 Invalid = true; 4464 } 4465 4466 // Mock up a declarator. 4467 Declarator Dc(DS, Declarator::MemberContext); 4468 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4469 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4470 4471 // Create a declaration for this anonymous struct/union. 4472 NamedDecl *Anon = nullptr; 4473 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4474 Anon = FieldDecl::Create(Context, OwningClass, 4475 DS.getLocStart(), 4476 Record->getLocation(), 4477 /*IdentifierInfo=*/nullptr, 4478 Context.getTypeDeclType(Record), 4479 TInfo, 4480 /*BitWidth=*/nullptr, /*Mutable=*/false, 4481 /*InitStyle=*/ICIS_NoInit); 4482 Anon->setAccess(AS); 4483 if (getLangOpts().CPlusPlus) 4484 FieldCollector->Add(cast<FieldDecl>(Anon)); 4485 } else { 4486 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4487 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4488 if (SCSpec == DeclSpec::SCS_mutable) { 4489 // mutable can only appear on non-static class members, so it's always 4490 // an error here 4491 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4492 Invalid = true; 4493 SC = SC_None; 4494 } 4495 4496 Anon = VarDecl::Create(Context, Owner, 4497 DS.getLocStart(), 4498 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4499 Context.getTypeDeclType(Record), 4500 TInfo, SC); 4501 4502 // Default-initialize the implicit variable. This initialization will be 4503 // trivial in almost all cases, except if a union member has an in-class 4504 // initializer: 4505 // union { int n = 0; }; 4506 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4507 } 4508 Anon->setImplicit(); 4509 4510 // Mark this as an anonymous struct/union type. 4511 Record->setAnonymousStructOrUnion(true); 4512 4513 // Add the anonymous struct/union object to the current 4514 // context. We'll be referencing this object when we refer to one of 4515 // its members. 4516 Owner->addDecl(Anon); 4517 4518 // Inject the members of the anonymous struct/union into the owning 4519 // context and into the identifier resolver chain for name lookup 4520 // purposes. 4521 SmallVector<NamedDecl*, 2> Chain; 4522 Chain.push_back(Anon); 4523 4524 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4525 Invalid = true; 4526 4527 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4528 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4529 Decl *ManglingContextDecl; 4530 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4531 NewVD->getDeclContext(), ManglingContextDecl)) { 4532 Context.setManglingNumber( 4533 NewVD, MCtx->getManglingNumber( 4534 NewVD, getMSManglingNumber(getLangOpts(), S))); 4535 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4536 } 4537 } 4538 } 4539 4540 if (Invalid) 4541 Anon->setInvalidDecl(); 4542 4543 return Anon; 4544 } 4545 4546 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4547 /// Microsoft C anonymous structure. 4548 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4549 /// Example: 4550 /// 4551 /// struct A { int a; }; 4552 /// struct B { struct A; int b; }; 4553 /// 4554 /// void foo() { 4555 /// B var; 4556 /// var.a = 3; 4557 /// } 4558 /// 4559 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4560 RecordDecl *Record) { 4561 assert(Record && "expected a record!"); 4562 4563 // Mock up a declarator. 4564 Declarator Dc(DS, Declarator::TypeNameContext); 4565 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4566 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4567 4568 auto *ParentDecl = cast<RecordDecl>(CurContext); 4569 QualType RecTy = Context.getTypeDeclType(Record); 4570 4571 // Create a declaration for this anonymous struct. 4572 NamedDecl *Anon = FieldDecl::Create(Context, 4573 ParentDecl, 4574 DS.getLocStart(), 4575 DS.getLocStart(), 4576 /*IdentifierInfo=*/nullptr, 4577 RecTy, 4578 TInfo, 4579 /*BitWidth=*/nullptr, /*Mutable=*/false, 4580 /*InitStyle=*/ICIS_NoInit); 4581 Anon->setImplicit(); 4582 4583 // Add the anonymous struct object to the current context. 4584 CurContext->addDecl(Anon); 4585 4586 // Inject the members of the anonymous struct into the current 4587 // context and into the identifier resolver chain for name lookup 4588 // purposes. 4589 SmallVector<NamedDecl*, 2> Chain; 4590 Chain.push_back(Anon); 4591 4592 RecordDecl *RecordDef = Record->getDefinition(); 4593 if (RequireCompleteType(Anon->getLocation(), RecTy, 4594 diag::err_field_incomplete) || 4595 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4596 AS_none, Chain)) { 4597 Anon->setInvalidDecl(); 4598 ParentDecl->setInvalidDecl(); 4599 } 4600 4601 return Anon; 4602 } 4603 4604 /// GetNameForDeclarator - Determine the full declaration name for the 4605 /// given Declarator. 4606 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4607 return GetNameFromUnqualifiedId(D.getName()); 4608 } 4609 4610 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4611 DeclarationNameInfo 4612 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4613 DeclarationNameInfo NameInfo; 4614 NameInfo.setLoc(Name.StartLocation); 4615 4616 switch (Name.getKind()) { 4617 4618 case UnqualifiedId::IK_ImplicitSelfParam: 4619 case UnqualifiedId::IK_Identifier: 4620 NameInfo.setName(Name.Identifier); 4621 NameInfo.setLoc(Name.StartLocation); 4622 return NameInfo; 4623 4624 case UnqualifiedId::IK_OperatorFunctionId: 4625 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4626 Name.OperatorFunctionId.Operator)); 4627 NameInfo.setLoc(Name.StartLocation); 4628 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4629 = Name.OperatorFunctionId.SymbolLocations[0]; 4630 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4631 = Name.EndLocation.getRawEncoding(); 4632 return NameInfo; 4633 4634 case UnqualifiedId::IK_LiteralOperatorId: 4635 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4636 Name.Identifier)); 4637 NameInfo.setLoc(Name.StartLocation); 4638 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4639 return NameInfo; 4640 4641 case UnqualifiedId::IK_ConversionFunctionId: { 4642 TypeSourceInfo *TInfo; 4643 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4644 if (Ty.isNull()) 4645 return DeclarationNameInfo(); 4646 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4647 Context.getCanonicalType(Ty))); 4648 NameInfo.setLoc(Name.StartLocation); 4649 NameInfo.setNamedTypeInfo(TInfo); 4650 return NameInfo; 4651 } 4652 4653 case UnqualifiedId::IK_ConstructorName: { 4654 TypeSourceInfo *TInfo; 4655 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4656 if (Ty.isNull()) 4657 return DeclarationNameInfo(); 4658 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4659 Context.getCanonicalType(Ty))); 4660 NameInfo.setLoc(Name.StartLocation); 4661 NameInfo.setNamedTypeInfo(TInfo); 4662 return NameInfo; 4663 } 4664 4665 case UnqualifiedId::IK_ConstructorTemplateId: { 4666 // In well-formed code, we can only have a constructor 4667 // template-id that refers to the current context, so go there 4668 // to find the actual type being constructed. 4669 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4670 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4671 return DeclarationNameInfo(); 4672 4673 // Determine the type of the class being constructed. 4674 QualType CurClassType = Context.getTypeDeclType(CurClass); 4675 4676 // FIXME: Check two things: that the template-id names the same type as 4677 // CurClassType, and that the template-id does not occur when the name 4678 // was qualified. 4679 4680 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4681 Context.getCanonicalType(CurClassType))); 4682 NameInfo.setLoc(Name.StartLocation); 4683 // FIXME: should we retrieve TypeSourceInfo? 4684 NameInfo.setNamedTypeInfo(nullptr); 4685 return NameInfo; 4686 } 4687 4688 case UnqualifiedId::IK_DestructorName: { 4689 TypeSourceInfo *TInfo; 4690 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4691 if (Ty.isNull()) 4692 return DeclarationNameInfo(); 4693 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4694 Context.getCanonicalType(Ty))); 4695 NameInfo.setLoc(Name.StartLocation); 4696 NameInfo.setNamedTypeInfo(TInfo); 4697 return NameInfo; 4698 } 4699 4700 case UnqualifiedId::IK_TemplateId: { 4701 TemplateName TName = Name.TemplateId->Template.get(); 4702 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4703 return Context.getNameForTemplate(TName, TNameLoc); 4704 } 4705 4706 } // switch (Name.getKind()) 4707 4708 llvm_unreachable("Unknown name kind"); 4709 } 4710 4711 static QualType getCoreType(QualType Ty) { 4712 do { 4713 if (Ty->isPointerType() || Ty->isReferenceType()) 4714 Ty = Ty->getPointeeType(); 4715 else if (Ty->isArrayType()) 4716 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4717 else 4718 return Ty.withoutLocalFastQualifiers(); 4719 } while (true); 4720 } 4721 4722 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4723 /// and Definition have "nearly" matching parameters. This heuristic is 4724 /// used to improve diagnostics in the case where an out-of-line function 4725 /// definition doesn't match any declaration within the class or namespace. 4726 /// Also sets Params to the list of indices to the parameters that differ 4727 /// between the declaration and the definition. If hasSimilarParameters 4728 /// returns true and Params is empty, then all of the parameters match. 4729 static bool hasSimilarParameters(ASTContext &Context, 4730 FunctionDecl *Declaration, 4731 FunctionDecl *Definition, 4732 SmallVectorImpl<unsigned> &Params) { 4733 Params.clear(); 4734 if (Declaration->param_size() != Definition->param_size()) 4735 return false; 4736 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4737 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4738 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4739 4740 // The parameter types are identical 4741 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4742 continue; 4743 4744 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4745 QualType DefParamBaseTy = getCoreType(DefParamTy); 4746 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4747 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4748 4749 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4750 (DeclTyName && DeclTyName == DefTyName)) 4751 Params.push_back(Idx); 4752 else // The two parameters aren't even close 4753 return false; 4754 } 4755 4756 return true; 4757 } 4758 4759 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4760 /// declarator needs to be rebuilt in the current instantiation. 4761 /// Any bits of declarator which appear before the name are valid for 4762 /// consideration here. That's specifically the type in the decl spec 4763 /// and the base type in any member-pointer chunks. 4764 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4765 DeclarationName Name) { 4766 // The types we specifically need to rebuild are: 4767 // - typenames, typeofs, and decltypes 4768 // - types which will become injected class names 4769 // Of course, we also need to rebuild any type referencing such a 4770 // type. It's safest to just say "dependent", but we call out a 4771 // few cases here. 4772 4773 DeclSpec &DS = D.getMutableDeclSpec(); 4774 switch (DS.getTypeSpecType()) { 4775 case DeclSpec::TST_typename: 4776 case DeclSpec::TST_typeofType: 4777 case DeclSpec::TST_underlyingType: 4778 case DeclSpec::TST_atomic: { 4779 // Grab the type from the parser. 4780 TypeSourceInfo *TSI = nullptr; 4781 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4782 if (T.isNull() || !T->isDependentType()) break; 4783 4784 // Make sure there's a type source info. This isn't really much 4785 // of a waste; most dependent types should have type source info 4786 // attached already. 4787 if (!TSI) 4788 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4789 4790 // Rebuild the type in the current instantiation. 4791 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4792 if (!TSI) return true; 4793 4794 // Store the new type back in the decl spec. 4795 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4796 DS.UpdateTypeRep(LocType); 4797 break; 4798 } 4799 4800 case DeclSpec::TST_decltype: 4801 case DeclSpec::TST_typeofExpr: { 4802 Expr *E = DS.getRepAsExpr(); 4803 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4804 if (Result.isInvalid()) return true; 4805 DS.UpdateExprRep(Result.get()); 4806 break; 4807 } 4808 4809 default: 4810 // Nothing to do for these decl specs. 4811 break; 4812 } 4813 4814 // It doesn't matter what order we do this in. 4815 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4816 DeclaratorChunk &Chunk = D.getTypeObject(I); 4817 4818 // The only type information in the declarator which can come 4819 // before the declaration name is the base type of a member 4820 // pointer. 4821 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4822 continue; 4823 4824 // Rebuild the scope specifier in-place. 4825 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4826 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4827 return true; 4828 } 4829 4830 return false; 4831 } 4832 4833 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4834 D.setFunctionDefinitionKind(FDK_Declaration); 4835 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4836 4837 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4838 Dcl && Dcl->getDeclContext()->isFileContext()) 4839 Dcl->setTopLevelDeclInObjCContainer(); 4840 4841 return Dcl; 4842 } 4843 4844 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4845 /// If T is the name of a class, then each of the following shall have a 4846 /// name different from T: 4847 /// - every static data member of class T; 4848 /// - every member function of class T 4849 /// - every member of class T that is itself a type; 4850 /// \returns true if the declaration name violates these rules. 4851 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4852 DeclarationNameInfo NameInfo) { 4853 DeclarationName Name = NameInfo.getName(); 4854 4855 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4856 while (Record && Record->isAnonymousStructOrUnion()) 4857 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4858 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4859 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4860 return true; 4861 } 4862 4863 return false; 4864 } 4865 4866 /// \brief Diagnose a declaration whose declarator-id has the given 4867 /// nested-name-specifier. 4868 /// 4869 /// \param SS The nested-name-specifier of the declarator-id. 4870 /// 4871 /// \param DC The declaration context to which the nested-name-specifier 4872 /// resolves. 4873 /// 4874 /// \param Name The name of the entity being declared. 4875 /// 4876 /// \param Loc The location of the name of the entity being declared. 4877 /// 4878 /// \returns true if we cannot safely recover from this error, false otherwise. 4879 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4880 DeclarationName Name, 4881 SourceLocation Loc) { 4882 DeclContext *Cur = CurContext; 4883 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4884 Cur = Cur->getParent(); 4885 4886 // If the user provided a superfluous scope specifier that refers back to the 4887 // class in which the entity is already declared, diagnose and ignore it. 4888 // 4889 // class X { 4890 // void X::f(); 4891 // }; 4892 // 4893 // Note, it was once ill-formed to give redundant qualification in all 4894 // contexts, but that rule was removed by DR482. 4895 if (Cur->Equals(DC)) { 4896 if (Cur->isRecord()) { 4897 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4898 : diag::err_member_extra_qualification) 4899 << Name << FixItHint::CreateRemoval(SS.getRange()); 4900 SS.clear(); 4901 } else { 4902 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4903 } 4904 return false; 4905 } 4906 4907 // Check whether the qualifying scope encloses the scope of the original 4908 // declaration. 4909 if (!Cur->Encloses(DC)) { 4910 if (Cur->isRecord()) 4911 Diag(Loc, diag::err_member_qualification) 4912 << Name << SS.getRange(); 4913 else if (isa<TranslationUnitDecl>(DC)) 4914 Diag(Loc, diag::err_invalid_declarator_global_scope) 4915 << Name << SS.getRange(); 4916 else if (isa<FunctionDecl>(Cur)) 4917 Diag(Loc, diag::err_invalid_declarator_in_function) 4918 << Name << SS.getRange(); 4919 else if (isa<BlockDecl>(Cur)) 4920 Diag(Loc, diag::err_invalid_declarator_in_block) 4921 << Name << SS.getRange(); 4922 else 4923 Diag(Loc, diag::err_invalid_declarator_scope) 4924 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4925 4926 return true; 4927 } 4928 4929 if (Cur->isRecord()) { 4930 // Cannot qualify members within a class. 4931 Diag(Loc, diag::err_member_qualification) 4932 << Name << SS.getRange(); 4933 SS.clear(); 4934 4935 // C++ constructors and destructors with incorrect scopes can break 4936 // our AST invariants by having the wrong underlying types. If 4937 // that's the case, then drop this declaration entirely. 4938 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4939 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4940 !Context.hasSameType(Name.getCXXNameType(), 4941 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4942 return true; 4943 4944 return false; 4945 } 4946 4947 // C++11 [dcl.meaning]p1: 4948 // [...] "The nested-name-specifier of the qualified declarator-id shall 4949 // not begin with a decltype-specifer" 4950 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4951 while (SpecLoc.getPrefix()) 4952 SpecLoc = SpecLoc.getPrefix(); 4953 if (dyn_cast_or_null<DecltypeType>( 4954 SpecLoc.getNestedNameSpecifier()->getAsType())) 4955 Diag(Loc, diag::err_decltype_in_declarator) 4956 << SpecLoc.getTypeLoc().getSourceRange(); 4957 4958 return false; 4959 } 4960 4961 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4962 MultiTemplateParamsArg TemplateParamLists) { 4963 // TODO: consider using NameInfo for diagnostic. 4964 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4965 DeclarationName Name = NameInfo.getName(); 4966 4967 // All of these full declarators require an identifier. If it doesn't have 4968 // one, the ParsedFreeStandingDeclSpec action should be used. 4969 if (D.isDecompositionDeclarator()) { 4970 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 4971 } else if (!Name) { 4972 if (!D.isInvalidType()) // Reject this if we think it is valid. 4973 Diag(D.getDeclSpec().getLocStart(), 4974 diag::err_declarator_need_ident) 4975 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4976 return nullptr; 4977 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4978 return nullptr; 4979 4980 // The scope passed in may not be a decl scope. Zip up the scope tree until 4981 // we find one that is. 4982 while ((S->getFlags() & Scope::DeclScope) == 0 || 4983 (S->getFlags() & Scope::TemplateParamScope) != 0) 4984 S = S->getParent(); 4985 4986 DeclContext *DC = CurContext; 4987 if (D.getCXXScopeSpec().isInvalid()) 4988 D.setInvalidType(); 4989 else if (D.getCXXScopeSpec().isSet()) { 4990 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4991 UPPC_DeclarationQualifier)) 4992 return nullptr; 4993 4994 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4995 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4996 if (!DC || isa<EnumDecl>(DC)) { 4997 // If we could not compute the declaration context, it's because the 4998 // declaration context is dependent but does not refer to a class, 4999 // class template, or class template partial specialization. Complain 5000 // and return early, to avoid the coming semantic disaster. 5001 Diag(D.getIdentifierLoc(), 5002 diag::err_template_qualified_declarator_no_match) 5003 << D.getCXXScopeSpec().getScopeRep() 5004 << D.getCXXScopeSpec().getRange(); 5005 return nullptr; 5006 } 5007 bool IsDependentContext = DC->isDependentContext(); 5008 5009 if (!IsDependentContext && 5010 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5011 return nullptr; 5012 5013 // If a class is incomplete, do not parse entities inside it. 5014 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5015 Diag(D.getIdentifierLoc(), 5016 diag::err_member_def_undefined_record) 5017 << Name << DC << D.getCXXScopeSpec().getRange(); 5018 return nullptr; 5019 } 5020 if (!D.getDeclSpec().isFriendSpecified()) { 5021 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5022 Name, D.getIdentifierLoc())) { 5023 if (DC->isRecord()) 5024 return nullptr; 5025 5026 D.setInvalidType(); 5027 } 5028 } 5029 5030 // Check whether we need to rebuild the type of the given 5031 // declaration in the current instantiation. 5032 if (EnteringContext && IsDependentContext && 5033 TemplateParamLists.size() != 0) { 5034 ContextRAII SavedContext(*this, DC); 5035 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5036 D.setInvalidType(); 5037 } 5038 } 5039 5040 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5041 QualType R = TInfo->getType(); 5042 5043 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5044 // If this is a typedef, we'll end up spewing multiple diagnostics. 5045 // Just return early; it's safer. If this is a function, let the 5046 // "constructor cannot have a return type" diagnostic handle it. 5047 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5048 return nullptr; 5049 5050 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5051 UPPC_DeclarationType)) 5052 D.setInvalidType(); 5053 5054 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5055 ForRedeclaration); 5056 5057 // See if this is a redefinition of a variable in the same scope. 5058 if (!D.getCXXScopeSpec().isSet()) { 5059 bool IsLinkageLookup = false; 5060 bool CreateBuiltins = false; 5061 5062 // If the declaration we're planning to build will be a function 5063 // or object with linkage, then look for another declaration with 5064 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5065 // 5066 // If the declaration we're planning to build will be declared with 5067 // external linkage in the translation unit, create any builtin with 5068 // the same name. 5069 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5070 /* Do nothing*/; 5071 else if (CurContext->isFunctionOrMethod() && 5072 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5073 R->isFunctionType())) { 5074 IsLinkageLookup = true; 5075 CreateBuiltins = 5076 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5077 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5078 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5079 CreateBuiltins = true; 5080 5081 if (IsLinkageLookup) 5082 Previous.clear(LookupRedeclarationWithLinkage); 5083 5084 LookupName(Previous, S, CreateBuiltins); 5085 } else { // Something like "int foo::x;" 5086 LookupQualifiedName(Previous, DC); 5087 5088 // C++ [dcl.meaning]p1: 5089 // When the declarator-id is qualified, the declaration shall refer to a 5090 // previously declared member of the class or namespace to which the 5091 // qualifier refers (or, in the case of a namespace, of an element of the 5092 // inline namespace set of that namespace (7.3.1)) or to a specialization 5093 // thereof; [...] 5094 // 5095 // Note that we already checked the context above, and that we do not have 5096 // enough information to make sure that Previous contains the declaration 5097 // we want to match. For example, given: 5098 // 5099 // class X { 5100 // void f(); 5101 // void f(float); 5102 // }; 5103 // 5104 // void X::f(int) { } // ill-formed 5105 // 5106 // In this case, Previous will point to the overload set 5107 // containing the two f's declared in X, but neither of them 5108 // matches. 5109 5110 // C++ [dcl.meaning]p1: 5111 // [...] the member shall not merely have been introduced by a 5112 // using-declaration in the scope of the class or namespace nominated by 5113 // the nested-name-specifier of the declarator-id. 5114 RemoveUsingDecls(Previous); 5115 } 5116 5117 if (Previous.isSingleResult() && 5118 Previous.getFoundDecl()->isTemplateParameter()) { 5119 // Maybe we will complain about the shadowed template parameter. 5120 if (!D.isInvalidType()) 5121 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5122 Previous.getFoundDecl()); 5123 5124 // Just pretend that we didn't see the previous declaration. 5125 Previous.clear(); 5126 } 5127 5128 // In C++, the previous declaration we find might be a tag type 5129 // (class or enum). In this case, the new declaration will hide the 5130 // tag type. Note that this does does not apply if we're declaring a 5131 // typedef (C++ [dcl.typedef]p4). 5132 if (Previous.isSingleTagDecl() && 5133 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5134 Previous.clear(); 5135 5136 // Check that there are no default arguments other than in the parameters 5137 // of a function declaration (C++ only). 5138 if (getLangOpts().CPlusPlus) 5139 CheckExtraCXXDefaultArguments(D); 5140 5141 if (D.getDeclSpec().isConceptSpecified()) { 5142 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5143 // applied only to the definition of a function template or variable 5144 // template, declared in namespace scope 5145 if (!TemplateParamLists.size()) { 5146 Diag(D.getDeclSpec().getConceptSpecLoc(), 5147 diag:: err_concept_wrong_decl_kind); 5148 return nullptr; 5149 } 5150 5151 if (!DC->getRedeclContext()->isFileContext()) { 5152 Diag(D.getIdentifierLoc(), 5153 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5154 return nullptr; 5155 } 5156 } 5157 5158 NamedDecl *New; 5159 5160 bool AddToScope = true; 5161 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5162 if (TemplateParamLists.size()) { 5163 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5164 return nullptr; 5165 } 5166 5167 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5168 } else if (R->isFunctionType()) { 5169 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5170 TemplateParamLists, 5171 AddToScope); 5172 } else { 5173 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5174 AddToScope); 5175 } 5176 5177 if (!New) 5178 return nullptr; 5179 5180 // If this has an identifier and is not a function template specialization, 5181 // add it to the scope stack. 5182 if (New->getDeclName() && AddToScope) { 5183 // Only make a locally-scoped extern declaration visible if it is the first 5184 // declaration of this entity. Qualified lookup for such an entity should 5185 // only find this declaration if there is no visible declaration of it. 5186 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5187 PushOnScopeChains(New, S, AddToContext); 5188 if (!AddToContext) 5189 CurContext->addHiddenDecl(New); 5190 } 5191 5192 if (isInOpenMPDeclareTargetContext()) 5193 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5194 5195 return New; 5196 } 5197 5198 /// Helper method to turn variable array types into constant array 5199 /// types in certain situations which would otherwise be errors (for 5200 /// GCC compatibility). 5201 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5202 ASTContext &Context, 5203 bool &SizeIsNegative, 5204 llvm::APSInt &Oversized) { 5205 // This method tries to turn a variable array into a constant 5206 // array even when the size isn't an ICE. This is necessary 5207 // for compatibility with code that depends on gcc's buggy 5208 // constant expression folding, like struct {char x[(int)(char*)2];} 5209 SizeIsNegative = false; 5210 Oversized = 0; 5211 5212 if (T->isDependentType()) 5213 return QualType(); 5214 5215 QualifierCollector Qs; 5216 const Type *Ty = Qs.strip(T); 5217 5218 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5219 QualType Pointee = PTy->getPointeeType(); 5220 QualType FixedType = 5221 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5222 Oversized); 5223 if (FixedType.isNull()) return FixedType; 5224 FixedType = Context.getPointerType(FixedType); 5225 return Qs.apply(Context, FixedType); 5226 } 5227 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5228 QualType Inner = PTy->getInnerType(); 5229 QualType FixedType = 5230 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5231 Oversized); 5232 if (FixedType.isNull()) return FixedType; 5233 FixedType = Context.getParenType(FixedType); 5234 return Qs.apply(Context, FixedType); 5235 } 5236 5237 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5238 if (!VLATy) 5239 return QualType(); 5240 // FIXME: We should probably handle this case 5241 if (VLATy->getElementType()->isVariablyModifiedType()) 5242 return QualType(); 5243 5244 llvm::APSInt Res; 5245 if (!VLATy->getSizeExpr() || 5246 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5247 return QualType(); 5248 5249 // Check whether the array size is negative. 5250 if (Res.isSigned() && Res.isNegative()) { 5251 SizeIsNegative = true; 5252 return QualType(); 5253 } 5254 5255 // Check whether the array is too large to be addressed. 5256 unsigned ActiveSizeBits 5257 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5258 Res); 5259 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5260 Oversized = Res; 5261 return QualType(); 5262 } 5263 5264 return Context.getConstantArrayType(VLATy->getElementType(), 5265 Res, ArrayType::Normal, 0); 5266 } 5267 5268 static void 5269 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5270 SrcTL = SrcTL.getUnqualifiedLoc(); 5271 DstTL = DstTL.getUnqualifiedLoc(); 5272 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5273 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5274 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5275 DstPTL.getPointeeLoc()); 5276 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5277 return; 5278 } 5279 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5280 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5281 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5282 DstPTL.getInnerLoc()); 5283 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5284 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5285 return; 5286 } 5287 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5288 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5289 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5290 TypeLoc DstElemTL = DstATL.getElementLoc(); 5291 DstElemTL.initializeFullCopy(SrcElemTL); 5292 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5293 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5294 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5295 } 5296 5297 /// Helper method to turn variable array types into constant array 5298 /// types in certain situations which would otherwise be errors (for 5299 /// GCC compatibility). 5300 static TypeSourceInfo* 5301 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5302 ASTContext &Context, 5303 bool &SizeIsNegative, 5304 llvm::APSInt &Oversized) { 5305 QualType FixedTy 5306 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5307 SizeIsNegative, Oversized); 5308 if (FixedTy.isNull()) 5309 return nullptr; 5310 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5311 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5312 FixedTInfo->getTypeLoc()); 5313 return FixedTInfo; 5314 } 5315 5316 /// \brief Register the given locally-scoped extern "C" declaration so 5317 /// that it can be found later for redeclarations. We include any extern "C" 5318 /// declaration that is not visible in the translation unit here, not just 5319 /// function-scope declarations. 5320 void 5321 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5322 if (!getLangOpts().CPlusPlus && 5323 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5324 // Don't need to track declarations in the TU in C. 5325 return; 5326 5327 // Note that we have a locally-scoped external with this name. 5328 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5329 } 5330 5331 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5332 // FIXME: We can have multiple results via __attribute__((overloadable)). 5333 auto Result = Context.getExternCContextDecl()->lookup(Name); 5334 return Result.empty() ? nullptr : *Result.begin(); 5335 } 5336 5337 /// \brief Diagnose function specifiers on a declaration of an identifier that 5338 /// does not identify a function. 5339 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5340 // FIXME: We should probably indicate the identifier in question to avoid 5341 // confusion for constructs like "virtual int a(), b;" 5342 if (DS.isVirtualSpecified()) 5343 Diag(DS.getVirtualSpecLoc(), 5344 diag::err_virtual_non_function); 5345 5346 if (DS.isExplicitSpecified()) 5347 Diag(DS.getExplicitSpecLoc(), 5348 diag::err_explicit_non_function); 5349 5350 if (DS.isNoreturnSpecified()) 5351 Diag(DS.getNoreturnSpecLoc(), 5352 diag::err_noreturn_non_function); 5353 } 5354 5355 NamedDecl* 5356 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5357 TypeSourceInfo *TInfo, LookupResult &Previous) { 5358 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5359 if (D.getCXXScopeSpec().isSet()) { 5360 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5361 << D.getCXXScopeSpec().getRange(); 5362 D.setInvalidType(); 5363 // Pretend we didn't see the scope specifier. 5364 DC = CurContext; 5365 Previous.clear(); 5366 } 5367 5368 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5369 5370 if (D.getDeclSpec().isInlineSpecified()) 5371 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5372 << getLangOpts().CPlusPlus1z; 5373 if (D.getDeclSpec().isConstexprSpecified()) 5374 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5375 << 1; 5376 if (D.getDeclSpec().isConceptSpecified()) 5377 Diag(D.getDeclSpec().getConceptSpecLoc(), 5378 diag::err_concept_wrong_decl_kind); 5379 5380 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5381 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5382 << D.getName().getSourceRange(); 5383 return nullptr; 5384 } 5385 5386 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5387 if (!NewTD) return nullptr; 5388 5389 // Handle attributes prior to checking for duplicates in MergeVarDecl 5390 ProcessDeclAttributes(S, NewTD, D); 5391 5392 CheckTypedefForVariablyModifiedType(S, NewTD); 5393 5394 bool Redeclaration = D.isRedeclaration(); 5395 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5396 D.setRedeclaration(Redeclaration); 5397 return ND; 5398 } 5399 5400 void 5401 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5402 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5403 // then it shall have block scope. 5404 // Note that variably modified types must be fixed before merging the decl so 5405 // that redeclarations will match. 5406 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5407 QualType T = TInfo->getType(); 5408 if (T->isVariablyModifiedType()) { 5409 getCurFunction()->setHasBranchProtectedScope(); 5410 5411 if (S->getFnParent() == nullptr) { 5412 bool SizeIsNegative; 5413 llvm::APSInt Oversized; 5414 TypeSourceInfo *FixedTInfo = 5415 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5416 SizeIsNegative, 5417 Oversized); 5418 if (FixedTInfo) { 5419 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5420 NewTD->setTypeSourceInfo(FixedTInfo); 5421 } else { 5422 if (SizeIsNegative) 5423 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5424 else if (T->isVariableArrayType()) 5425 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5426 else if (Oversized.getBoolValue()) 5427 Diag(NewTD->getLocation(), diag::err_array_too_large) 5428 << Oversized.toString(10); 5429 else 5430 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5431 NewTD->setInvalidDecl(); 5432 } 5433 } 5434 } 5435 } 5436 5437 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5438 /// declares a typedef-name, either using the 'typedef' type specifier or via 5439 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5440 NamedDecl* 5441 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5442 LookupResult &Previous, bool &Redeclaration) { 5443 // Merge the decl with the existing one if appropriate. If the decl is 5444 // in an outer scope, it isn't the same thing. 5445 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5446 /*AllowInlineNamespace*/false); 5447 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5448 if (!Previous.empty()) { 5449 Redeclaration = true; 5450 MergeTypedefNameDecl(S, NewTD, Previous); 5451 } 5452 5453 // If this is the C FILE type, notify the AST context. 5454 if (IdentifierInfo *II = NewTD->getIdentifier()) 5455 if (!NewTD->isInvalidDecl() && 5456 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5457 if (II->isStr("FILE")) 5458 Context.setFILEDecl(NewTD); 5459 else if (II->isStr("jmp_buf")) 5460 Context.setjmp_bufDecl(NewTD); 5461 else if (II->isStr("sigjmp_buf")) 5462 Context.setsigjmp_bufDecl(NewTD); 5463 else if (II->isStr("ucontext_t")) 5464 Context.setucontext_tDecl(NewTD); 5465 } 5466 5467 return NewTD; 5468 } 5469 5470 /// \brief Determines whether the given declaration is an out-of-scope 5471 /// previous declaration. 5472 /// 5473 /// This routine should be invoked when name lookup has found a 5474 /// previous declaration (PrevDecl) that is not in the scope where a 5475 /// new declaration by the same name is being introduced. If the new 5476 /// declaration occurs in a local scope, previous declarations with 5477 /// linkage may still be considered previous declarations (C99 5478 /// 6.2.2p4-5, C++ [basic.link]p6). 5479 /// 5480 /// \param PrevDecl the previous declaration found by name 5481 /// lookup 5482 /// 5483 /// \param DC the context in which the new declaration is being 5484 /// declared. 5485 /// 5486 /// \returns true if PrevDecl is an out-of-scope previous declaration 5487 /// for a new delcaration with the same name. 5488 static bool 5489 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5490 ASTContext &Context) { 5491 if (!PrevDecl) 5492 return false; 5493 5494 if (!PrevDecl->hasLinkage()) 5495 return false; 5496 5497 if (Context.getLangOpts().CPlusPlus) { 5498 // C++ [basic.link]p6: 5499 // If there is a visible declaration of an entity with linkage 5500 // having the same name and type, ignoring entities declared 5501 // outside the innermost enclosing namespace scope, the block 5502 // scope declaration declares that same entity and receives the 5503 // linkage of the previous declaration. 5504 DeclContext *OuterContext = DC->getRedeclContext(); 5505 if (!OuterContext->isFunctionOrMethod()) 5506 // This rule only applies to block-scope declarations. 5507 return false; 5508 5509 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5510 if (PrevOuterContext->isRecord()) 5511 // We found a member function: ignore it. 5512 return false; 5513 5514 // Find the innermost enclosing namespace for the new and 5515 // previous declarations. 5516 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5517 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5518 5519 // The previous declaration is in a different namespace, so it 5520 // isn't the same function. 5521 if (!OuterContext->Equals(PrevOuterContext)) 5522 return false; 5523 } 5524 5525 return true; 5526 } 5527 5528 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5529 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5530 if (!SS.isSet()) return; 5531 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5532 } 5533 5534 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5535 QualType type = decl->getType(); 5536 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5537 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5538 // Various kinds of declaration aren't allowed to be __autoreleasing. 5539 unsigned kind = -1U; 5540 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5541 if (var->hasAttr<BlocksAttr>()) 5542 kind = 0; // __block 5543 else if (!var->hasLocalStorage()) 5544 kind = 1; // global 5545 } else if (isa<ObjCIvarDecl>(decl)) { 5546 kind = 3; // ivar 5547 } else if (isa<FieldDecl>(decl)) { 5548 kind = 2; // field 5549 } 5550 5551 if (kind != -1U) { 5552 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5553 << kind; 5554 } 5555 } else if (lifetime == Qualifiers::OCL_None) { 5556 // Try to infer lifetime. 5557 if (!type->isObjCLifetimeType()) 5558 return false; 5559 5560 lifetime = type->getObjCARCImplicitLifetime(); 5561 type = Context.getLifetimeQualifiedType(type, lifetime); 5562 decl->setType(type); 5563 } 5564 5565 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5566 // Thread-local variables cannot have lifetime. 5567 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5568 var->getTLSKind()) { 5569 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5570 << var->getType(); 5571 return true; 5572 } 5573 } 5574 5575 return false; 5576 } 5577 5578 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5579 // Ensure that an auto decl is deduced otherwise the checks below might cache 5580 // the wrong linkage. 5581 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5582 5583 // 'weak' only applies to declarations with external linkage. 5584 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5585 if (!ND.isExternallyVisible()) { 5586 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5587 ND.dropAttr<WeakAttr>(); 5588 } 5589 } 5590 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5591 if (ND.isExternallyVisible()) { 5592 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5593 ND.dropAttr<WeakRefAttr>(); 5594 ND.dropAttr<AliasAttr>(); 5595 } 5596 } 5597 5598 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5599 if (VD->hasInit()) { 5600 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5601 assert(VD->isThisDeclarationADefinition() && 5602 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5603 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5604 VD->dropAttr<AliasAttr>(); 5605 } 5606 } 5607 } 5608 5609 // 'selectany' only applies to externally visible variable declarations. 5610 // It does not apply to functions. 5611 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5612 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5613 S.Diag(Attr->getLocation(), 5614 diag::err_attribute_selectany_non_extern_data); 5615 ND.dropAttr<SelectAnyAttr>(); 5616 } 5617 } 5618 5619 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5620 // dll attributes require external linkage. Static locals may have external 5621 // linkage but still cannot be explicitly imported or exported. 5622 auto *VD = dyn_cast<VarDecl>(&ND); 5623 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5624 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5625 << &ND << Attr; 5626 ND.setInvalidDecl(); 5627 } 5628 } 5629 5630 // Virtual functions cannot be marked as 'notail'. 5631 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5632 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5633 if (MD->isVirtual()) { 5634 S.Diag(ND.getLocation(), 5635 diag::err_invalid_attribute_on_virtual_function) 5636 << Attr; 5637 ND.dropAttr<NotTailCalledAttr>(); 5638 } 5639 } 5640 5641 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5642 NamedDecl *NewDecl, 5643 bool IsSpecialization, 5644 bool IsDefinition) { 5645 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5646 OldDecl = OldTD->getTemplatedDecl(); 5647 if (!IsSpecialization) 5648 IsDefinition = false; 5649 } 5650 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5651 NewDecl = NewTD->getTemplatedDecl(); 5652 5653 if (!OldDecl || !NewDecl) 5654 return; 5655 5656 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5657 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5658 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5659 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5660 5661 // dllimport and dllexport are inheritable attributes so we have to exclude 5662 // inherited attribute instances. 5663 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5664 (NewExportAttr && !NewExportAttr->isInherited()); 5665 5666 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5667 // the only exception being explicit specializations. 5668 // Implicitly generated declarations are also excluded for now because there 5669 // is no other way to switch these to use dllimport or dllexport. 5670 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5671 5672 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5673 // Allow with a warning for free functions and global variables. 5674 bool JustWarn = false; 5675 if (!OldDecl->isCXXClassMember()) { 5676 auto *VD = dyn_cast<VarDecl>(OldDecl); 5677 if (VD && !VD->getDescribedVarTemplate()) 5678 JustWarn = true; 5679 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5680 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5681 JustWarn = true; 5682 } 5683 5684 // We cannot change a declaration that's been used because IR has already 5685 // been emitted. Dllimported functions will still work though (modulo 5686 // address equality) as they can use the thunk. 5687 if (OldDecl->isUsed()) 5688 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5689 JustWarn = false; 5690 5691 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5692 : diag::err_attribute_dll_redeclaration; 5693 S.Diag(NewDecl->getLocation(), DiagID) 5694 << NewDecl 5695 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5696 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5697 if (!JustWarn) { 5698 NewDecl->setInvalidDecl(); 5699 return; 5700 } 5701 } 5702 5703 // A redeclaration is not allowed to drop a dllimport attribute, the only 5704 // exceptions being inline function definitions, local extern declarations, 5705 // qualified friend declarations or special MSVC extension: in the last case, 5706 // the declaration is treated as if it were marked dllexport. 5707 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5708 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5709 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5710 // Ignore static data because out-of-line definitions are diagnosed 5711 // separately. 5712 IsStaticDataMember = VD->isStaticDataMember(); 5713 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5714 VarDecl::DeclarationOnly; 5715 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5716 IsInline = FD->isInlined(); 5717 IsQualifiedFriend = FD->getQualifier() && 5718 FD->getFriendObjectKind() == Decl::FOK_Declared; 5719 } 5720 5721 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5722 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5723 if (IsMicrosoft && IsDefinition) { 5724 S.Diag(NewDecl->getLocation(), 5725 diag::warn_redeclaration_without_import_attribute) 5726 << NewDecl; 5727 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5728 NewDecl->dropAttr<DLLImportAttr>(); 5729 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5730 NewImportAttr->getRange(), S.Context, 5731 NewImportAttr->getSpellingListIndex())); 5732 } else { 5733 S.Diag(NewDecl->getLocation(), 5734 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5735 << NewDecl << OldImportAttr; 5736 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5737 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5738 OldDecl->dropAttr<DLLImportAttr>(); 5739 NewDecl->dropAttr<DLLImportAttr>(); 5740 } 5741 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5742 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5743 OldDecl->dropAttr<DLLImportAttr>(); 5744 NewDecl->dropAttr<DLLImportAttr>(); 5745 S.Diag(NewDecl->getLocation(), 5746 diag::warn_dllimport_dropped_from_inline_function) 5747 << NewDecl << OldImportAttr; 5748 } 5749 } 5750 5751 /// Given that we are within the definition of the given function, 5752 /// will that definition behave like C99's 'inline', where the 5753 /// definition is discarded except for optimization purposes? 5754 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5755 // Try to avoid calling GetGVALinkageForFunction. 5756 5757 // All cases of this require the 'inline' keyword. 5758 if (!FD->isInlined()) return false; 5759 5760 // This is only possible in C++ with the gnu_inline attribute. 5761 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5762 return false; 5763 5764 // Okay, go ahead and call the relatively-more-expensive function. 5765 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5766 } 5767 5768 /// Determine whether a variable is extern "C" prior to attaching 5769 /// an initializer. We can't just call isExternC() here, because that 5770 /// will also compute and cache whether the declaration is externally 5771 /// visible, which might change when we attach the initializer. 5772 /// 5773 /// This can only be used if the declaration is known to not be a 5774 /// redeclaration of an internal linkage declaration. 5775 /// 5776 /// For instance: 5777 /// 5778 /// auto x = []{}; 5779 /// 5780 /// Attaching the initializer here makes this declaration not externally 5781 /// visible, because its type has internal linkage. 5782 /// 5783 /// FIXME: This is a hack. 5784 template<typename T> 5785 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5786 if (S.getLangOpts().CPlusPlus) { 5787 // In C++, the overloadable attribute negates the effects of extern "C". 5788 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5789 return false; 5790 5791 // So do CUDA's host/device attributes. 5792 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 5793 D->template hasAttr<CUDAHostAttr>())) 5794 return false; 5795 } 5796 return D->isExternC(); 5797 } 5798 5799 static bool shouldConsiderLinkage(const VarDecl *VD) { 5800 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5801 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 5802 return VD->hasExternalStorage(); 5803 if (DC->isFileContext()) 5804 return true; 5805 if (DC->isRecord()) 5806 return false; 5807 llvm_unreachable("Unexpected context"); 5808 } 5809 5810 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5811 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5812 if (DC->isFileContext() || DC->isFunctionOrMethod() || 5813 isa<OMPDeclareReductionDecl>(DC)) 5814 return true; 5815 if (DC->isRecord()) 5816 return false; 5817 llvm_unreachable("Unexpected context"); 5818 } 5819 5820 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5821 AttributeList::Kind Kind) { 5822 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5823 if (L->getKind() == Kind) 5824 return true; 5825 return false; 5826 } 5827 5828 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5829 AttributeList::Kind Kind) { 5830 // Check decl attributes on the DeclSpec. 5831 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5832 return true; 5833 5834 // Walk the declarator structure, checking decl attributes that were in a type 5835 // position to the decl itself. 5836 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5837 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5838 return true; 5839 } 5840 5841 // Finally, check attributes on the decl itself. 5842 return hasParsedAttr(S, PD.getAttributes(), Kind); 5843 } 5844 5845 /// Adjust the \c DeclContext for a function or variable that might be a 5846 /// function-local external declaration. 5847 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5848 if (!DC->isFunctionOrMethod()) 5849 return false; 5850 5851 // If this is a local extern function or variable declared within a function 5852 // template, don't add it into the enclosing namespace scope until it is 5853 // instantiated; it might have a dependent type right now. 5854 if (DC->isDependentContext()) 5855 return true; 5856 5857 // C++11 [basic.link]p7: 5858 // When a block scope declaration of an entity with linkage is not found to 5859 // refer to some other declaration, then that entity is a member of the 5860 // innermost enclosing namespace. 5861 // 5862 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5863 // semantically-enclosing namespace, not a lexically-enclosing one. 5864 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5865 DC = DC->getParent(); 5866 return true; 5867 } 5868 5869 /// \brief Returns true if given declaration has external C language linkage. 5870 static bool isDeclExternC(const Decl *D) { 5871 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5872 return FD->isExternC(); 5873 if (const auto *VD = dyn_cast<VarDecl>(D)) 5874 return VD->isExternC(); 5875 5876 llvm_unreachable("Unknown type of decl!"); 5877 } 5878 5879 NamedDecl *Sema::ActOnVariableDeclarator( 5880 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 5881 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 5882 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 5883 QualType R = TInfo->getType(); 5884 DeclarationName Name = GetNameForDeclarator(D).getName(); 5885 5886 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5887 5888 if (D.isDecompositionDeclarator()) { 5889 AddToScope = false; 5890 // Take the name of the first declarator as our name for diagnostic 5891 // purposes. 5892 auto &Decomp = D.getDecompositionDeclarator(); 5893 if (!Decomp.bindings().empty()) { 5894 II = Decomp.bindings()[0].Name; 5895 Name = II; 5896 } 5897 } else if (!II) { 5898 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5899 << Name; 5900 return nullptr; 5901 } 5902 5903 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 5904 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 5905 // argument. 5906 if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) { 5907 Diag(D.getIdentifierLoc(), 5908 diag::err_opencl_type_can_only_be_used_as_function_parameter) 5909 << R; 5910 D.setInvalidType(); 5911 return nullptr; 5912 } 5913 5914 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5915 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5916 5917 // dllimport globals without explicit storage class are treated as extern. We 5918 // have to change the storage class this early to get the right DeclContext. 5919 if (SC == SC_None && !DC->isRecord() && 5920 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5921 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5922 SC = SC_Extern; 5923 5924 DeclContext *OriginalDC = DC; 5925 bool IsLocalExternDecl = SC == SC_Extern && 5926 adjustContextForLocalExternDecl(DC); 5927 5928 if (getLangOpts().OpenCL) { 5929 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5930 QualType NR = R; 5931 while (NR->isPointerType()) { 5932 if (NR->isFunctionPointerType()) { 5933 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5934 D.setInvalidType(); 5935 break; 5936 } 5937 NR = NR->getPointeeType(); 5938 } 5939 5940 if (!getOpenCLOptions().cl_khr_fp16) { 5941 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5942 // half array type (unless the cl_khr_fp16 extension is enabled). 5943 if (Context.getBaseElementType(R)->isHalfType()) { 5944 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5945 D.setInvalidType(); 5946 } 5947 } 5948 } 5949 5950 if (SCSpec == DeclSpec::SCS_mutable) { 5951 // mutable can only appear on non-static class members, so it's always 5952 // an error here 5953 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5954 D.setInvalidType(); 5955 SC = SC_None; 5956 } 5957 5958 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5959 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5960 D.getDeclSpec().getStorageClassSpecLoc())) { 5961 // In C++11, the 'register' storage class specifier is deprecated. 5962 // Suppress the warning in system macros, it's used in macros in some 5963 // popular C system headers, such as in glibc's htonl() macro. 5964 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5965 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 5966 : diag::warn_deprecated_register) 5967 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5968 } 5969 5970 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5971 5972 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5973 // C99 6.9p2: The storage-class specifiers auto and register shall not 5974 // appear in the declaration specifiers in an external declaration. 5975 // Global Register+Asm is a GNU extension we support. 5976 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5977 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5978 D.setInvalidType(); 5979 } 5980 } 5981 5982 if (getLangOpts().OpenCL) { 5983 // OpenCL v1.2 s6.9.b p4: 5984 // The sampler type cannot be used with the __local and __global address 5985 // space qualifiers. 5986 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5987 R.getAddressSpace() == LangAS::opencl_global)) { 5988 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5989 } 5990 5991 // OpenCL 1.2 spec, p6.9 r: 5992 // The event type cannot be used to declare a program scope variable. 5993 // The event type cannot be used with the __local, __constant and __global 5994 // address space qualifiers. 5995 if (R->isEventT()) { 5996 if (S->getParent() == nullptr) { 5997 Diag(D.getLocStart(), diag::err_event_t_global_var); 5998 D.setInvalidType(); 5999 } 6000 6001 if (R.getAddressSpace()) { 6002 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6003 D.setInvalidType(); 6004 } 6005 } 6006 } 6007 6008 bool IsExplicitSpecialization = false; 6009 bool IsVariableTemplateSpecialization = false; 6010 bool IsPartialSpecialization = false; 6011 bool IsVariableTemplate = false; 6012 VarDecl *NewVD = nullptr; 6013 VarTemplateDecl *NewTemplate = nullptr; 6014 TemplateParameterList *TemplateParams = nullptr; 6015 if (!getLangOpts().CPlusPlus) { 6016 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6017 D.getIdentifierLoc(), II, 6018 R, TInfo, SC); 6019 6020 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6021 ParsingInitForAutoVars.insert(NewVD); 6022 6023 if (D.isInvalidType()) 6024 NewVD->setInvalidDecl(); 6025 } else { 6026 bool Invalid = false; 6027 6028 if (DC->isRecord() && !CurContext->isRecord()) { 6029 // This is an out-of-line definition of a static data member. 6030 switch (SC) { 6031 case SC_None: 6032 break; 6033 case SC_Static: 6034 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6035 diag::err_static_out_of_line) 6036 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6037 break; 6038 case SC_Auto: 6039 case SC_Register: 6040 case SC_Extern: 6041 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6042 // to names of variables declared in a block or to function parameters. 6043 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6044 // of class members 6045 6046 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6047 diag::err_storage_class_for_static_member) 6048 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6049 break; 6050 case SC_PrivateExtern: 6051 llvm_unreachable("C storage class in c++!"); 6052 } 6053 } 6054 6055 if (SC == SC_Static && CurContext->isRecord()) { 6056 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6057 if (RD->isLocalClass()) 6058 Diag(D.getIdentifierLoc(), 6059 diag::err_static_data_member_not_allowed_in_local_class) 6060 << Name << RD->getDeclName(); 6061 6062 // C++98 [class.union]p1: If a union contains a static data member, 6063 // the program is ill-formed. C++11 drops this restriction. 6064 if (RD->isUnion()) 6065 Diag(D.getIdentifierLoc(), 6066 getLangOpts().CPlusPlus11 6067 ? diag::warn_cxx98_compat_static_data_member_in_union 6068 : diag::ext_static_data_member_in_union) << Name; 6069 // We conservatively disallow static data members in anonymous structs. 6070 else if (!RD->getDeclName()) 6071 Diag(D.getIdentifierLoc(), 6072 diag::err_static_data_member_not_allowed_in_anon_struct) 6073 << Name << RD->isUnion(); 6074 } 6075 } 6076 6077 // Match up the template parameter lists with the scope specifier, then 6078 // determine whether we have a template or a template specialization. 6079 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6080 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6081 D.getCXXScopeSpec(), 6082 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6083 ? D.getName().TemplateId 6084 : nullptr, 6085 TemplateParamLists, 6086 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 6087 6088 if (TemplateParams) { 6089 if (!TemplateParams->size() && 6090 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6091 // There is an extraneous 'template<>' for this variable. Complain 6092 // about it, but allow the declaration of the variable. 6093 Diag(TemplateParams->getTemplateLoc(), 6094 diag::err_template_variable_noparams) 6095 << II 6096 << SourceRange(TemplateParams->getTemplateLoc(), 6097 TemplateParams->getRAngleLoc()); 6098 TemplateParams = nullptr; 6099 } else { 6100 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6101 // This is an explicit specialization or a partial specialization. 6102 // FIXME: Check that we can declare a specialization here. 6103 IsVariableTemplateSpecialization = true; 6104 IsPartialSpecialization = TemplateParams->size() > 0; 6105 } else { // if (TemplateParams->size() > 0) 6106 // This is a template declaration. 6107 IsVariableTemplate = true; 6108 6109 // Check that we can declare a template here. 6110 if (CheckTemplateDeclScope(S, TemplateParams)) 6111 return nullptr; 6112 6113 // Only C++1y supports variable templates (N3651). 6114 Diag(D.getIdentifierLoc(), 6115 getLangOpts().CPlusPlus14 6116 ? diag::warn_cxx11_compat_variable_template 6117 : diag::ext_variable_template); 6118 } 6119 } 6120 } else { 6121 assert( 6122 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6123 "should have a 'template<>' for this decl"); 6124 } 6125 6126 if (IsVariableTemplateSpecialization) { 6127 SourceLocation TemplateKWLoc = 6128 TemplateParamLists.size() > 0 6129 ? TemplateParamLists[0]->getTemplateLoc() 6130 : SourceLocation(); 6131 DeclResult Res = ActOnVarTemplateSpecialization( 6132 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6133 IsPartialSpecialization); 6134 if (Res.isInvalid()) 6135 return nullptr; 6136 NewVD = cast<VarDecl>(Res.get()); 6137 AddToScope = false; 6138 } else if (D.isDecompositionDeclarator()) { 6139 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6140 D.getIdentifierLoc(), R, TInfo, SC, 6141 Bindings); 6142 } else 6143 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6144 D.getIdentifierLoc(), II, R, TInfo, SC); 6145 6146 // If this is supposed to be a variable template, create it as such. 6147 if (IsVariableTemplate) { 6148 NewTemplate = 6149 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6150 TemplateParams, NewVD); 6151 NewVD->setDescribedVarTemplate(NewTemplate); 6152 } 6153 6154 // If this decl has an auto type in need of deduction, make a note of the 6155 // Decl so we can diagnose uses of it in its own initializer. 6156 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6157 ParsingInitForAutoVars.insert(NewVD); 6158 6159 if (D.isInvalidType() || Invalid) { 6160 NewVD->setInvalidDecl(); 6161 if (NewTemplate) 6162 NewTemplate->setInvalidDecl(); 6163 } 6164 6165 SetNestedNameSpecifier(NewVD, D); 6166 6167 // If we have any template parameter lists that don't directly belong to 6168 // the variable (matching the scope specifier), store them. 6169 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6170 if (TemplateParamLists.size() > VDTemplateParamLists) 6171 NewVD->setTemplateParameterListsInfo( 6172 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6173 6174 if (D.getDeclSpec().isConstexprSpecified()) { 6175 NewVD->setConstexpr(true); 6176 // C++1z [dcl.spec.constexpr]p1: 6177 // A static data member declared with the constexpr specifier is 6178 // implicitly an inline variable. 6179 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6180 NewVD->setImplicitlyInline(); 6181 } 6182 6183 if (D.getDeclSpec().isConceptSpecified()) { 6184 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6185 VTD->setConcept(); 6186 6187 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6188 // be declared with the thread_local, inline, friend, or constexpr 6189 // specifiers, [...] 6190 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6191 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6192 diag::err_concept_decl_invalid_specifiers) 6193 << 0 << 0; 6194 NewVD->setInvalidDecl(true); 6195 } 6196 6197 if (D.getDeclSpec().isConstexprSpecified()) { 6198 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6199 diag::err_concept_decl_invalid_specifiers) 6200 << 0 << 3; 6201 NewVD->setInvalidDecl(true); 6202 } 6203 6204 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6205 // applied only to the definition of a function template or variable 6206 // template, declared in namespace scope. 6207 if (IsVariableTemplateSpecialization) { 6208 Diag(D.getDeclSpec().getConceptSpecLoc(), 6209 diag::err_concept_specified_specialization) 6210 << (IsPartialSpecialization ? 2 : 1); 6211 } 6212 6213 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6214 // following restrictions: 6215 // - The declared type shall have the type bool. 6216 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6217 !NewVD->isInvalidDecl()) { 6218 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6219 NewVD->setInvalidDecl(true); 6220 } 6221 } 6222 } 6223 6224 if (D.getDeclSpec().isInlineSpecified()) { 6225 if (!getLangOpts().CPlusPlus) { 6226 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6227 << 0; 6228 } else if (CurContext->isFunctionOrMethod()) { 6229 // 'inline' is not allowed on block scope variable declaration. 6230 Diag(D.getDeclSpec().getInlineSpecLoc(), 6231 diag::err_inline_declaration_block_scope) << Name 6232 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6233 } else { 6234 Diag(D.getDeclSpec().getInlineSpecLoc(), 6235 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6236 : diag::ext_inline_variable); 6237 NewVD->setInlineSpecified(); 6238 } 6239 } 6240 6241 // Set the lexical context. If the declarator has a C++ scope specifier, the 6242 // lexical context will be different from the semantic context. 6243 NewVD->setLexicalDeclContext(CurContext); 6244 if (NewTemplate) 6245 NewTemplate->setLexicalDeclContext(CurContext); 6246 6247 if (IsLocalExternDecl) { 6248 if (D.isDecompositionDeclarator()) 6249 for (auto *B : Bindings) 6250 B->setLocalExternDecl(); 6251 else 6252 NewVD->setLocalExternDecl(); 6253 } 6254 6255 bool EmitTLSUnsupportedError = false; 6256 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6257 // C++11 [dcl.stc]p4: 6258 // When thread_local is applied to a variable of block scope the 6259 // storage-class-specifier static is implied if it does not appear 6260 // explicitly. 6261 // Core issue: 'static' is not implied if the variable is declared 6262 // 'extern'. 6263 if (NewVD->hasLocalStorage() && 6264 (SCSpec != DeclSpec::SCS_unspecified || 6265 TSCS != DeclSpec::TSCS_thread_local || 6266 !DC->isFunctionOrMethod())) 6267 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6268 diag::err_thread_non_global) 6269 << DeclSpec::getSpecifierName(TSCS); 6270 else if (!Context.getTargetInfo().isTLSSupported()) { 6271 if (getLangOpts().CUDA) { 6272 // Postpone error emission until we've collected attributes required to 6273 // figure out whether it's a host or device variable and whether the 6274 // error should be ignored. 6275 EmitTLSUnsupportedError = true; 6276 // We still need to mark the variable as TLS so it shows up in AST with 6277 // proper storage class for other tools to use even if we're not going 6278 // to emit any code for it. 6279 NewVD->setTSCSpec(TSCS); 6280 } else 6281 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6282 diag::err_thread_unsupported); 6283 } else 6284 NewVD->setTSCSpec(TSCS); 6285 } 6286 6287 // C99 6.7.4p3 6288 // An inline definition of a function with external linkage shall 6289 // not contain a definition of a modifiable object with static or 6290 // thread storage duration... 6291 // We only apply this when the function is required to be defined 6292 // elsewhere, i.e. when the function is not 'extern inline'. Note 6293 // that a local variable with thread storage duration still has to 6294 // be marked 'static'. Also note that it's possible to get these 6295 // semantics in C++ using __attribute__((gnu_inline)). 6296 if (SC == SC_Static && S->getFnParent() != nullptr && 6297 !NewVD->getType().isConstQualified()) { 6298 FunctionDecl *CurFD = getCurFunctionDecl(); 6299 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6300 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6301 diag::warn_static_local_in_extern_inline); 6302 MaybeSuggestAddingStaticToDecl(CurFD); 6303 } 6304 } 6305 6306 if (D.getDeclSpec().isModulePrivateSpecified()) { 6307 if (IsVariableTemplateSpecialization) 6308 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6309 << (IsPartialSpecialization ? 1 : 0) 6310 << FixItHint::CreateRemoval( 6311 D.getDeclSpec().getModulePrivateSpecLoc()); 6312 else if (IsExplicitSpecialization) 6313 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6314 << 2 6315 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6316 else if (NewVD->hasLocalStorage()) 6317 Diag(NewVD->getLocation(), diag::err_module_private_local) 6318 << 0 << NewVD->getDeclName() 6319 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6320 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6321 else { 6322 NewVD->setModulePrivate(); 6323 if (NewTemplate) 6324 NewTemplate->setModulePrivate(); 6325 for (auto *B : Bindings) 6326 B->setModulePrivate(); 6327 } 6328 } 6329 6330 // Handle attributes prior to checking for duplicates in MergeVarDecl 6331 ProcessDeclAttributes(S, NewVD, D); 6332 6333 if (getLangOpts().CUDA) { 6334 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6335 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6336 diag::err_thread_unsupported); 6337 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6338 // storage [duration]." 6339 if (SC == SC_None && S->getFnParent() != nullptr && 6340 (NewVD->hasAttr<CUDASharedAttr>() || 6341 NewVD->hasAttr<CUDAConstantAttr>())) { 6342 NewVD->setStorageClass(SC_Static); 6343 } 6344 } 6345 6346 // Ensure that dllimport globals without explicit storage class are treated as 6347 // extern. The storage class is set above using parsed attributes. Now we can 6348 // check the VarDecl itself. 6349 assert(!NewVD->hasAttr<DLLImportAttr>() || 6350 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6351 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6352 6353 // In auto-retain/release, infer strong retension for variables of 6354 // retainable type. 6355 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6356 NewVD->setInvalidDecl(); 6357 6358 // Handle GNU asm-label extension (encoded as an attribute). 6359 if (Expr *E = (Expr*)D.getAsmLabel()) { 6360 // The parser guarantees this is a string. 6361 StringLiteral *SE = cast<StringLiteral>(E); 6362 StringRef Label = SE->getString(); 6363 if (S->getFnParent() != nullptr) { 6364 switch (SC) { 6365 case SC_None: 6366 case SC_Auto: 6367 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6368 break; 6369 case SC_Register: 6370 // Local Named register 6371 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6372 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6373 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6374 break; 6375 case SC_Static: 6376 case SC_Extern: 6377 case SC_PrivateExtern: 6378 break; 6379 } 6380 } else if (SC == SC_Register) { 6381 // Global Named register 6382 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6383 const auto &TI = Context.getTargetInfo(); 6384 bool HasSizeMismatch; 6385 6386 if (!TI.isValidGCCRegisterName(Label)) 6387 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6388 else if (!TI.validateGlobalRegisterVariable(Label, 6389 Context.getTypeSize(R), 6390 HasSizeMismatch)) 6391 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6392 else if (HasSizeMismatch) 6393 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6394 } 6395 6396 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6397 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6398 NewVD->setInvalidDecl(true); 6399 } 6400 } 6401 6402 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6403 Context, Label, 0)); 6404 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6405 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6406 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6407 if (I != ExtnameUndeclaredIdentifiers.end()) { 6408 if (isDeclExternC(NewVD)) { 6409 NewVD->addAttr(I->second); 6410 ExtnameUndeclaredIdentifiers.erase(I); 6411 } else 6412 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6413 << /*Variable*/1 << NewVD; 6414 } 6415 } 6416 6417 // Diagnose shadowed variables before filtering for scope. 6418 if (D.getCXXScopeSpec().isEmpty()) 6419 CheckShadow(S, NewVD, Previous); 6420 6421 // Don't consider existing declarations that are in a different 6422 // scope and are out-of-semantic-context declarations (if the new 6423 // declaration has linkage). 6424 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6425 D.getCXXScopeSpec().isNotEmpty() || 6426 IsExplicitSpecialization || 6427 IsVariableTemplateSpecialization); 6428 6429 // Check whether the previous declaration is in the same block scope. This 6430 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6431 if (getLangOpts().CPlusPlus && 6432 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6433 NewVD->setPreviousDeclInSameBlockScope( 6434 Previous.isSingleResult() && !Previous.isShadowed() && 6435 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6436 6437 if (!getLangOpts().CPlusPlus) { 6438 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6439 } else { 6440 // If this is an explicit specialization of a static data member, check it. 6441 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6442 CheckMemberSpecialization(NewVD, Previous)) 6443 NewVD->setInvalidDecl(); 6444 6445 // Merge the decl with the existing one if appropriate. 6446 if (!Previous.empty()) { 6447 if (Previous.isSingleResult() && 6448 isa<FieldDecl>(Previous.getFoundDecl()) && 6449 D.getCXXScopeSpec().isSet()) { 6450 // The user tried to define a non-static data member 6451 // out-of-line (C++ [dcl.meaning]p1). 6452 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6453 << D.getCXXScopeSpec().getRange(); 6454 Previous.clear(); 6455 NewVD->setInvalidDecl(); 6456 } 6457 } else if (D.getCXXScopeSpec().isSet()) { 6458 // No previous declaration in the qualifying scope. 6459 Diag(D.getIdentifierLoc(), diag::err_no_member) 6460 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6461 << D.getCXXScopeSpec().getRange(); 6462 NewVD->setInvalidDecl(); 6463 } 6464 6465 if (!IsVariableTemplateSpecialization) 6466 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6467 6468 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6469 // an explicit specialization (14.8.3) or a partial specialization of a 6470 // concept definition. 6471 if (IsVariableTemplateSpecialization && 6472 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6473 Previous.isSingleResult()) { 6474 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6475 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6476 if (VarTmpl->isConcept()) { 6477 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6478 << 1 /*variable*/ 6479 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6480 : 1 /*explicitly specialized*/); 6481 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6482 NewVD->setInvalidDecl(); 6483 } 6484 } 6485 } 6486 6487 if (NewTemplate) { 6488 VarTemplateDecl *PrevVarTemplate = 6489 NewVD->getPreviousDecl() 6490 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6491 : nullptr; 6492 6493 // Check the template parameter list of this declaration, possibly 6494 // merging in the template parameter list from the previous variable 6495 // template declaration. 6496 if (CheckTemplateParameterList( 6497 TemplateParams, 6498 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6499 : nullptr, 6500 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6501 DC->isDependentContext()) 6502 ? TPC_ClassTemplateMember 6503 : TPC_VarTemplate)) 6504 NewVD->setInvalidDecl(); 6505 6506 // If we are providing an explicit specialization of a static variable 6507 // template, make a note of that. 6508 if (PrevVarTemplate && 6509 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6510 PrevVarTemplate->setMemberSpecialization(); 6511 } 6512 } 6513 6514 ProcessPragmaWeak(S, NewVD); 6515 6516 // If this is the first declaration of an extern C variable, update 6517 // the map of such variables. 6518 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6519 isIncompleteDeclExternC(*this, NewVD)) 6520 RegisterLocallyScopedExternCDecl(NewVD, S); 6521 6522 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6523 Decl *ManglingContextDecl; 6524 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6525 NewVD->getDeclContext(), ManglingContextDecl)) { 6526 Context.setManglingNumber( 6527 NewVD, MCtx->getManglingNumber( 6528 NewVD, getMSManglingNumber(getLangOpts(), S))); 6529 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6530 } 6531 } 6532 6533 // Special handling of variable named 'main'. 6534 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6535 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6536 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6537 6538 // C++ [basic.start.main]p3 6539 // A program that declares a variable main at global scope is ill-formed. 6540 if (getLangOpts().CPlusPlus) 6541 Diag(D.getLocStart(), diag::err_main_global_variable); 6542 6543 // In C, and external-linkage variable named main results in undefined 6544 // behavior. 6545 else if (NewVD->hasExternalFormalLinkage()) 6546 Diag(D.getLocStart(), diag::warn_main_redefined); 6547 } 6548 6549 if (D.isRedeclaration() && !Previous.empty()) { 6550 checkDLLAttributeRedeclaration( 6551 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6552 IsExplicitSpecialization, D.isFunctionDefinition()); 6553 } 6554 6555 if (NewTemplate) { 6556 if (NewVD->isInvalidDecl()) 6557 NewTemplate->setInvalidDecl(); 6558 ActOnDocumentableDecl(NewTemplate); 6559 return NewTemplate; 6560 } 6561 6562 return NewVD; 6563 } 6564 6565 /// Enum describing the %select options in diag::warn_decl_shadow. 6566 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field }; 6567 6568 /// Determine what kind of declaration we're shadowing. 6569 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6570 const DeclContext *OldDC) { 6571 if (isa<RecordDecl>(OldDC)) 6572 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6573 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6574 } 6575 6576 /// \brief Diagnose variable or built-in function shadowing. Implements 6577 /// -Wshadow. 6578 /// 6579 /// This method is called whenever a VarDecl is added to a "useful" 6580 /// scope. 6581 /// 6582 /// \param S the scope in which the shadowing name is being declared 6583 /// \param R the lookup of the name 6584 /// 6585 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6586 // Return if warning is ignored. 6587 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6588 return; 6589 6590 // Don't diagnose declarations at file scope. 6591 if (D->hasGlobalStorage()) 6592 return; 6593 6594 DeclContext *NewDC = D->getDeclContext(); 6595 6596 // Only diagnose if we're shadowing an unambiguous field or variable. 6597 if (R.getResultKind() != LookupResult::Found) 6598 return; 6599 6600 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6601 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6602 return; 6603 6604 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6605 // Fields are not shadowed by variables in C++ static methods. 6606 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6607 if (MD->isStatic()) 6608 return; 6609 6610 // Fields shadowed by constructor parameters are a special case. Usually 6611 // the constructor initializes the field with the parameter. 6612 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) { 6613 // Remember that this was shadowed so we can either warn about its 6614 // modification or its existence depending on warning settings. 6615 D = D->getCanonicalDecl(); 6616 ShadowingDecls.insert({D, FD}); 6617 return; 6618 } 6619 } 6620 6621 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6622 if (shadowedVar->isExternC()) { 6623 // For shadowing external vars, make sure that we point to the global 6624 // declaration, not a locally scoped extern declaration. 6625 for (auto I : shadowedVar->redecls()) 6626 if (I->isFileVarDecl()) { 6627 ShadowedDecl = I; 6628 break; 6629 } 6630 } 6631 6632 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6633 6634 // Only warn about certain kinds of shadowing for class members. 6635 if (NewDC && NewDC->isRecord()) { 6636 // In particular, don't warn about shadowing non-class members. 6637 if (!OldDC->isRecord()) 6638 return; 6639 6640 // TODO: should we warn about static data members shadowing 6641 // static data members from base classes? 6642 6643 // TODO: don't diagnose for inaccessible shadowed members. 6644 // This is hard to do perfectly because we might friend the 6645 // shadowing context, but that's just a false negative. 6646 } 6647 6648 6649 DeclarationName Name = R.getLookupName(); 6650 6651 // Emit warning and note. 6652 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6653 return; 6654 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6655 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6656 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6657 } 6658 6659 /// \brief Check -Wshadow without the advantage of a previous lookup. 6660 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6661 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6662 return; 6663 6664 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6665 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6666 LookupName(R, S); 6667 CheckShadow(S, D, R); 6668 } 6669 6670 /// Check if 'E', which is an expression that is about to be modified, refers 6671 /// to a constructor parameter that shadows a field. 6672 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 6673 // Quickly ignore expressions that can't be shadowing ctor parameters. 6674 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 6675 return; 6676 E = E->IgnoreParenImpCasts(); 6677 auto *DRE = dyn_cast<DeclRefExpr>(E); 6678 if (!DRE) 6679 return; 6680 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 6681 auto I = ShadowingDecls.find(D); 6682 if (I == ShadowingDecls.end()) 6683 return; 6684 const NamedDecl *ShadowedDecl = I->second; 6685 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6686 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 6687 Diag(D->getLocation(), diag::note_var_declared_here) << D; 6688 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6689 6690 // Avoid issuing multiple warnings about the same decl. 6691 ShadowingDecls.erase(I); 6692 } 6693 6694 /// Check for conflict between this global or extern "C" declaration and 6695 /// previous global or extern "C" declarations. This is only used in C++. 6696 template<typename T> 6697 static bool checkGlobalOrExternCConflict( 6698 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6699 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6700 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6701 6702 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6703 // The common case: this global doesn't conflict with any extern "C" 6704 // declaration. 6705 return false; 6706 } 6707 6708 if (Prev) { 6709 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6710 // Both the old and new declarations have C language linkage. This is a 6711 // redeclaration. 6712 Previous.clear(); 6713 Previous.addDecl(Prev); 6714 return true; 6715 } 6716 6717 // This is a global, non-extern "C" declaration, and there is a previous 6718 // non-global extern "C" declaration. Diagnose if this is a variable 6719 // declaration. 6720 if (!isa<VarDecl>(ND)) 6721 return false; 6722 } else { 6723 // The declaration is extern "C". Check for any declaration in the 6724 // translation unit which might conflict. 6725 if (IsGlobal) { 6726 // We have already performed the lookup into the translation unit. 6727 IsGlobal = false; 6728 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6729 I != E; ++I) { 6730 if (isa<VarDecl>(*I)) { 6731 Prev = *I; 6732 break; 6733 } 6734 } 6735 } else { 6736 DeclContext::lookup_result R = 6737 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6738 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6739 I != E; ++I) { 6740 if (isa<VarDecl>(*I)) { 6741 Prev = *I; 6742 break; 6743 } 6744 // FIXME: If we have any other entity with this name in global scope, 6745 // the declaration is ill-formed, but that is a defect: it breaks the 6746 // 'stat' hack, for instance. Only variables can have mangled name 6747 // clashes with extern "C" declarations, so only they deserve a 6748 // diagnostic. 6749 } 6750 } 6751 6752 if (!Prev) 6753 return false; 6754 } 6755 6756 // Use the first declaration's location to ensure we point at something which 6757 // is lexically inside an extern "C" linkage-spec. 6758 assert(Prev && "should have found a previous declaration to diagnose"); 6759 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6760 Prev = FD->getFirstDecl(); 6761 else 6762 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6763 6764 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6765 << IsGlobal << ND; 6766 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6767 << IsGlobal; 6768 return false; 6769 } 6770 6771 /// Apply special rules for handling extern "C" declarations. Returns \c true 6772 /// if we have found that this is a redeclaration of some prior entity. 6773 /// 6774 /// Per C++ [dcl.link]p6: 6775 /// Two declarations [for a function or variable] with C language linkage 6776 /// with the same name that appear in different scopes refer to the same 6777 /// [entity]. An entity with C language linkage shall not be declared with 6778 /// the same name as an entity in global scope. 6779 template<typename T> 6780 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6781 LookupResult &Previous) { 6782 if (!S.getLangOpts().CPlusPlus) { 6783 // In C, when declaring a global variable, look for a corresponding 'extern' 6784 // variable declared in function scope. We don't need this in C++, because 6785 // we find local extern decls in the surrounding file-scope DeclContext. 6786 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6787 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6788 Previous.clear(); 6789 Previous.addDecl(Prev); 6790 return true; 6791 } 6792 } 6793 return false; 6794 } 6795 6796 // A declaration in the translation unit can conflict with an extern "C" 6797 // declaration. 6798 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6799 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6800 6801 // An extern "C" declaration can conflict with a declaration in the 6802 // translation unit or can be a redeclaration of an extern "C" declaration 6803 // in another scope. 6804 if (isIncompleteDeclExternC(S,ND)) 6805 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6806 6807 // Neither global nor extern "C": nothing to do. 6808 return false; 6809 } 6810 6811 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6812 // If the decl is already known invalid, don't check it. 6813 if (NewVD->isInvalidDecl()) 6814 return; 6815 6816 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6817 QualType T = TInfo->getType(); 6818 6819 // Defer checking an 'auto' type until its initializer is attached. 6820 if (T->isUndeducedType()) 6821 return; 6822 6823 if (NewVD->hasAttrs()) 6824 CheckAlignasUnderalignment(NewVD); 6825 6826 if (T->isObjCObjectType()) { 6827 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6828 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6829 T = Context.getObjCObjectPointerType(T); 6830 NewVD->setType(T); 6831 } 6832 6833 // Emit an error if an address space was applied to decl with local storage. 6834 // This includes arrays of objects with address space qualifiers, but not 6835 // automatic variables that point to other address spaces. 6836 // ISO/IEC TR 18037 S5.1.2 6837 if (!getLangOpts().OpenCL 6838 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6839 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6840 NewVD->setInvalidDecl(); 6841 return; 6842 } 6843 6844 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 6845 // scope. 6846 if (getLangOpts().OpenCLVersion == 120 && 6847 !getOpenCLOptions().cl_clang_storage_class_specifiers && 6848 NewVD->isStaticLocal()) { 6849 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6850 NewVD->setInvalidDecl(); 6851 return; 6852 } 6853 6854 if (getLangOpts().OpenCL) { 6855 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 6856 if (NewVD->hasAttr<BlocksAttr>()) { 6857 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 6858 return; 6859 } 6860 6861 if (T->isBlockPointerType()) { 6862 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 6863 // can't use 'extern' storage class. 6864 if (!T.isConstQualified()) { 6865 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 6866 << 0 /*const*/; 6867 NewVD->setInvalidDecl(); 6868 return; 6869 } 6870 if (NewVD->hasExternalStorage()) { 6871 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 6872 NewVD->setInvalidDecl(); 6873 return; 6874 } 6875 } 6876 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6877 // __constant address space. 6878 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6879 // variables inside a function can also be declared in the global 6880 // address space. 6881 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 6882 NewVD->hasExternalStorage()) { 6883 if (!T->isSamplerT() && 6884 !(T.getAddressSpace() == LangAS::opencl_constant || 6885 (T.getAddressSpace() == LangAS::opencl_global && 6886 getLangOpts().OpenCLVersion == 200))) { 6887 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 6888 if (getLangOpts().OpenCLVersion == 200) 6889 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6890 << Scope << "global or constant"; 6891 else 6892 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6893 << Scope << "constant"; 6894 NewVD->setInvalidDecl(); 6895 return; 6896 } 6897 } else { 6898 if (T.getAddressSpace() == LangAS::opencl_global) { 6899 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6900 << 1 /*is any function*/ << "global"; 6901 NewVD->setInvalidDecl(); 6902 return; 6903 } 6904 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 6905 // in functions. 6906 if (T.getAddressSpace() == LangAS::opencl_constant || 6907 T.getAddressSpace() == LangAS::opencl_local) { 6908 FunctionDecl *FD = getCurFunctionDecl(); 6909 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 6910 if (T.getAddressSpace() == LangAS::opencl_constant) 6911 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6912 << 0 /*non-kernel only*/ << "constant"; 6913 else 6914 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6915 << 0 /*non-kernel only*/ << "local"; 6916 NewVD->setInvalidDecl(); 6917 return; 6918 } 6919 } 6920 } 6921 } 6922 6923 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6924 && !NewVD->hasAttr<BlocksAttr>()) { 6925 if (getLangOpts().getGC() != LangOptions::NonGC) 6926 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6927 else { 6928 assert(!getLangOpts().ObjCAutoRefCount); 6929 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6930 } 6931 } 6932 6933 bool isVM = T->isVariablyModifiedType(); 6934 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6935 NewVD->hasAttr<BlocksAttr>()) 6936 getCurFunction()->setHasBranchProtectedScope(); 6937 6938 if ((isVM && NewVD->hasLinkage()) || 6939 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6940 bool SizeIsNegative; 6941 llvm::APSInt Oversized; 6942 TypeSourceInfo *FixedTInfo = 6943 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6944 SizeIsNegative, Oversized); 6945 if (!FixedTInfo && T->isVariableArrayType()) { 6946 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6947 // FIXME: This won't give the correct result for 6948 // int a[10][n]; 6949 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6950 6951 if (NewVD->isFileVarDecl()) 6952 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6953 << SizeRange; 6954 else if (NewVD->isStaticLocal()) 6955 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6956 << SizeRange; 6957 else 6958 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6959 << SizeRange; 6960 NewVD->setInvalidDecl(); 6961 return; 6962 } 6963 6964 if (!FixedTInfo) { 6965 if (NewVD->isFileVarDecl()) 6966 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6967 else 6968 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6969 NewVD->setInvalidDecl(); 6970 return; 6971 } 6972 6973 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6974 NewVD->setType(FixedTInfo->getType()); 6975 NewVD->setTypeSourceInfo(FixedTInfo); 6976 } 6977 6978 if (T->isVoidType()) { 6979 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6980 // of objects and functions. 6981 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6982 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6983 << T; 6984 NewVD->setInvalidDecl(); 6985 return; 6986 } 6987 } 6988 6989 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6990 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6991 NewVD->setInvalidDecl(); 6992 return; 6993 } 6994 6995 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6996 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6997 NewVD->setInvalidDecl(); 6998 return; 6999 } 7000 7001 if (NewVD->isConstexpr() && !T->isDependentType() && 7002 RequireLiteralType(NewVD->getLocation(), T, 7003 diag::err_constexpr_var_non_literal)) { 7004 NewVD->setInvalidDecl(); 7005 return; 7006 } 7007 } 7008 7009 /// \brief Perform semantic checking on a newly-created variable 7010 /// declaration. 7011 /// 7012 /// This routine performs all of the type-checking required for a 7013 /// variable declaration once it has been built. It is used both to 7014 /// check variables after they have been parsed and their declarators 7015 /// have been translated into a declaration, and to check variables 7016 /// that have been instantiated from a template. 7017 /// 7018 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7019 /// 7020 /// Returns true if the variable declaration is a redeclaration. 7021 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7022 CheckVariableDeclarationType(NewVD); 7023 7024 // If the decl is already known invalid, don't check it. 7025 if (NewVD->isInvalidDecl()) 7026 return false; 7027 7028 // If we did not find anything by this name, look for a non-visible 7029 // extern "C" declaration with the same name. 7030 if (Previous.empty() && 7031 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7032 Previous.setShadowed(); 7033 7034 if (!Previous.empty()) { 7035 MergeVarDecl(NewVD, Previous); 7036 return true; 7037 } 7038 return false; 7039 } 7040 7041 namespace { 7042 struct FindOverriddenMethod { 7043 Sema *S; 7044 CXXMethodDecl *Method; 7045 7046 /// Member lookup function that determines whether a given C++ 7047 /// method overrides a method in a base class, to be used with 7048 /// CXXRecordDecl::lookupInBases(). 7049 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7050 RecordDecl *BaseRecord = 7051 Specifier->getType()->getAs<RecordType>()->getDecl(); 7052 7053 DeclarationName Name = Method->getDeclName(); 7054 7055 // FIXME: Do we care about other names here too? 7056 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7057 // We really want to find the base class destructor here. 7058 QualType T = S->Context.getTypeDeclType(BaseRecord); 7059 CanQualType CT = S->Context.getCanonicalType(T); 7060 7061 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7062 } 7063 7064 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7065 Path.Decls = Path.Decls.slice(1)) { 7066 NamedDecl *D = Path.Decls.front(); 7067 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7068 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7069 return true; 7070 } 7071 } 7072 7073 return false; 7074 } 7075 }; 7076 7077 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7078 } // end anonymous namespace 7079 7080 /// \brief Report an error regarding overriding, along with any relevant 7081 /// overriden methods. 7082 /// 7083 /// \param DiagID the primary error to report. 7084 /// \param MD the overriding method. 7085 /// \param OEK which overrides to include as notes. 7086 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7087 OverrideErrorKind OEK = OEK_All) { 7088 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7089 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7090 E = MD->end_overridden_methods(); 7091 I != E; ++I) { 7092 // This check (& the OEK parameter) could be replaced by a predicate, but 7093 // without lambdas that would be overkill. This is still nicer than writing 7094 // out the diag loop 3 times. 7095 if ((OEK == OEK_All) || 7096 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7097 (OEK == OEK_Deleted && (*I)->isDeleted())) 7098 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7099 } 7100 } 7101 7102 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7103 /// and if so, check that it's a valid override and remember it. 7104 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7105 // Look for methods in base classes that this method might override. 7106 CXXBasePaths Paths; 7107 FindOverriddenMethod FOM; 7108 FOM.Method = MD; 7109 FOM.S = this; 7110 bool hasDeletedOverridenMethods = false; 7111 bool hasNonDeletedOverridenMethods = false; 7112 bool AddedAny = false; 7113 if (DC->lookupInBases(FOM, Paths)) { 7114 for (auto *I : Paths.found_decls()) { 7115 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7116 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7117 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7118 !CheckOverridingFunctionAttributes(MD, OldMD) && 7119 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7120 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7121 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7122 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7123 AddedAny = true; 7124 } 7125 } 7126 } 7127 } 7128 7129 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7130 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7131 } 7132 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7133 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7134 } 7135 7136 return AddedAny; 7137 } 7138 7139 namespace { 7140 // Struct for holding all of the extra arguments needed by 7141 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7142 struct ActOnFDArgs { 7143 Scope *S; 7144 Declarator &D; 7145 MultiTemplateParamsArg TemplateParamLists; 7146 bool AddToScope; 7147 }; 7148 } // end anonymous namespace 7149 7150 namespace { 7151 7152 // Callback to only accept typo corrections that have a non-zero edit distance. 7153 // Also only accept corrections that have the same parent decl. 7154 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7155 public: 7156 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7157 CXXRecordDecl *Parent) 7158 : Context(Context), OriginalFD(TypoFD), 7159 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7160 7161 bool ValidateCandidate(const TypoCorrection &candidate) override { 7162 if (candidate.getEditDistance() == 0) 7163 return false; 7164 7165 SmallVector<unsigned, 1> MismatchedParams; 7166 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7167 CDeclEnd = candidate.end(); 7168 CDecl != CDeclEnd; ++CDecl) { 7169 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7170 7171 if (FD && !FD->hasBody() && 7172 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7173 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7174 CXXRecordDecl *Parent = MD->getParent(); 7175 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7176 return true; 7177 } else if (!ExpectedParent) { 7178 return true; 7179 } 7180 } 7181 } 7182 7183 return false; 7184 } 7185 7186 private: 7187 ASTContext &Context; 7188 FunctionDecl *OriginalFD; 7189 CXXRecordDecl *ExpectedParent; 7190 }; 7191 7192 } // end anonymous namespace 7193 7194 /// \brief Generate diagnostics for an invalid function redeclaration. 7195 /// 7196 /// This routine handles generating the diagnostic messages for an invalid 7197 /// function redeclaration, including finding possible similar declarations 7198 /// or performing typo correction if there are no previous declarations with 7199 /// the same name. 7200 /// 7201 /// Returns a NamedDecl iff typo correction was performed and substituting in 7202 /// the new declaration name does not cause new errors. 7203 static NamedDecl *DiagnoseInvalidRedeclaration( 7204 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7205 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7206 DeclarationName Name = NewFD->getDeclName(); 7207 DeclContext *NewDC = NewFD->getDeclContext(); 7208 SmallVector<unsigned, 1> MismatchedParams; 7209 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7210 TypoCorrection Correction; 7211 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7212 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7213 : diag::err_member_decl_does_not_match; 7214 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7215 IsLocalFriend ? Sema::LookupLocalFriendName 7216 : Sema::LookupOrdinaryName, 7217 Sema::ForRedeclaration); 7218 7219 NewFD->setInvalidDecl(); 7220 if (IsLocalFriend) 7221 SemaRef.LookupName(Prev, S); 7222 else 7223 SemaRef.LookupQualifiedName(Prev, NewDC); 7224 assert(!Prev.isAmbiguous() && 7225 "Cannot have an ambiguity in previous-declaration lookup"); 7226 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7227 if (!Prev.empty()) { 7228 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7229 Func != FuncEnd; ++Func) { 7230 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7231 if (FD && 7232 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7233 // Add 1 to the index so that 0 can mean the mismatch didn't 7234 // involve a parameter 7235 unsigned ParamNum = 7236 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7237 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7238 } 7239 } 7240 // If the qualified name lookup yielded nothing, try typo correction 7241 } else if ((Correction = SemaRef.CorrectTypo( 7242 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7243 &ExtraArgs.D.getCXXScopeSpec(), 7244 llvm::make_unique<DifferentNameValidatorCCC>( 7245 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7246 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7247 // Set up everything for the call to ActOnFunctionDeclarator 7248 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7249 ExtraArgs.D.getIdentifierLoc()); 7250 Previous.clear(); 7251 Previous.setLookupName(Correction.getCorrection()); 7252 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7253 CDeclEnd = Correction.end(); 7254 CDecl != CDeclEnd; ++CDecl) { 7255 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7256 if (FD && !FD->hasBody() && 7257 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7258 Previous.addDecl(FD); 7259 } 7260 } 7261 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7262 7263 NamedDecl *Result; 7264 // Retry building the function declaration with the new previous 7265 // declarations, and with errors suppressed. 7266 { 7267 // Trap errors. 7268 Sema::SFINAETrap Trap(SemaRef); 7269 7270 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7271 // pieces need to verify the typo-corrected C++ declaration and hopefully 7272 // eliminate the need for the parameter pack ExtraArgs. 7273 Result = SemaRef.ActOnFunctionDeclarator( 7274 ExtraArgs.S, ExtraArgs.D, 7275 Correction.getCorrectionDecl()->getDeclContext(), 7276 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7277 ExtraArgs.AddToScope); 7278 7279 if (Trap.hasErrorOccurred()) 7280 Result = nullptr; 7281 } 7282 7283 if (Result) { 7284 // Determine which correction we picked. 7285 Decl *Canonical = Result->getCanonicalDecl(); 7286 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7287 I != E; ++I) 7288 if ((*I)->getCanonicalDecl() == Canonical) 7289 Correction.setCorrectionDecl(*I); 7290 7291 SemaRef.diagnoseTypo( 7292 Correction, 7293 SemaRef.PDiag(IsLocalFriend 7294 ? diag::err_no_matching_local_friend_suggest 7295 : diag::err_member_decl_does_not_match_suggest) 7296 << Name << NewDC << IsDefinition); 7297 return Result; 7298 } 7299 7300 // Pretend the typo correction never occurred 7301 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7302 ExtraArgs.D.getIdentifierLoc()); 7303 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7304 Previous.clear(); 7305 Previous.setLookupName(Name); 7306 } 7307 7308 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7309 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7310 7311 bool NewFDisConst = false; 7312 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7313 NewFDisConst = NewMD->isConst(); 7314 7315 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7316 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7317 NearMatch != NearMatchEnd; ++NearMatch) { 7318 FunctionDecl *FD = NearMatch->first; 7319 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7320 bool FDisConst = MD && MD->isConst(); 7321 bool IsMember = MD || !IsLocalFriend; 7322 7323 // FIXME: These notes are poorly worded for the local friend case. 7324 if (unsigned Idx = NearMatch->second) { 7325 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7326 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7327 if (Loc.isInvalid()) Loc = FD->getLocation(); 7328 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7329 : diag::note_local_decl_close_param_match) 7330 << Idx << FDParam->getType() 7331 << NewFD->getParamDecl(Idx - 1)->getType(); 7332 } else if (FDisConst != NewFDisConst) { 7333 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7334 << NewFDisConst << FD->getSourceRange().getEnd(); 7335 } else 7336 SemaRef.Diag(FD->getLocation(), 7337 IsMember ? diag::note_member_def_close_match 7338 : diag::note_local_decl_close_match); 7339 } 7340 return nullptr; 7341 } 7342 7343 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7344 switch (D.getDeclSpec().getStorageClassSpec()) { 7345 default: llvm_unreachable("Unknown storage class!"); 7346 case DeclSpec::SCS_auto: 7347 case DeclSpec::SCS_register: 7348 case DeclSpec::SCS_mutable: 7349 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7350 diag::err_typecheck_sclass_func); 7351 D.setInvalidType(); 7352 break; 7353 case DeclSpec::SCS_unspecified: break; 7354 case DeclSpec::SCS_extern: 7355 if (D.getDeclSpec().isExternInLinkageSpec()) 7356 return SC_None; 7357 return SC_Extern; 7358 case DeclSpec::SCS_static: { 7359 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7360 // C99 6.7.1p5: 7361 // The declaration of an identifier for a function that has 7362 // block scope shall have no explicit storage-class specifier 7363 // other than extern 7364 // See also (C++ [dcl.stc]p4). 7365 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7366 diag::err_static_block_func); 7367 break; 7368 } else 7369 return SC_Static; 7370 } 7371 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7372 } 7373 7374 // No explicit storage class has already been returned 7375 return SC_None; 7376 } 7377 7378 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7379 DeclContext *DC, QualType &R, 7380 TypeSourceInfo *TInfo, 7381 StorageClass SC, 7382 bool &IsVirtualOkay) { 7383 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7384 DeclarationName Name = NameInfo.getName(); 7385 7386 FunctionDecl *NewFD = nullptr; 7387 bool isInline = D.getDeclSpec().isInlineSpecified(); 7388 7389 if (!SemaRef.getLangOpts().CPlusPlus) { 7390 // Determine whether the function was written with a 7391 // prototype. This true when: 7392 // - there is a prototype in the declarator, or 7393 // - the type R of the function is some kind of typedef or other reference 7394 // to a type name (which eventually refers to a function type). 7395 bool HasPrototype = 7396 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7397 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7398 7399 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7400 D.getLocStart(), NameInfo, R, 7401 TInfo, SC, isInline, 7402 HasPrototype, false); 7403 if (D.isInvalidType()) 7404 NewFD->setInvalidDecl(); 7405 7406 return NewFD; 7407 } 7408 7409 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7410 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7411 7412 // Check that the return type is not an abstract class type. 7413 // For record types, this is done by the AbstractClassUsageDiagnoser once 7414 // the class has been completely parsed. 7415 if (!DC->isRecord() && 7416 SemaRef.RequireNonAbstractType( 7417 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7418 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7419 D.setInvalidType(); 7420 7421 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7422 // This is a C++ constructor declaration. 7423 assert(DC->isRecord() && 7424 "Constructors can only be declared in a member context"); 7425 7426 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7427 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7428 D.getLocStart(), NameInfo, 7429 R, TInfo, isExplicit, isInline, 7430 /*isImplicitlyDeclared=*/false, 7431 isConstexpr); 7432 7433 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7434 // This is a C++ destructor declaration. 7435 if (DC->isRecord()) { 7436 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7437 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7438 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7439 SemaRef.Context, Record, 7440 D.getLocStart(), 7441 NameInfo, R, TInfo, isInline, 7442 /*isImplicitlyDeclared=*/false); 7443 7444 // If the class is complete, then we now create the implicit exception 7445 // specification. If the class is incomplete or dependent, we can't do 7446 // it yet. 7447 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7448 Record->getDefinition() && !Record->isBeingDefined() && 7449 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7450 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7451 } 7452 7453 IsVirtualOkay = true; 7454 return NewDD; 7455 7456 } else { 7457 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7458 D.setInvalidType(); 7459 7460 // Create a FunctionDecl to satisfy the function definition parsing 7461 // code path. 7462 return FunctionDecl::Create(SemaRef.Context, DC, 7463 D.getLocStart(), 7464 D.getIdentifierLoc(), Name, R, TInfo, 7465 SC, isInline, 7466 /*hasPrototype=*/true, isConstexpr); 7467 } 7468 7469 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7470 if (!DC->isRecord()) { 7471 SemaRef.Diag(D.getIdentifierLoc(), 7472 diag::err_conv_function_not_member); 7473 return nullptr; 7474 } 7475 7476 SemaRef.CheckConversionDeclarator(D, R, SC); 7477 IsVirtualOkay = true; 7478 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7479 D.getLocStart(), NameInfo, 7480 R, TInfo, isInline, isExplicit, 7481 isConstexpr, SourceLocation()); 7482 7483 } else if (DC->isRecord()) { 7484 // If the name of the function is the same as the name of the record, 7485 // then this must be an invalid constructor that has a return type. 7486 // (The parser checks for a return type and makes the declarator a 7487 // constructor if it has no return type). 7488 if (Name.getAsIdentifierInfo() && 7489 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7490 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7491 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7492 << SourceRange(D.getIdentifierLoc()); 7493 return nullptr; 7494 } 7495 7496 // This is a C++ method declaration. 7497 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7498 cast<CXXRecordDecl>(DC), 7499 D.getLocStart(), NameInfo, R, 7500 TInfo, SC, isInline, 7501 isConstexpr, SourceLocation()); 7502 IsVirtualOkay = !Ret->isStatic(); 7503 return Ret; 7504 } else { 7505 bool isFriend = 7506 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7507 if (!isFriend && SemaRef.CurContext->isRecord()) 7508 return nullptr; 7509 7510 // Determine whether the function was written with a 7511 // prototype. This true when: 7512 // - we're in C++ (where every function has a prototype), 7513 return FunctionDecl::Create(SemaRef.Context, DC, 7514 D.getLocStart(), 7515 NameInfo, R, TInfo, SC, isInline, 7516 true/*HasPrototype*/, isConstexpr); 7517 } 7518 } 7519 7520 enum OpenCLParamType { 7521 ValidKernelParam, 7522 PtrPtrKernelParam, 7523 PtrKernelParam, 7524 PrivatePtrKernelParam, 7525 InvalidKernelParam, 7526 RecordKernelParam 7527 }; 7528 7529 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7530 if (PT->isPointerType()) { 7531 QualType PointeeType = PT->getPointeeType(); 7532 if (PointeeType->isPointerType()) 7533 return PtrPtrKernelParam; 7534 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 7535 : PtrKernelParam; 7536 } 7537 7538 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7539 // be used as builtin types. 7540 7541 if (PT->isImageType()) 7542 return PtrKernelParam; 7543 7544 if (PT->isBooleanType()) 7545 return InvalidKernelParam; 7546 7547 if (PT->isEventT()) 7548 return InvalidKernelParam; 7549 7550 // OpenCL extension spec v1.2 s9.5: 7551 // This extension adds support for half scalar and vector types as built-in 7552 // types that can be used for arithmetic operations, conversions etc. 7553 if (!S.getOpenCLOptions().cl_khr_fp16 && PT->isHalfType()) 7554 return InvalidKernelParam; 7555 7556 if (PT->isRecordType()) 7557 return RecordKernelParam; 7558 7559 return ValidKernelParam; 7560 } 7561 7562 static void checkIsValidOpenCLKernelParameter( 7563 Sema &S, 7564 Declarator &D, 7565 ParmVarDecl *Param, 7566 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7567 QualType PT = Param->getType(); 7568 7569 // Cache the valid types we encounter to avoid rechecking structs that are 7570 // used again 7571 if (ValidTypes.count(PT.getTypePtr())) 7572 return; 7573 7574 switch (getOpenCLKernelParameterType(S, PT)) { 7575 case PtrPtrKernelParam: 7576 // OpenCL v1.2 s6.9.a: 7577 // A kernel function argument cannot be declared as a 7578 // pointer to a pointer type. 7579 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7580 D.setInvalidType(); 7581 return; 7582 7583 case PrivatePtrKernelParam: 7584 // OpenCL v1.2 s6.9.a: 7585 // A kernel function argument cannot be declared as a 7586 // pointer to the private address space. 7587 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 7588 D.setInvalidType(); 7589 return; 7590 7591 // OpenCL v1.2 s6.9.k: 7592 // Arguments to kernel functions in a program cannot be declared with the 7593 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7594 // uintptr_t or a struct and/or union that contain fields declared to be 7595 // one of these built-in scalar types. 7596 7597 case InvalidKernelParam: 7598 // OpenCL v1.2 s6.8 n: 7599 // A kernel function argument cannot be declared 7600 // of event_t type. 7601 // Do not diagnose half type since it is diagnosed as invalid argument 7602 // type for any function elsewhere. 7603 if (!PT->isHalfType()) 7604 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7605 D.setInvalidType(); 7606 return; 7607 7608 case PtrKernelParam: 7609 case ValidKernelParam: 7610 ValidTypes.insert(PT.getTypePtr()); 7611 return; 7612 7613 case RecordKernelParam: 7614 break; 7615 } 7616 7617 // Track nested structs we will inspect 7618 SmallVector<const Decl *, 4> VisitStack; 7619 7620 // Track where we are in the nested structs. Items will migrate from 7621 // VisitStack to HistoryStack as we do the DFS for bad field. 7622 SmallVector<const FieldDecl *, 4> HistoryStack; 7623 HistoryStack.push_back(nullptr); 7624 7625 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7626 VisitStack.push_back(PD); 7627 7628 assert(VisitStack.back() && "First decl null?"); 7629 7630 do { 7631 const Decl *Next = VisitStack.pop_back_val(); 7632 if (!Next) { 7633 assert(!HistoryStack.empty()); 7634 // Found a marker, we have gone up a level 7635 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7636 ValidTypes.insert(Hist->getType().getTypePtr()); 7637 7638 continue; 7639 } 7640 7641 // Adds everything except the original parameter declaration (which is not a 7642 // field itself) to the history stack. 7643 const RecordDecl *RD; 7644 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7645 HistoryStack.push_back(Field); 7646 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7647 } else { 7648 RD = cast<RecordDecl>(Next); 7649 } 7650 7651 // Add a null marker so we know when we've gone back up a level 7652 VisitStack.push_back(nullptr); 7653 7654 for (const auto *FD : RD->fields()) { 7655 QualType QT = FD->getType(); 7656 7657 if (ValidTypes.count(QT.getTypePtr())) 7658 continue; 7659 7660 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 7661 if (ParamType == ValidKernelParam) 7662 continue; 7663 7664 if (ParamType == RecordKernelParam) { 7665 VisitStack.push_back(FD); 7666 continue; 7667 } 7668 7669 // OpenCL v1.2 s6.9.p: 7670 // Arguments to kernel functions that are declared to be a struct or union 7671 // do not allow OpenCL objects to be passed as elements of the struct or 7672 // union. 7673 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7674 ParamType == PrivatePtrKernelParam) { 7675 S.Diag(Param->getLocation(), 7676 diag::err_record_with_pointers_kernel_param) 7677 << PT->isUnionType() 7678 << PT; 7679 } else { 7680 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7681 } 7682 7683 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7684 << PD->getDeclName(); 7685 7686 // We have an error, now let's go back up through history and show where 7687 // the offending field came from 7688 for (ArrayRef<const FieldDecl *>::const_iterator 7689 I = HistoryStack.begin() + 1, 7690 E = HistoryStack.end(); 7691 I != E; ++I) { 7692 const FieldDecl *OuterField = *I; 7693 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7694 << OuterField->getType(); 7695 } 7696 7697 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7698 << QT->isPointerType() 7699 << QT; 7700 D.setInvalidType(); 7701 return; 7702 } 7703 } while (!VisitStack.empty()); 7704 } 7705 7706 NamedDecl* 7707 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7708 TypeSourceInfo *TInfo, LookupResult &Previous, 7709 MultiTemplateParamsArg TemplateParamLists, 7710 bool &AddToScope) { 7711 QualType R = TInfo->getType(); 7712 7713 assert(R.getTypePtr()->isFunctionType()); 7714 7715 // TODO: consider using NameInfo for diagnostic. 7716 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7717 DeclarationName Name = NameInfo.getName(); 7718 StorageClass SC = getFunctionStorageClass(*this, D); 7719 7720 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7721 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7722 diag::err_invalid_thread) 7723 << DeclSpec::getSpecifierName(TSCS); 7724 7725 if (D.isFirstDeclarationOfMember()) 7726 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7727 D.getIdentifierLoc()); 7728 7729 bool isFriend = false; 7730 FunctionTemplateDecl *FunctionTemplate = nullptr; 7731 bool isExplicitSpecialization = false; 7732 bool isFunctionTemplateSpecialization = false; 7733 7734 bool isDependentClassScopeExplicitSpecialization = false; 7735 bool HasExplicitTemplateArgs = false; 7736 TemplateArgumentListInfo TemplateArgs; 7737 7738 bool isVirtualOkay = false; 7739 7740 DeclContext *OriginalDC = DC; 7741 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7742 7743 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7744 isVirtualOkay); 7745 if (!NewFD) return nullptr; 7746 7747 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7748 NewFD->setTopLevelDeclInObjCContainer(); 7749 7750 // Set the lexical context. If this is a function-scope declaration, or has a 7751 // C++ scope specifier, or is the object of a friend declaration, the lexical 7752 // context will be different from the semantic context. 7753 NewFD->setLexicalDeclContext(CurContext); 7754 7755 if (IsLocalExternDecl) 7756 NewFD->setLocalExternDecl(); 7757 7758 if (getLangOpts().CPlusPlus) { 7759 bool isInline = D.getDeclSpec().isInlineSpecified(); 7760 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7761 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7762 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7763 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7764 isFriend = D.getDeclSpec().isFriendSpecified(); 7765 if (isFriend && !isInline && D.isFunctionDefinition()) { 7766 // C++ [class.friend]p5 7767 // A function can be defined in a friend declaration of a 7768 // class . . . . Such a function is implicitly inline. 7769 NewFD->setImplicitlyInline(); 7770 } 7771 7772 // If this is a method defined in an __interface, and is not a constructor 7773 // or an overloaded operator, then set the pure flag (isVirtual will already 7774 // return true). 7775 if (const CXXRecordDecl *Parent = 7776 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7777 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7778 NewFD->setPure(true); 7779 7780 // C++ [class.union]p2 7781 // A union can have member functions, but not virtual functions. 7782 if (isVirtual && Parent->isUnion()) 7783 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7784 } 7785 7786 SetNestedNameSpecifier(NewFD, D); 7787 isExplicitSpecialization = false; 7788 isFunctionTemplateSpecialization = false; 7789 if (D.isInvalidType()) 7790 NewFD->setInvalidDecl(); 7791 7792 // Match up the template parameter lists with the scope specifier, then 7793 // determine whether we have a template or a template specialization. 7794 bool Invalid = false; 7795 if (TemplateParameterList *TemplateParams = 7796 MatchTemplateParametersToScopeSpecifier( 7797 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7798 D.getCXXScopeSpec(), 7799 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7800 ? D.getName().TemplateId 7801 : nullptr, 7802 TemplateParamLists, isFriend, isExplicitSpecialization, 7803 Invalid)) { 7804 if (TemplateParams->size() > 0) { 7805 // This is a function template 7806 7807 // Check that we can declare a template here. 7808 if (CheckTemplateDeclScope(S, TemplateParams)) 7809 NewFD->setInvalidDecl(); 7810 7811 // A destructor cannot be a template. 7812 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7813 Diag(NewFD->getLocation(), diag::err_destructor_template); 7814 NewFD->setInvalidDecl(); 7815 } 7816 7817 // If we're adding a template to a dependent context, we may need to 7818 // rebuilding some of the types used within the template parameter list, 7819 // now that we know what the current instantiation is. 7820 if (DC->isDependentContext()) { 7821 ContextRAII SavedContext(*this, DC); 7822 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7823 Invalid = true; 7824 } 7825 7826 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7827 NewFD->getLocation(), 7828 Name, TemplateParams, 7829 NewFD); 7830 FunctionTemplate->setLexicalDeclContext(CurContext); 7831 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7832 7833 // For source fidelity, store the other template param lists. 7834 if (TemplateParamLists.size() > 1) { 7835 NewFD->setTemplateParameterListsInfo(Context, 7836 TemplateParamLists.drop_back(1)); 7837 } 7838 } else { 7839 // This is a function template specialization. 7840 isFunctionTemplateSpecialization = true; 7841 // For source fidelity, store all the template param lists. 7842 if (TemplateParamLists.size() > 0) 7843 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7844 7845 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7846 if (isFriend) { 7847 // We want to remove the "template<>", found here. 7848 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7849 7850 // If we remove the template<> and the name is not a 7851 // template-id, we're actually silently creating a problem: 7852 // the friend declaration will refer to an untemplated decl, 7853 // and clearly the user wants a template specialization. So 7854 // we need to insert '<>' after the name. 7855 SourceLocation InsertLoc; 7856 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7857 InsertLoc = D.getName().getSourceRange().getEnd(); 7858 InsertLoc = getLocForEndOfToken(InsertLoc); 7859 } 7860 7861 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7862 << Name << RemoveRange 7863 << FixItHint::CreateRemoval(RemoveRange) 7864 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7865 } 7866 } 7867 } 7868 else { 7869 // All template param lists were matched against the scope specifier: 7870 // this is NOT (an explicit specialization of) a template. 7871 if (TemplateParamLists.size() > 0) 7872 // For source fidelity, store all the template param lists. 7873 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7874 } 7875 7876 if (Invalid) { 7877 NewFD->setInvalidDecl(); 7878 if (FunctionTemplate) 7879 FunctionTemplate->setInvalidDecl(); 7880 } 7881 7882 // C++ [dcl.fct.spec]p5: 7883 // The virtual specifier shall only be used in declarations of 7884 // nonstatic class member functions that appear within a 7885 // member-specification of a class declaration; see 10.3. 7886 // 7887 if (isVirtual && !NewFD->isInvalidDecl()) { 7888 if (!isVirtualOkay) { 7889 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7890 diag::err_virtual_non_function); 7891 } else if (!CurContext->isRecord()) { 7892 // 'virtual' was specified outside of the class. 7893 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7894 diag::err_virtual_out_of_class) 7895 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7896 } else if (NewFD->getDescribedFunctionTemplate()) { 7897 // C++ [temp.mem]p3: 7898 // A member function template shall not be virtual. 7899 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7900 diag::err_virtual_member_function_template) 7901 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7902 } else { 7903 // Okay: Add virtual to the method. 7904 NewFD->setVirtualAsWritten(true); 7905 } 7906 7907 if (getLangOpts().CPlusPlus14 && 7908 NewFD->getReturnType()->isUndeducedType()) 7909 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7910 } 7911 7912 if (getLangOpts().CPlusPlus14 && 7913 (NewFD->isDependentContext() || 7914 (isFriend && CurContext->isDependentContext())) && 7915 NewFD->getReturnType()->isUndeducedType()) { 7916 // If the function template is referenced directly (for instance, as a 7917 // member of the current instantiation), pretend it has a dependent type. 7918 // This is not really justified by the standard, but is the only sane 7919 // thing to do. 7920 // FIXME: For a friend function, we have not marked the function as being 7921 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7922 const FunctionProtoType *FPT = 7923 NewFD->getType()->castAs<FunctionProtoType>(); 7924 QualType Result = 7925 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7926 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7927 FPT->getExtProtoInfo())); 7928 } 7929 7930 // C++ [dcl.fct.spec]p3: 7931 // The inline specifier shall not appear on a block scope function 7932 // declaration. 7933 if (isInline && !NewFD->isInvalidDecl()) { 7934 if (CurContext->isFunctionOrMethod()) { 7935 // 'inline' is not allowed on block scope function declaration. 7936 Diag(D.getDeclSpec().getInlineSpecLoc(), 7937 diag::err_inline_declaration_block_scope) << Name 7938 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7939 } 7940 } 7941 7942 // C++ [dcl.fct.spec]p6: 7943 // The explicit specifier shall be used only in the declaration of a 7944 // constructor or conversion function within its class definition; 7945 // see 12.3.1 and 12.3.2. 7946 if (isExplicit && !NewFD->isInvalidDecl()) { 7947 if (!CurContext->isRecord()) { 7948 // 'explicit' was specified outside of the class. 7949 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7950 diag::err_explicit_out_of_class) 7951 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7952 } else if (!isa<CXXConstructorDecl>(NewFD) && 7953 !isa<CXXConversionDecl>(NewFD)) { 7954 // 'explicit' was specified on a function that wasn't a constructor 7955 // or conversion function. 7956 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7957 diag::err_explicit_non_ctor_or_conv_function) 7958 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7959 } 7960 } 7961 7962 if (isConstexpr) { 7963 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7964 // are implicitly inline. 7965 NewFD->setImplicitlyInline(); 7966 7967 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7968 // be either constructors or to return a literal type. Therefore, 7969 // destructors cannot be declared constexpr. 7970 if (isa<CXXDestructorDecl>(NewFD)) 7971 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7972 } 7973 7974 if (isConcept) { 7975 // This is a function concept. 7976 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 7977 FTD->setConcept(); 7978 7979 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7980 // applied only to the definition of a function template [...] 7981 if (!D.isFunctionDefinition()) { 7982 Diag(D.getDeclSpec().getConceptSpecLoc(), 7983 diag::err_function_concept_not_defined); 7984 NewFD->setInvalidDecl(); 7985 } 7986 7987 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 7988 // have no exception-specification and is treated as if it were specified 7989 // with noexcept(true) (15.4). [...] 7990 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 7991 if (FPT->hasExceptionSpec()) { 7992 SourceRange Range; 7993 if (D.isFunctionDeclarator()) 7994 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 7995 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 7996 << FixItHint::CreateRemoval(Range); 7997 NewFD->setInvalidDecl(); 7998 } else { 7999 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8000 } 8001 8002 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8003 // following restrictions: 8004 // - The declared return type shall have the type bool. 8005 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8006 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8007 NewFD->setInvalidDecl(); 8008 } 8009 8010 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8011 // following restrictions: 8012 // - The declaration's parameter list shall be equivalent to an empty 8013 // parameter list. 8014 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8015 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8016 } 8017 8018 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8019 // implicity defined to be a constexpr declaration (implicitly inline) 8020 NewFD->setImplicitlyInline(); 8021 8022 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8023 // be declared with the thread_local, inline, friend, or constexpr 8024 // specifiers, [...] 8025 if (isInline) { 8026 Diag(D.getDeclSpec().getInlineSpecLoc(), 8027 diag::err_concept_decl_invalid_specifiers) 8028 << 1 << 1; 8029 NewFD->setInvalidDecl(true); 8030 } 8031 8032 if (isFriend) { 8033 Diag(D.getDeclSpec().getFriendSpecLoc(), 8034 diag::err_concept_decl_invalid_specifiers) 8035 << 1 << 2; 8036 NewFD->setInvalidDecl(true); 8037 } 8038 8039 if (isConstexpr) { 8040 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8041 diag::err_concept_decl_invalid_specifiers) 8042 << 1 << 3; 8043 NewFD->setInvalidDecl(true); 8044 } 8045 8046 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8047 // applied only to the definition of a function template or variable 8048 // template, declared in namespace scope. 8049 if (isFunctionTemplateSpecialization) { 8050 Diag(D.getDeclSpec().getConceptSpecLoc(), 8051 diag::err_concept_specified_specialization) << 1; 8052 NewFD->setInvalidDecl(true); 8053 return NewFD; 8054 } 8055 } 8056 8057 // If __module_private__ was specified, mark the function accordingly. 8058 if (D.getDeclSpec().isModulePrivateSpecified()) { 8059 if (isFunctionTemplateSpecialization) { 8060 SourceLocation ModulePrivateLoc 8061 = D.getDeclSpec().getModulePrivateSpecLoc(); 8062 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8063 << 0 8064 << FixItHint::CreateRemoval(ModulePrivateLoc); 8065 } else { 8066 NewFD->setModulePrivate(); 8067 if (FunctionTemplate) 8068 FunctionTemplate->setModulePrivate(); 8069 } 8070 } 8071 8072 if (isFriend) { 8073 if (FunctionTemplate) { 8074 FunctionTemplate->setObjectOfFriendDecl(); 8075 FunctionTemplate->setAccess(AS_public); 8076 } 8077 NewFD->setObjectOfFriendDecl(); 8078 NewFD->setAccess(AS_public); 8079 } 8080 8081 // If a function is defined as defaulted or deleted, mark it as such now. 8082 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8083 // definition kind to FDK_Definition. 8084 switch (D.getFunctionDefinitionKind()) { 8085 case FDK_Declaration: 8086 case FDK_Definition: 8087 break; 8088 8089 case FDK_Defaulted: 8090 NewFD->setDefaulted(); 8091 break; 8092 8093 case FDK_Deleted: 8094 NewFD->setDeletedAsWritten(); 8095 break; 8096 } 8097 8098 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8099 D.isFunctionDefinition()) { 8100 // C++ [class.mfct]p2: 8101 // A member function may be defined (8.4) in its class definition, in 8102 // which case it is an inline member function (7.1.2) 8103 NewFD->setImplicitlyInline(); 8104 } 8105 8106 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8107 !CurContext->isRecord()) { 8108 // C++ [class.static]p1: 8109 // A data or function member of a class may be declared static 8110 // in a class definition, in which case it is a static member of 8111 // the class. 8112 8113 // Complain about the 'static' specifier if it's on an out-of-line 8114 // member function definition. 8115 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8116 diag::err_static_out_of_line) 8117 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8118 } 8119 8120 // C++11 [except.spec]p15: 8121 // A deallocation function with no exception-specification is treated 8122 // as if it were specified with noexcept(true). 8123 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8124 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8125 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8126 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8127 NewFD->setType(Context.getFunctionType( 8128 FPT->getReturnType(), FPT->getParamTypes(), 8129 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8130 } 8131 8132 // Filter out previous declarations that don't match the scope. 8133 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8134 D.getCXXScopeSpec().isNotEmpty() || 8135 isExplicitSpecialization || 8136 isFunctionTemplateSpecialization); 8137 8138 // Handle GNU asm-label extension (encoded as an attribute). 8139 if (Expr *E = (Expr*) D.getAsmLabel()) { 8140 // The parser guarantees this is a string. 8141 StringLiteral *SE = cast<StringLiteral>(E); 8142 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8143 SE->getString(), 0)); 8144 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8145 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8146 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8147 if (I != ExtnameUndeclaredIdentifiers.end()) { 8148 if (isDeclExternC(NewFD)) { 8149 NewFD->addAttr(I->second); 8150 ExtnameUndeclaredIdentifiers.erase(I); 8151 } else 8152 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8153 << /*Variable*/0 << NewFD; 8154 } 8155 } 8156 8157 // Copy the parameter declarations from the declarator D to the function 8158 // declaration NewFD, if they are available. First scavenge them into Params. 8159 SmallVector<ParmVarDecl*, 16> Params; 8160 if (D.isFunctionDeclarator()) { 8161 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8162 8163 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8164 // function that takes no arguments, not a function that takes a 8165 // single void argument. 8166 // We let through "const void" here because Sema::GetTypeForDeclarator 8167 // already checks for that case. 8168 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8169 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8170 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8171 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8172 Param->setDeclContext(NewFD); 8173 Params.push_back(Param); 8174 8175 if (Param->isInvalidDecl()) 8176 NewFD->setInvalidDecl(); 8177 } 8178 } 8179 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8180 // When we're declaring a function with a typedef, typeof, etc as in the 8181 // following example, we'll need to synthesize (unnamed) 8182 // parameters for use in the declaration. 8183 // 8184 // @code 8185 // typedef void fn(int); 8186 // fn f; 8187 // @endcode 8188 8189 // Synthesize a parameter for each argument type. 8190 for (const auto &AI : FT->param_types()) { 8191 ParmVarDecl *Param = 8192 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8193 Param->setScopeInfo(0, Params.size()); 8194 Params.push_back(Param); 8195 } 8196 } else { 8197 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8198 "Should not need args for typedef of non-prototype fn"); 8199 } 8200 8201 // Finally, we know we have the right number of parameters, install them. 8202 NewFD->setParams(Params); 8203 8204 // Find all anonymous symbols defined during the declaration of this function 8205 // and add to NewFD. This lets us track decls such 'enum Y' in: 8206 // 8207 // void f(enum Y {AA} x) {} 8208 // 8209 // which would otherwise incorrectly end up in the translation unit scope. 8210 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 8211 DeclsInPrototypeScope.clear(); 8212 8213 if (D.getDeclSpec().isNoreturnSpecified()) 8214 NewFD->addAttr( 8215 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8216 Context, 0)); 8217 8218 // Functions returning a variably modified type violate C99 6.7.5.2p2 8219 // because all functions have linkage. 8220 if (!NewFD->isInvalidDecl() && 8221 NewFD->getReturnType()->isVariablyModifiedType()) { 8222 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8223 NewFD->setInvalidDecl(); 8224 } 8225 8226 // Apply an implicit SectionAttr if #pragma code_seg is active. 8227 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8228 !NewFD->hasAttr<SectionAttr>()) { 8229 NewFD->addAttr( 8230 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8231 CodeSegStack.CurrentValue->getString(), 8232 CodeSegStack.CurrentPragmaLocation)); 8233 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8234 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8235 ASTContext::PSF_Read, 8236 NewFD)) 8237 NewFD->dropAttr<SectionAttr>(); 8238 } 8239 8240 // Handle attributes. 8241 ProcessDeclAttributes(S, NewFD, D); 8242 8243 if (getLangOpts().CUDA) 8244 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8245 8246 if (getLangOpts().OpenCL) { 8247 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8248 // type declaration will generate a compilation error. 8249 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8250 if (AddressSpace == LangAS::opencl_local || 8251 AddressSpace == LangAS::opencl_global || 8252 AddressSpace == LangAS::opencl_constant) { 8253 Diag(NewFD->getLocation(), 8254 diag::err_opencl_return_value_with_address_space); 8255 NewFD->setInvalidDecl(); 8256 } 8257 } 8258 8259 if (!getLangOpts().CPlusPlus) { 8260 // Perform semantic checking on the function declaration. 8261 bool isExplicitSpecialization=false; 8262 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8263 CheckMain(NewFD, D.getDeclSpec()); 8264 8265 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8266 CheckMSVCRTEntryPoint(NewFD); 8267 8268 if (!NewFD->isInvalidDecl()) 8269 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8270 isExplicitSpecialization)); 8271 else if (!Previous.empty()) 8272 // Recover gracefully from an invalid redeclaration. 8273 D.setRedeclaration(true); 8274 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8275 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8276 "previous declaration set still overloaded"); 8277 8278 // Diagnose no-prototype function declarations with calling conventions that 8279 // don't support variadic calls. Only do this in C and do it after merging 8280 // possibly prototyped redeclarations. 8281 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8282 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8283 CallingConv CC = FT->getExtInfo().getCC(); 8284 if (!supportsVariadicCall(CC)) { 8285 // Windows system headers sometimes accidentally use stdcall without 8286 // (void) parameters, so we relax this to a warning. 8287 int DiagID = 8288 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8289 Diag(NewFD->getLocation(), DiagID) 8290 << FunctionType::getNameForCallConv(CC); 8291 } 8292 } 8293 } else { 8294 // C++11 [replacement.functions]p3: 8295 // The program's definitions shall not be specified as inline. 8296 // 8297 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8298 // 8299 // Suppress the diagnostic if the function is __attribute__((used)), since 8300 // that forces an external definition to be emitted. 8301 if (D.getDeclSpec().isInlineSpecified() && 8302 NewFD->isReplaceableGlobalAllocationFunction() && 8303 !NewFD->hasAttr<UsedAttr>()) 8304 Diag(D.getDeclSpec().getInlineSpecLoc(), 8305 diag::ext_operator_new_delete_declared_inline) 8306 << NewFD->getDeclName(); 8307 8308 // If the declarator is a template-id, translate the parser's template 8309 // argument list into our AST format. 8310 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8311 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8312 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8313 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8314 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8315 TemplateId->NumArgs); 8316 translateTemplateArguments(TemplateArgsPtr, 8317 TemplateArgs); 8318 8319 HasExplicitTemplateArgs = true; 8320 8321 if (NewFD->isInvalidDecl()) { 8322 HasExplicitTemplateArgs = false; 8323 } else if (FunctionTemplate) { 8324 // Function template with explicit template arguments. 8325 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8326 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8327 8328 HasExplicitTemplateArgs = false; 8329 } else { 8330 assert((isFunctionTemplateSpecialization || 8331 D.getDeclSpec().isFriendSpecified()) && 8332 "should have a 'template<>' for this decl"); 8333 // "friend void foo<>(int);" is an implicit specialization decl. 8334 isFunctionTemplateSpecialization = true; 8335 } 8336 } else if (isFriend && isFunctionTemplateSpecialization) { 8337 // This combination is only possible in a recovery case; the user 8338 // wrote something like: 8339 // template <> friend void foo(int); 8340 // which we're recovering from as if the user had written: 8341 // friend void foo<>(int); 8342 // Go ahead and fake up a template id. 8343 HasExplicitTemplateArgs = true; 8344 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8345 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8346 } 8347 8348 // If it's a friend (and only if it's a friend), it's possible 8349 // that either the specialized function type or the specialized 8350 // template is dependent, and therefore matching will fail. In 8351 // this case, don't check the specialization yet. 8352 bool InstantiationDependent = false; 8353 if (isFunctionTemplateSpecialization && isFriend && 8354 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8355 TemplateSpecializationType::anyDependentTemplateArguments( 8356 TemplateArgs, 8357 InstantiationDependent))) { 8358 assert(HasExplicitTemplateArgs && 8359 "friend function specialization without template args"); 8360 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8361 Previous)) 8362 NewFD->setInvalidDecl(); 8363 } else if (isFunctionTemplateSpecialization) { 8364 if (CurContext->isDependentContext() && CurContext->isRecord() 8365 && !isFriend) { 8366 isDependentClassScopeExplicitSpecialization = true; 8367 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8368 diag::ext_function_specialization_in_class : 8369 diag::err_function_specialization_in_class) 8370 << NewFD->getDeclName(); 8371 } else if (CheckFunctionTemplateSpecialization(NewFD, 8372 (HasExplicitTemplateArgs ? &TemplateArgs 8373 : nullptr), 8374 Previous)) 8375 NewFD->setInvalidDecl(); 8376 8377 // C++ [dcl.stc]p1: 8378 // A storage-class-specifier shall not be specified in an explicit 8379 // specialization (14.7.3) 8380 FunctionTemplateSpecializationInfo *Info = 8381 NewFD->getTemplateSpecializationInfo(); 8382 if (Info && SC != SC_None) { 8383 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8384 Diag(NewFD->getLocation(), 8385 diag::err_explicit_specialization_inconsistent_storage_class) 8386 << SC 8387 << FixItHint::CreateRemoval( 8388 D.getDeclSpec().getStorageClassSpecLoc()); 8389 8390 else 8391 Diag(NewFD->getLocation(), 8392 diag::ext_explicit_specialization_storage_class) 8393 << FixItHint::CreateRemoval( 8394 D.getDeclSpec().getStorageClassSpecLoc()); 8395 } 8396 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 8397 if (CheckMemberSpecialization(NewFD, Previous)) 8398 NewFD->setInvalidDecl(); 8399 } 8400 8401 // Perform semantic checking on the function declaration. 8402 if (!isDependentClassScopeExplicitSpecialization) { 8403 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8404 CheckMain(NewFD, D.getDeclSpec()); 8405 8406 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8407 CheckMSVCRTEntryPoint(NewFD); 8408 8409 if (!NewFD->isInvalidDecl()) 8410 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8411 isExplicitSpecialization)); 8412 else if (!Previous.empty()) 8413 // Recover gracefully from an invalid redeclaration. 8414 D.setRedeclaration(true); 8415 } 8416 8417 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8418 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8419 "previous declaration set still overloaded"); 8420 8421 NamedDecl *PrincipalDecl = (FunctionTemplate 8422 ? cast<NamedDecl>(FunctionTemplate) 8423 : NewFD); 8424 8425 if (isFriend && NewFD->getPreviousDecl()) { 8426 AccessSpecifier Access = AS_public; 8427 if (!NewFD->isInvalidDecl()) 8428 Access = NewFD->getPreviousDecl()->getAccess(); 8429 8430 NewFD->setAccess(Access); 8431 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8432 } 8433 8434 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8435 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8436 PrincipalDecl->setNonMemberOperator(); 8437 8438 // If we have a function template, check the template parameter 8439 // list. This will check and merge default template arguments. 8440 if (FunctionTemplate) { 8441 FunctionTemplateDecl *PrevTemplate = 8442 FunctionTemplate->getPreviousDecl(); 8443 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8444 PrevTemplate ? PrevTemplate->getTemplateParameters() 8445 : nullptr, 8446 D.getDeclSpec().isFriendSpecified() 8447 ? (D.isFunctionDefinition() 8448 ? TPC_FriendFunctionTemplateDefinition 8449 : TPC_FriendFunctionTemplate) 8450 : (D.getCXXScopeSpec().isSet() && 8451 DC && DC->isRecord() && 8452 DC->isDependentContext()) 8453 ? TPC_ClassTemplateMember 8454 : TPC_FunctionTemplate); 8455 } 8456 8457 if (NewFD->isInvalidDecl()) { 8458 // Ignore all the rest of this. 8459 } else if (!D.isRedeclaration()) { 8460 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8461 AddToScope }; 8462 // Fake up an access specifier if it's supposed to be a class member. 8463 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8464 NewFD->setAccess(AS_public); 8465 8466 // Qualified decls generally require a previous declaration. 8467 if (D.getCXXScopeSpec().isSet()) { 8468 // ...with the major exception of templated-scope or 8469 // dependent-scope friend declarations. 8470 8471 // TODO: we currently also suppress this check in dependent 8472 // contexts because (1) the parameter depth will be off when 8473 // matching friend templates and (2) we might actually be 8474 // selecting a friend based on a dependent factor. But there 8475 // are situations where these conditions don't apply and we 8476 // can actually do this check immediately. 8477 if (isFriend && 8478 (TemplateParamLists.size() || 8479 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8480 CurContext->isDependentContext())) { 8481 // ignore these 8482 } else { 8483 // The user tried to provide an out-of-line definition for a 8484 // function that is a member of a class or namespace, but there 8485 // was no such member function declared (C++ [class.mfct]p2, 8486 // C++ [namespace.memdef]p2). For example: 8487 // 8488 // class X { 8489 // void f() const; 8490 // }; 8491 // 8492 // void X::f() { } // ill-formed 8493 // 8494 // Complain about this problem, and attempt to suggest close 8495 // matches (e.g., those that differ only in cv-qualifiers and 8496 // whether the parameter types are references). 8497 8498 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8499 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8500 AddToScope = ExtraArgs.AddToScope; 8501 return Result; 8502 } 8503 } 8504 8505 // Unqualified local friend declarations are required to resolve 8506 // to something. 8507 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8508 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8509 *this, Previous, NewFD, ExtraArgs, true, S)) { 8510 AddToScope = ExtraArgs.AddToScope; 8511 return Result; 8512 } 8513 } 8514 } else if (!D.isFunctionDefinition() && 8515 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8516 !isFriend && !isFunctionTemplateSpecialization && 8517 !isExplicitSpecialization) { 8518 // An out-of-line member function declaration must also be a 8519 // definition (C++ [class.mfct]p2). 8520 // Note that this is not the case for explicit specializations of 8521 // function templates or member functions of class templates, per 8522 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8523 // extension for compatibility with old SWIG code which likes to 8524 // generate them. 8525 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8526 << D.getCXXScopeSpec().getRange(); 8527 } 8528 } 8529 8530 ProcessPragmaWeak(S, NewFD); 8531 checkAttributesAfterMerging(*this, *NewFD); 8532 8533 AddKnownFunctionAttributes(NewFD); 8534 8535 if (NewFD->hasAttr<OverloadableAttr>() && 8536 !NewFD->getType()->getAs<FunctionProtoType>()) { 8537 Diag(NewFD->getLocation(), 8538 diag::err_attribute_overloadable_no_prototype) 8539 << NewFD; 8540 8541 // Turn this into a variadic function with no parameters. 8542 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8543 FunctionProtoType::ExtProtoInfo EPI( 8544 Context.getDefaultCallingConvention(true, false)); 8545 EPI.Variadic = true; 8546 EPI.ExtInfo = FT->getExtInfo(); 8547 8548 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8549 NewFD->setType(R); 8550 } 8551 8552 // If there's a #pragma GCC visibility in scope, and this isn't a class 8553 // member, set the visibility of this function. 8554 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8555 AddPushedVisibilityAttribute(NewFD); 8556 8557 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8558 // marking the function. 8559 AddCFAuditedAttribute(NewFD); 8560 8561 // If this is a function definition, check if we have to apply optnone due to 8562 // a pragma. 8563 if(D.isFunctionDefinition()) 8564 AddRangeBasedOptnone(NewFD); 8565 8566 // If this is the first declaration of an extern C variable, update 8567 // the map of such variables. 8568 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8569 isIncompleteDeclExternC(*this, NewFD)) 8570 RegisterLocallyScopedExternCDecl(NewFD, S); 8571 8572 // Set this FunctionDecl's range up to the right paren. 8573 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8574 8575 if (D.isRedeclaration() && !Previous.empty()) { 8576 checkDLLAttributeRedeclaration( 8577 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8578 isExplicitSpecialization || isFunctionTemplateSpecialization, 8579 D.isFunctionDefinition()); 8580 } 8581 8582 if (getLangOpts().CUDA) { 8583 IdentifierInfo *II = NewFD->getIdentifier(); 8584 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8585 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8586 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8587 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8588 8589 Context.setcudaConfigureCallDecl(NewFD); 8590 } 8591 8592 // Variadic functions, other than a *declaration* of printf, are not allowed 8593 // in device-side CUDA code, unless someone passed 8594 // -fcuda-allow-variadic-functions. 8595 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8596 (NewFD->hasAttr<CUDADeviceAttr>() || 8597 NewFD->hasAttr<CUDAGlobalAttr>()) && 8598 !(II && II->isStr("printf") && NewFD->isExternC() && 8599 !D.isFunctionDefinition())) { 8600 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8601 } 8602 } 8603 8604 if (getLangOpts().CPlusPlus) { 8605 if (FunctionTemplate) { 8606 if (NewFD->isInvalidDecl()) 8607 FunctionTemplate->setInvalidDecl(); 8608 return FunctionTemplate; 8609 } 8610 } 8611 8612 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8613 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8614 if ((getLangOpts().OpenCLVersion >= 120) 8615 && (SC == SC_Static)) { 8616 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8617 D.setInvalidType(); 8618 } 8619 8620 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8621 if (!NewFD->getReturnType()->isVoidType()) { 8622 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8623 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8624 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8625 : FixItHint()); 8626 D.setInvalidType(); 8627 } 8628 8629 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8630 for (auto Param : NewFD->parameters()) 8631 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8632 } 8633 for (const ParmVarDecl *Param : NewFD->parameters()) { 8634 QualType PT = Param->getType(); 8635 8636 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8637 // types. 8638 if (getLangOpts().OpenCLVersion >= 200) { 8639 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8640 QualType ElemTy = PipeTy->getElementType(); 8641 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8642 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8643 D.setInvalidType(); 8644 } 8645 } 8646 } 8647 } 8648 8649 MarkUnusedFileScopedDecl(NewFD); 8650 8651 // Here we have an function template explicit specialization at class scope. 8652 // The actually specialization will be postponed to template instatiation 8653 // time via the ClassScopeFunctionSpecializationDecl node. 8654 if (isDependentClassScopeExplicitSpecialization) { 8655 ClassScopeFunctionSpecializationDecl *NewSpec = 8656 ClassScopeFunctionSpecializationDecl::Create( 8657 Context, CurContext, SourceLocation(), 8658 cast<CXXMethodDecl>(NewFD), 8659 HasExplicitTemplateArgs, TemplateArgs); 8660 CurContext->addDecl(NewSpec); 8661 AddToScope = false; 8662 } 8663 8664 return NewFD; 8665 } 8666 8667 /// \brief Checks if the new declaration declared in dependent context must be 8668 /// put in the same redeclaration chain as the specified declaration. 8669 /// 8670 /// \param D Declaration that is checked. 8671 /// \param PrevDecl Previous declaration found with proper lookup method for the 8672 /// same declaration name. 8673 /// \returns True if D must be added to the redeclaration chain which PrevDecl 8674 /// belongs to. 8675 /// 8676 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 8677 // Any declarations should be put into redeclaration chains except for 8678 // friend declaration in a dependent context that names a function in 8679 // namespace scope. 8680 // 8681 // This allows to compile code like: 8682 // 8683 // void func(); 8684 // template<typename T> class C1 { friend void func() { } }; 8685 // template<typename T> class C2 { friend void func() { } }; 8686 // 8687 // This code snippet is a valid code unless both templates are instantiated. 8688 return !(D->getLexicalDeclContext()->isDependentContext() && 8689 D->getDeclContext()->isFileContext() && 8690 D->getFriendObjectKind() != Decl::FOK_None); 8691 } 8692 8693 /// \brief Perform semantic checking of a new function declaration. 8694 /// 8695 /// Performs semantic analysis of the new function declaration 8696 /// NewFD. This routine performs all semantic checking that does not 8697 /// require the actual declarator involved in the declaration, and is 8698 /// used both for the declaration of functions as they are parsed 8699 /// (called via ActOnDeclarator) and for the declaration of functions 8700 /// that have been instantiated via C++ template instantiation (called 8701 /// via InstantiateDecl). 8702 /// 8703 /// \param IsExplicitSpecialization whether this new function declaration is 8704 /// an explicit specialization of the previous declaration. 8705 /// 8706 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8707 /// 8708 /// \returns true if the function declaration is a redeclaration. 8709 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8710 LookupResult &Previous, 8711 bool IsExplicitSpecialization) { 8712 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8713 "Variably modified return types are not handled here"); 8714 8715 // Determine whether the type of this function should be merged with 8716 // a previous visible declaration. This never happens for functions in C++, 8717 // and always happens in C if the previous declaration was visible. 8718 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8719 !Previous.isShadowed(); 8720 8721 bool Redeclaration = false; 8722 NamedDecl *OldDecl = nullptr; 8723 8724 // Merge or overload the declaration with an existing declaration of 8725 // the same name, if appropriate. 8726 if (!Previous.empty()) { 8727 // Determine whether NewFD is an overload of PrevDecl or 8728 // a declaration that requires merging. If it's an overload, 8729 // there's no more work to do here; we'll just add the new 8730 // function to the scope. 8731 if (!AllowOverloadingOfFunction(Previous, Context)) { 8732 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8733 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8734 Redeclaration = true; 8735 OldDecl = Candidate; 8736 } 8737 } else { 8738 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8739 /*NewIsUsingDecl*/ false)) { 8740 case Ovl_Match: 8741 Redeclaration = true; 8742 break; 8743 8744 case Ovl_NonFunction: 8745 Redeclaration = true; 8746 break; 8747 8748 case Ovl_Overload: 8749 Redeclaration = false; 8750 break; 8751 } 8752 8753 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8754 // If a function name is overloadable in C, then every function 8755 // with that name must be marked "overloadable". 8756 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8757 << Redeclaration << NewFD; 8758 NamedDecl *OverloadedDecl = nullptr; 8759 if (Redeclaration) 8760 OverloadedDecl = OldDecl; 8761 else if (!Previous.empty()) 8762 OverloadedDecl = Previous.getRepresentativeDecl(); 8763 if (OverloadedDecl) 8764 Diag(OverloadedDecl->getLocation(), 8765 diag::note_attribute_overloadable_prev_overload); 8766 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8767 } 8768 } 8769 } 8770 8771 // Check for a previous extern "C" declaration with this name. 8772 if (!Redeclaration && 8773 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8774 if (!Previous.empty()) { 8775 // This is an extern "C" declaration with the same name as a previous 8776 // declaration, and thus redeclares that entity... 8777 Redeclaration = true; 8778 OldDecl = Previous.getFoundDecl(); 8779 MergeTypeWithPrevious = false; 8780 8781 // ... except in the presence of __attribute__((overloadable)). 8782 if (OldDecl->hasAttr<OverloadableAttr>()) { 8783 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8784 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8785 << Redeclaration << NewFD; 8786 Diag(Previous.getFoundDecl()->getLocation(), 8787 diag::note_attribute_overloadable_prev_overload); 8788 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8789 } 8790 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8791 Redeclaration = false; 8792 OldDecl = nullptr; 8793 } 8794 } 8795 } 8796 } 8797 8798 // C++11 [dcl.constexpr]p8: 8799 // A constexpr specifier for a non-static member function that is not 8800 // a constructor declares that member function to be const. 8801 // 8802 // This needs to be delayed until we know whether this is an out-of-line 8803 // definition of a static member function. 8804 // 8805 // This rule is not present in C++1y, so we produce a backwards 8806 // compatibility warning whenever it happens in C++11. 8807 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8808 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8809 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8810 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8811 CXXMethodDecl *OldMD = nullptr; 8812 if (OldDecl) 8813 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8814 if (!OldMD || !OldMD->isStatic()) { 8815 const FunctionProtoType *FPT = 8816 MD->getType()->castAs<FunctionProtoType>(); 8817 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8818 EPI.TypeQuals |= Qualifiers::Const; 8819 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8820 FPT->getParamTypes(), EPI)); 8821 8822 // Warn that we did this, if we're not performing template instantiation. 8823 // In that case, we'll have warned already when the template was defined. 8824 if (ActiveTemplateInstantiations.empty()) { 8825 SourceLocation AddConstLoc; 8826 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8827 .IgnoreParens().getAs<FunctionTypeLoc>()) 8828 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8829 8830 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8831 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8832 } 8833 } 8834 } 8835 8836 if (Redeclaration) { 8837 // NewFD and OldDecl represent declarations that need to be 8838 // merged. 8839 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8840 NewFD->setInvalidDecl(); 8841 return Redeclaration; 8842 } 8843 8844 Previous.clear(); 8845 Previous.addDecl(OldDecl); 8846 8847 if (FunctionTemplateDecl *OldTemplateDecl 8848 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8849 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8850 FunctionTemplateDecl *NewTemplateDecl 8851 = NewFD->getDescribedFunctionTemplate(); 8852 assert(NewTemplateDecl && "Template/non-template mismatch"); 8853 if (CXXMethodDecl *Method 8854 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8855 Method->setAccess(OldTemplateDecl->getAccess()); 8856 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8857 } 8858 8859 // If this is an explicit specialization of a member that is a function 8860 // template, mark it as a member specialization. 8861 if (IsExplicitSpecialization && 8862 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8863 NewTemplateDecl->setMemberSpecialization(); 8864 assert(OldTemplateDecl->isMemberSpecialization()); 8865 // Explicit specializations of a member template do not inherit deleted 8866 // status from the parent member template that they are specializing. 8867 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 8868 FunctionDecl *const OldTemplatedDecl = 8869 OldTemplateDecl->getTemplatedDecl(); 8870 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 8871 OldTemplatedDecl->setDeletedAsWritten(false); 8872 } 8873 } 8874 8875 } else { 8876 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 8877 // This needs to happen first so that 'inline' propagates. 8878 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8879 if (isa<CXXMethodDecl>(NewFD)) 8880 NewFD->setAccess(OldDecl->getAccess()); 8881 } 8882 } 8883 } 8884 8885 // Semantic checking for this function declaration (in isolation). 8886 8887 if (getLangOpts().CPlusPlus) { 8888 // C++-specific checks. 8889 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8890 CheckConstructor(Constructor); 8891 } else if (CXXDestructorDecl *Destructor = 8892 dyn_cast<CXXDestructorDecl>(NewFD)) { 8893 CXXRecordDecl *Record = Destructor->getParent(); 8894 QualType ClassType = Context.getTypeDeclType(Record); 8895 8896 // FIXME: Shouldn't we be able to perform this check even when the class 8897 // type is dependent? Both gcc and edg can handle that. 8898 if (!ClassType->isDependentType()) { 8899 DeclarationName Name 8900 = Context.DeclarationNames.getCXXDestructorName( 8901 Context.getCanonicalType(ClassType)); 8902 if (NewFD->getDeclName() != Name) { 8903 Diag(NewFD->getLocation(), diag::err_destructor_name); 8904 NewFD->setInvalidDecl(); 8905 return Redeclaration; 8906 } 8907 } 8908 } else if (CXXConversionDecl *Conversion 8909 = dyn_cast<CXXConversionDecl>(NewFD)) { 8910 ActOnConversionDeclarator(Conversion); 8911 } 8912 8913 // Find any virtual functions that this function overrides. 8914 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8915 if (!Method->isFunctionTemplateSpecialization() && 8916 !Method->getDescribedFunctionTemplate() && 8917 Method->isCanonicalDecl()) { 8918 if (AddOverriddenMethods(Method->getParent(), Method)) { 8919 // If the function was marked as "static", we have a problem. 8920 if (NewFD->getStorageClass() == SC_Static) { 8921 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8922 } 8923 } 8924 } 8925 8926 if (Method->isStatic()) 8927 checkThisInStaticMemberFunctionType(Method); 8928 } 8929 8930 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8931 if (NewFD->isOverloadedOperator() && 8932 CheckOverloadedOperatorDeclaration(NewFD)) { 8933 NewFD->setInvalidDecl(); 8934 return Redeclaration; 8935 } 8936 8937 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8938 if (NewFD->getLiteralIdentifier() && 8939 CheckLiteralOperatorDeclaration(NewFD)) { 8940 NewFD->setInvalidDecl(); 8941 return Redeclaration; 8942 } 8943 8944 // In C++, check default arguments now that we have merged decls. Unless 8945 // the lexical context is the class, because in this case this is done 8946 // during delayed parsing anyway. 8947 if (!CurContext->isRecord()) 8948 CheckCXXDefaultArguments(NewFD); 8949 8950 // If this function declares a builtin function, check the type of this 8951 // declaration against the expected type for the builtin. 8952 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8953 ASTContext::GetBuiltinTypeError Error; 8954 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8955 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8956 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8957 // The type of this function differs from the type of the builtin, 8958 // so forget about the builtin entirely. 8959 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 8960 } 8961 } 8962 8963 // If this function is declared as being extern "C", then check to see if 8964 // the function returns a UDT (class, struct, or union type) that is not C 8965 // compatible, and if it does, warn the user. 8966 // But, issue any diagnostic on the first declaration only. 8967 if (Previous.empty() && NewFD->isExternC()) { 8968 QualType R = NewFD->getReturnType(); 8969 if (R->isIncompleteType() && !R->isVoidType()) 8970 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8971 << NewFD << R; 8972 else if (!R.isPODType(Context) && !R->isVoidType() && 8973 !R->isObjCObjectPointerType()) 8974 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8975 } 8976 8977 // C++1z [dcl.fct]p6: 8978 // [...] whether the function has a non-throwing exception-specification 8979 // [is] part of the function type 8980 // 8981 // This results in an ABI break between C++14 and C++17 for functions whose 8982 // declared type includes an exception-specification in a parameter or 8983 // return type. (Exception specifications on the function itself are OK in 8984 // most cases, and exception specifications are not permitted in most other 8985 // contexts where they could make it into a mangling.) 8986 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 8987 auto HasNoexcept = [&](QualType T) -> bool { 8988 // Strip off declarator chunks that could be between us and a function 8989 // type. We don't need to look far, exception specifications are very 8990 // restricted prior to C++17. 8991 if (auto *RT = T->getAs<ReferenceType>()) 8992 T = RT->getPointeeType(); 8993 else if (T->isAnyPointerType()) 8994 T = T->getPointeeType(); 8995 else if (auto *MPT = T->getAs<MemberPointerType>()) 8996 T = MPT->getPointeeType(); 8997 if (auto *FPT = T->getAs<FunctionProtoType>()) 8998 if (FPT->isNothrow(Context)) 8999 return true; 9000 return false; 9001 }; 9002 9003 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9004 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9005 for (QualType T : FPT->param_types()) 9006 AnyNoexcept |= HasNoexcept(T); 9007 if (AnyNoexcept) 9008 Diag(NewFD->getLocation(), 9009 diag::warn_cxx1z_compat_exception_spec_in_signature) 9010 << NewFD; 9011 } 9012 } 9013 return Redeclaration; 9014 } 9015 9016 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9017 // C++11 [basic.start.main]p3: 9018 // A program that [...] declares main to be inline, static or 9019 // constexpr is ill-formed. 9020 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9021 // appear in a declaration of main. 9022 // static main is not an error under C99, but we should warn about it. 9023 // We accept _Noreturn main as an extension. 9024 if (FD->getStorageClass() == SC_Static) 9025 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9026 ? diag::err_static_main : diag::warn_static_main) 9027 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9028 if (FD->isInlineSpecified()) 9029 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9030 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9031 if (DS.isNoreturnSpecified()) { 9032 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9033 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9034 Diag(NoreturnLoc, diag::ext_noreturn_main); 9035 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9036 << FixItHint::CreateRemoval(NoreturnRange); 9037 } 9038 if (FD->isConstexpr()) { 9039 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9040 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9041 FD->setConstexpr(false); 9042 } 9043 9044 if (getLangOpts().OpenCL) { 9045 Diag(FD->getLocation(), diag::err_opencl_no_main) 9046 << FD->hasAttr<OpenCLKernelAttr>(); 9047 FD->setInvalidDecl(); 9048 return; 9049 } 9050 9051 QualType T = FD->getType(); 9052 assert(T->isFunctionType() && "function decl is not of function type"); 9053 const FunctionType* FT = T->castAs<FunctionType>(); 9054 9055 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9056 // In C with GNU extensions we allow main() to have non-integer return 9057 // type, but we should warn about the extension, and we disable the 9058 // implicit-return-zero rule. 9059 9060 // GCC in C mode accepts qualified 'int'. 9061 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9062 FD->setHasImplicitReturnZero(true); 9063 else { 9064 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9065 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9066 if (RTRange.isValid()) 9067 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9068 << FixItHint::CreateReplacement(RTRange, "int"); 9069 } 9070 } else { 9071 // In C and C++, main magically returns 0 if you fall off the end; 9072 // set the flag which tells us that. 9073 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9074 9075 // All the standards say that main() should return 'int'. 9076 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9077 FD->setHasImplicitReturnZero(true); 9078 else { 9079 // Otherwise, this is just a flat-out error. 9080 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9081 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9082 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9083 : FixItHint()); 9084 FD->setInvalidDecl(true); 9085 } 9086 } 9087 9088 // Treat protoless main() as nullary. 9089 if (isa<FunctionNoProtoType>(FT)) return; 9090 9091 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9092 unsigned nparams = FTP->getNumParams(); 9093 assert(FD->getNumParams() == nparams); 9094 9095 bool HasExtraParameters = (nparams > 3); 9096 9097 if (FTP->isVariadic()) { 9098 Diag(FD->getLocation(), diag::ext_variadic_main); 9099 // FIXME: if we had information about the location of the ellipsis, we 9100 // could add a FixIt hint to remove it as a parameter. 9101 } 9102 9103 // Darwin passes an undocumented fourth argument of type char**. If 9104 // other platforms start sprouting these, the logic below will start 9105 // getting shifty. 9106 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9107 HasExtraParameters = false; 9108 9109 if (HasExtraParameters) { 9110 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9111 FD->setInvalidDecl(true); 9112 nparams = 3; 9113 } 9114 9115 // FIXME: a lot of the following diagnostics would be improved 9116 // if we had some location information about types. 9117 9118 QualType CharPP = 9119 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9120 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9121 9122 for (unsigned i = 0; i < nparams; ++i) { 9123 QualType AT = FTP->getParamType(i); 9124 9125 bool mismatch = true; 9126 9127 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9128 mismatch = false; 9129 else if (Expected[i] == CharPP) { 9130 // As an extension, the following forms are okay: 9131 // char const ** 9132 // char const * const * 9133 // char * const * 9134 9135 QualifierCollector qs; 9136 const PointerType* PT; 9137 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9138 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9139 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9140 Context.CharTy)) { 9141 qs.removeConst(); 9142 mismatch = !qs.empty(); 9143 } 9144 } 9145 9146 if (mismatch) { 9147 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9148 // TODO: suggest replacing given type with expected type 9149 FD->setInvalidDecl(true); 9150 } 9151 } 9152 9153 if (nparams == 1 && !FD->isInvalidDecl()) { 9154 Diag(FD->getLocation(), diag::warn_main_one_arg); 9155 } 9156 9157 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9158 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9159 FD->setInvalidDecl(); 9160 } 9161 } 9162 9163 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9164 QualType T = FD->getType(); 9165 assert(T->isFunctionType() && "function decl is not of function type"); 9166 const FunctionType *FT = T->castAs<FunctionType>(); 9167 9168 // Set an implicit return of 'zero' if the function can return some integral, 9169 // enumeration, pointer or nullptr type. 9170 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9171 FT->getReturnType()->isAnyPointerType() || 9172 FT->getReturnType()->isNullPtrType()) 9173 // DllMain is exempt because a return value of zero means it failed. 9174 if (FD->getName() != "DllMain") 9175 FD->setHasImplicitReturnZero(true); 9176 9177 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9178 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9179 FD->setInvalidDecl(); 9180 } 9181 } 9182 9183 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9184 // FIXME: Need strict checking. In C89, we need to check for 9185 // any assignment, increment, decrement, function-calls, or 9186 // commas outside of a sizeof. In C99, it's the same list, 9187 // except that the aforementioned are allowed in unevaluated 9188 // expressions. Everything else falls under the 9189 // "may accept other forms of constant expressions" exception. 9190 // (We never end up here for C++, so the constant expression 9191 // rules there don't matter.) 9192 const Expr *Culprit; 9193 if (Init->isConstantInitializer(Context, false, &Culprit)) 9194 return false; 9195 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9196 << Culprit->getSourceRange(); 9197 return true; 9198 } 9199 9200 namespace { 9201 // Visits an initialization expression to see if OrigDecl is evaluated in 9202 // its own initialization and throws a warning if it does. 9203 class SelfReferenceChecker 9204 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9205 Sema &S; 9206 Decl *OrigDecl; 9207 bool isRecordType; 9208 bool isPODType; 9209 bool isReferenceType; 9210 9211 bool isInitList; 9212 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9213 9214 public: 9215 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9216 9217 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9218 S(S), OrigDecl(OrigDecl) { 9219 isPODType = false; 9220 isRecordType = false; 9221 isReferenceType = false; 9222 isInitList = false; 9223 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9224 isPODType = VD->getType().isPODType(S.Context); 9225 isRecordType = VD->getType()->isRecordType(); 9226 isReferenceType = VD->getType()->isReferenceType(); 9227 } 9228 } 9229 9230 // For most expressions, just call the visitor. For initializer lists, 9231 // track the index of the field being initialized since fields are 9232 // initialized in order allowing use of previously initialized fields. 9233 void CheckExpr(Expr *E) { 9234 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9235 if (!InitList) { 9236 Visit(E); 9237 return; 9238 } 9239 9240 // Track and increment the index here. 9241 isInitList = true; 9242 InitFieldIndex.push_back(0); 9243 for (auto Child : InitList->children()) { 9244 CheckExpr(cast<Expr>(Child)); 9245 ++InitFieldIndex.back(); 9246 } 9247 InitFieldIndex.pop_back(); 9248 } 9249 9250 // Returns true if MemberExpr is checked and no futher checking is needed. 9251 // Returns false if additional checking is required. 9252 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9253 llvm::SmallVector<FieldDecl*, 4> Fields; 9254 Expr *Base = E; 9255 bool ReferenceField = false; 9256 9257 // Get the field memebers used. 9258 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9259 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9260 if (!FD) 9261 return false; 9262 Fields.push_back(FD); 9263 if (FD->getType()->isReferenceType()) 9264 ReferenceField = true; 9265 Base = ME->getBase()->IgnoreParenImpCasts(); 9266 } 9267 9268 // Keep checking only if the base Decl is the same. 9269 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9270 if (!DRE || DRE->getDecl() != OrigDecl) 9271 return false; 9272 9273 // A reference field can be bound to an unininitialized field. 9274 if (CheckReference && !ReferenceField) 9275 return true; 9276 9277 // Convert FieldDecls to their index number. 9278 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9279 for (const FieldDecl *I : llvm::reverse(Fields)) 9280 UsedFieldIndex.push_back(I->getFieldIndex()); 9281 9282 // See if a warning is needed by checking the first difference in index 9283 // numbers. If field being used has index less than the field being 9284 // initialized, then the use is safe. 9285 for (auto UsedIter = UsedFieldIndex.begin(), 9286 UsedEnd = UsedFieldIndex.end(), 9287 OrigIter = InitFieldIndex.begin(), 9288 OrigEnd = InitFieldIndex.end(); 9289 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9290 if (*UsedIter < *OrigIter) 9291 return true; 9292 if (*UsedIter > *OrigIter) 9293 break; 9294 } 9295 9296 // TODO: Add a different warning which will print the field names. 9297 HandleDeclRefExpr(DRE); 9298 return true; 9299 } 9300 9301 // For most expressions, the cast is directly above the DeclRefExpr. 9302 // For conditional operators, the cast can be outside the conditional 9303 // operator if both expressions are DeclRefExpr's. 9304 void HandleValue(Expr *E) { 9305 E = E->IgnoreParens(); 9306 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9307 HandleDeclRefExpr(DRE); 9308 return; 9309 } 9310 9311 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9312 Visit(CO->getCond()); 9313 HandleValue(CO->getTrueExpr()); 9314 HandleValue(CO->getFalseExpr()); 9315 return; 9316 } 9317 9318 if (BinaryConditionalOperator *BCO = 9319 dyn_cast<BinaryConditionalOperator>(E)) { 9320 Visit(BCO->getCond()); 9321 HandleValue(BCO->getFalseExpr()); 9322 return; 9323 } 9324 9325 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9326 HandleValue(OVE->getSourceExpr()); 9327 return; 9328 } 9329 9330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9331 if (BO->getOpcode() == BO_Comma) { 9332 Visit(BO->getLHS()); 9333 HandleValue(BO->getRHS()); 9334 return; 9335 } 9336 } 9337 9338 if (isa<MemberExpr>(E)) { 9339 if (isInitList) { 9340 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9341 false /*CheckReference*/)) 9342 return; 9343 } 9344 9345 Expr *Base = E->IgnoreParenImpCasts(); 9346 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9347 // Check for static member variables and don't warn on them. 9348 if (!isa<FieldDecl>(ME->getMemberDecl())) 9349 return; 9350 Base = ME->getBase()->IgnoreParenImpCasts(); 9351 } 9352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9353 HandleDeclRefExpr(DRE); 9354 return; 9355 } 9356 9357 Visit(E); 9358 } 9359 9360 // Reference types not handled in HandleValue are handled here since all 9361 // uses of references are bad, not just r-value uses. 9362 void VisitDeclRefExpr(DeclRefExpr *E) { 9363 if (isReferenceType) 9364 HandleDeclRefExpr(E); 9365 } 9366 9367 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9368 if (E->getCastKind() == CK_LValueToRValue) { 9369 HandleValue(E->getSubExpr()); 9370 return; 9371 } 9372 9373 Inherited::VisitImplicitCastExpr(E); 9374 } 9375 9376 void VisitMemberExpr(MemberExpr *E) { 9377 if (isInitList) { 9378 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9379 return; 9380 } 9381 9382 // Don't warn on arrays since they can be treated as pointers. 9383 if (E->getType()->canDecayToPointerType()) return; 9384 9385 // Warn when a non-static method call is followed by non-static member 9386 // field accesses, which is followed by a DeclRefExpr. 9387 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9388 bool Warn = (MD && !MD->isStatic()); 9389 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9390 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9391 if (!isa<FieldDecl>(ME->getMemberDecl())) 9392 Warn = false; 9393 Base = ME->getBase()->IgnoreParenImpCasts(); 9394 } 9395 9396 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9397 if (Warn) 9398 HandleDeclRefExpr(DRE); 9399 return; 9400 } 9401 9402 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9403 // Visit that expression. 9404 Visit(Base); 9405 } 9406 9407 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9408 Expr *Callee = E->getCallee(); 9409 9410 if (isa<UnresolvedLookupExpr>(Callee)) 9411 return Inherited::VisitCXXOperatorCallExpr(E); 9412 9413 Visit(Callee); 9414 for (auto Arg: E->arguments()) 9415 HandleValue(Arg->IgnoreParenImpCasts()); 9416 } 9417 9418 void VisitUnaryOperator(UnaryOperator *E) { 9419 // For POD record types, addresses of its own members are well-defined. 9420 if (E->getOpcode() == UO_AddrOf && isRecordType && 9421 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9422 if (!isPODType) 9423 HandleValue(E->getSubExpr()); 9424 return; 9425 } 9426 9427 if (E->isIncrementDecrementOp()) { 9428 HandleValue(E->getSubExpr()); 9429 return; 9430 } 9431 9432 Inherited::VisitUnaryOperator(E); 9433 } 9434 9435 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9436 9437 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9438 if (E->getConstructor()->isCopyConstructor()) { 9439 Expr *ArgExpr = E->getArg(0); 9440 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9441 if (ILE->getNumInits() == 1) 9442 ArgExpr = ILE->getInit(0); 9443 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9444 if (ICE->getCastKind() == CK_NoOp) 9445 ArgExpr = ICE->getSubExpr(); 9446 HandleValue(ArgExpr); 9447 return; 9448 } 9449 Inherited::VisitCXXConstructExpr(E); 9450 } 9451 9452 void VisitCallExpr(CallExpr *E) { 9453 // Treat std::move as a use. 9454 if (E->getNumArgs() == 1) { 9455 if (FunctionDecl *FD = E->getDirectCallee()) { 9456 if (FD->isInStdNamespace() && FD->getIdentifier() && 9457 FD->getIdentifier()->isStr("move")) { 9458 HandleValue(E->getArg(0)); 9459 return; 9460 } 9461 } 9462 } 9463 9464 Inherited::VisitCallExpr(E); 9465 } 9466 9467 void VisitBinaryOperator(BinaryOperator *E) { 9468 if (E->isCompoundAssignmentOp()) { 9469 HandleValue(E->getLHS()); 9470 Visit(E->getRHS()); 9471 return; 9472 } 9473 9474 Inherited::VisitBinaryOperator(E); 9475 } 9476 9477 // A custom visitor for BinaryConditionalOperator is needed because the 9478 // regular visitor would check the condition and true expression separately 9479 // but both point to the same place giving duplicate diagnostics. 9480 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9481 Visit(E->getCond()); 9482 Visit(E->getFalseExpr()); 9483 } 9484 9485 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9486 Decl* ReferenceDecl = DRE->getDecl(); 9487 if (OrigDecl != ReferenceDecl) return; 9488 unsigned diag; 9489 if (isReferenceType) { 9490 diag = diag::warn_uninit_self_reference_in_reference_init; 9491 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9492 diag = diag::warn_static_self_reference_in_init; 9493 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9494 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9495 DRE->getDecl()->getType()->isRecordType()) { 9496 diag = diag::warn_uninit_self_reference_in_init; 9497 } else { 9498 // Local variables will be handled by the CFG analysis. 9499 return; 9500 } 9501 9502 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9503 S.PDiag(diag) 9504 << DRE->getNameInfo().getName() 9505 << OrigDecl->getLocation() 9506 << DRE->getSourceRange()); 9507 } 9508 }; 9509 9510 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9511 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9512 bool DirectInit) { 9513 // Parameters arguments are occassionially constructed with itself, 9514 // for instance, in recursive functions. Skip them. 9515 if (isa<ParmVarDecl>(OrigDecl)) 9516 return; 9517 9518 E = E->IgnoreParens(); 9519 9520 // Skip checking T a = a where T is not a record or reference type. 9521 // Doing so is a way to silence uninitialized warnings. 9522 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9523 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9524 if (ICE->getCastKind() == CK_LValueToRValue) 9525 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9526 if (DRE->getDecl() == OrigDecl) 9527 return; 9528 9529 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9530 } 9531 } // end anonymous namespace 9532 9533 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9534 DeclarationName Name, QualType Type, 9535 TypeSourceInfo *TSI, 9536 SourceRange Range, bool DirectInit, 9537 Expr *Init) { 9538 bool IsInitCapture = !VDecl; 9539 assert((!VDecl || !VDecl->isInitCapture()) && 9540 "init captures are expected to be deduced prior to initialization"); 9541 9542 // FIXME: Deduction for a decomposition declaration does weird things if the 9543 // initializer is an array. 9544 9545 ArrayRef<Expr *> DeduceInits = Init; 9546 if (DirectInit) { 9547 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9548 DeduceInits = PL->exprs(); 9549 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9550 DeduceInits = IL->inits(); 9551 } 9552 9553 // Deduction only works if we have exactly one source expression. 9554 if (DeduceInits.empty()) { 9555 // It isn't possible to write this directly, but it is possible to 9556 // end up in this situation with "auto x(some_pack...);" 9557 Diag(Init->getLocStart(), IsInitCapture 9558 ? diag::err_init_capture_no_expression 9559 : diag::err_auto_var_init_no_expression) 9560 << Name << Type << Range; 9561 return QualType(); 9562 } 9563 9564 if (DeduceInits.size() > 1) { 9565 Diag(DeduceInits[1]->getLocStart(), 9566 IsInitCapture ? diag::err_init_capture_multiple_expressions 9567 : diag::err_auto_var_init_multiple_expressions) 9568 << Name << Type << Range; 9569 return QualType(); 9570 } 9571 9572 Expr *DeduceInit = DeduceInits[0]; 9573 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9574 Diag(Init->getLocStart(), IsInitCapture 9575 ? diag::err_init_capture_paren_braces 9576 : diag::err_auto_var_init_paren_braces) 9577 << isa<InitListExpr>(Init) << Name << Type << Range; 9578 return QualType(); 9579 } 9580 9581 // Expressions default to 'id' when we're in a debugger. 9582 bool DefaultedAnyToId = false; 9583 if (getLangOpts().DebuggerCastResultToId && 9584 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9585 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9586 if (Result.isInvalid()) { 9587 return QualType(); 9588 } 9589 Init = Result.get(); 9590 DefaultedAnyToId = true; 9591 } 9592 9593 QualType DeducedType; 9594 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9595 if (!IsInitCapture) 9596 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9597 else if (isa<InitListExpr>(Init)) 9598 Diag(Range.getBegin(), 9599 diag::err_init_capture_deduction_failure_from_init_list) 9600 << Name 9601 << (DeduceInit->getType().isNull() ? TSI->getType() 9602 : DeduceInit->getType()) 9603 << DeduceInit->getSourceRange(); 9604 else 9605 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9606 << Name << TSI->getType() 9607 << (DeduceInit->getType().isNull() ? TSI->getType() 9608 : DeduceInit->getType()) 9609 << DeduceInit->getSourceRange(); 9610 } 9611 9612 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9613 // 'id' instead of a specific object type prevents most of our usual 9614 // checks. 9615 // We only want to warn outside of template instantiations, though: 9616 // inside a template, the 'id' could have come from a parameter. 9617 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9618 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9619 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9620 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range; 9621 } 9622 9623 return DeducedType; 9624 } 9625 9626 /// AddInitializerToDecl - Adds the initializer Init to the 9627 /// declaration dcl. If DirectInit is true, this is C++ direct 9628 /// initialization rather than copy initialization. 9629 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 9630 bool DirectInit, bool TypeMayContainAuto) { 9631 // If there is no declaration, there was an error parsing it. Just ignore 9632 // the initializer. 9633 if (!RealDecl || RealDecl->isInvalidDecl()) { 9634 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9635 return; 9636 } 9637 9638 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9639 // Pure-specifiers are handled in ActOnPureSpecifier. 9640 Diag(Method->getLocation(), diag::err_member_function_initialization) 9641 << Method->getDeclName() << Init->getSourceRange(); 9642 Method->setInvalidDecl(); 9643 return; 9644 } 9645 9646 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9647 if (!VDecl) { 9648 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9649 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9650 RealDecl->setInvalidDecl(); 9651 return; 9652 } 9653 9654 // C++1z [dcl.dcl]p1 grammar implies that a parenthesized initializer is not 9655 // permitted. 9656 if (isa<DecompositionDecl>(VDecl) && DirectInit && isa<ParenListExpr>(Init)) 9657 Diag(VDecl->getLocation(), diag::err_decomp_decl_paren_init) << VDecl; 9658 9659 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9660 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 9661 // Attempt typo correction early so that the type of the init expression can 9662 // be deduced based on the chosen correction if the original init contains a 9663 // TypoExpr. 9664 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9665 if (!Res.isUsable()) { 9666 RealDecl->setInvalidDecl(); 9667 return; 9668 } 9669 Init = Res.get(); 9670 9671 QualType DeducedType = deduceVarTypeFromInitializer( 9672 VDecl, VDecl->getDeclName(), VDecl->getType(), 9673 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9674 if (DeducedType.isNull()) { 9675 RealDecl->setInvalidDecl(); 9676 return; 9677 } 9678 9679 VDecl->setType(DeducedType); 9680 assert(VDecl->isLinkageValid()); 9681 9682 // In ARC, infer lifetime. 9683 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9684 VDecl->setInvalidDecl(); 9685 9686 // If this is a redeclaration, check that the type we just deduced matches 9687 // the previously declared type. 9688 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9689 // We never need to merge the type, because we cannot form an incomplete 9690 // array of auto, nor deduce such a type. 9691 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9692 } 9693 9694 // Check the deduced type is valid for a variable declaration. 9695 CheckVariableDeclarationType(VDecl); 9696 if (VDecl->isInvalidDecl()) 9697 return; 9698 } 9699 9700 // dllimport cannot be used on variable definitions. 9701 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9702 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9703 VDecl->setInvalidDecl(); 9704 return; 9705 } 9706 9707 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9708 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9709 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9710 VDecl->setInvalidDecl(); 9711 return; 9712 } 9713 9714 if (!VDecl->getType()->isDependentType()) { 9715 // A definition must end up with a complete type, which means it must be 9716 // complete with the restriction that an array type might be completed by 9717 // the initializer; note that later code assumes this restriction. 9718 QualType BaseDeclType = VDecl->getType(); 9719 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9720 BaseDeclType = Array->getElementType(); 9721 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9722 diag::err_typecheck_decl_incomplete_type)) { 9723 RealDecl->setInvalidDecl(); 9724 return; 9725 } 9726 9727 // The variable can not have an abstract class type. 9728 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9729 diag::err_abstract_type_in_decl, 9730 AbstractVariableType)) 9731 VDecl->setInvalidDecl(); 9732 } 9733 9734 // If adding the initializer will turn this declaration into a definition, 9735 // and we already have a definition for this variable, diagnose or otherwise 9736 // handle the situation. 9737 VarDecl *Def; 9738 if ((Def = VDecl->getDefinition()) && Def != VDecl && 9739 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 9740 !VDecl->isThisDeclarationADemotedDefinition() && 9741 checkVarDeclRedefinition(Def, VDecl)) 9742 return; 9743 9744 if (getLangOpts().CPlusPlus) { 9745 // C++ [class.static.data]p4 9746 // If a static data member is of const integral or const 9747 // enumeration type, its declaration in the class definition can 9748 // specify a constant-initializer which shall be an integral 9749 // constant expression (5.19). In that case, the member can appear 9750 // in integral constant expressions. The member shall still be 9751 // defined in a namespace scope if it is used in the program and the 9752 // namespace scope definition shall not contain an initializer. 9753 // 9754 // We already performed a redefinition check above, but for static 9755 // data members we also need to check whether there was an in-class 9756 // declaration with an initializer. 9757 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9758 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9759 << VDecl->getDeclName(); 9760 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9761 diag::note_previous_initializer) 9762 << 0; 9763 return; 9764 } 9765 9766 if (VDecl->hasLocalStorage()) 9767 getCurFunction()->setHasBranchProtectedScope(); 9768 9769 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 9770 VDecl->setInvalidDecl(); 9771 return; 9772 } 9773 } 9774 9775 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 9776 // a kernel function cannot be initialized." 9777 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 9778 Diag(VDecl->getLocation(), diag::err_local_cant_init); 9779 VDecl->setInvalidDecl(); 9780 return; 9781 } 9782 9783 // Get the decls type and save a reference for later, since 9784 // CheckInitializerTypes may change it. 9785 QualType DclT = VDecl->getType(), SavT = DclT; 9786 9787 // Expressions default to 'id' when we're in a debugger 9788 // and we are assigning it to a variable of Objective-C pointer type. 9789 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 9790 Init->getType() == Context.UnknownAnyTy) { 9791 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9792 if (Result.isInvalid()) { 9793 VDecl->setInvalidDecl(); 9794 return; 9795 } 9796 Init = Result.get(); 9797 } 9798 9799 // Perform the initialization. 9800 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 9801 if (!VDecl->isInvalidDecl()) { 9802 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9803 InitializationKind Kind = 9804 DirectInit 9805 ? CXXDirectInit 9806 ? InitializationKind::CreateDirect(VDecl->getLocation(), 9807 Init->getLocStart(), 9808 Init->getLocEnd()) 9809 : InitializationKind::CreateDirectList(VDecl->getLocation()) 9810 : InitializationKind::CreateCopy(VDecl->getLocation(), 9811 Init->getLocStart()); 9812 9813 MultiExprArg Args = Init; 9814 if (CXXDirectInit) 9815 Args = MultiExprArg(CXXDirectInit->getExprs(), 9816 CXXDirectInit->getNumExprs()); 9817 9818 // Try to correct any TypoExprs in the initialization arguments. 9819 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9820 ExprResult Res = CorrectDelayedTyposInExpr( 9821 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9822 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9823 return Init.Failed() ? ExprError() : E; 9824 }); 9825 if (Res.isInvalid()) { 9826 VDecl->setInvalidDecl(); 9827 } else if (Res.get() != Args[Idx]) { 9828 Args[Idx] = Res.get(); 9829 } 9830 } 9831 if (VDecl->isInvalidDecl()) 9832 return; 9833 9834 InitializationSequence InitSeq(*this, Entity, Kind, Args, 9835 /*TopLevelOfInitList=*/false, 9836 /*TreatUnavailableAsInvalid=*/false); 9837 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9838 if (Result.isInvalid()) { 9839 VDecl->setInvalidDecl(); 9840 return; 9841 } 9842 9843 Init = Result.getAs<Expr>(); 9844 } 9845 9846 // Check for self-references within variable initializers. 9847 // Variables declared within a function/method body (except for references) 9848 // are handled by a dataflow analysis. 9849 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9850 VDecl->getType()->isReferenceType()) { 9851 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9852 } 9853 9854 // If the type changed, it means we had an incomplete type that was 9855 // completed by the initializer. For example: 9856 // int ary[] = { 1, 3, 5 }; 9857 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9858 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9859 VDecl->setType(DclT); 9860 9861 if (!VDecl->isInvalidDecl()) { 9862 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9863 9864 if (VDecl->hasAttr<BlocksAttr>()) 9865 checkRetainCycles(VDecl, Init); 9866 9867 // It is safe to assign a weak reference into a strong variable. 9868 // Although this code can still have problems: 9869 // id x = self.weakProp; 9870 // id y = self.weakProp; 9871 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9872 // paths through the function. This should be revisited if 9873 // -Wrepeated-use-of-weak is made flow-sensitive. 9874 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9875 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9876 Init->getLocStart())) 9877 getCurFunction()->markSafeWeakUse(Init); 9878 } 9879 9880 // The initialization is usually a full-expression. 9881 // 9882 // FIXME: If this is a braced initialization of an aggregate, it is not 9883 // an expression, and each individual field initializer is a separate 9884 // full-expression. For instance, in: 9885 // 9886 // struct Temp { ~Temp(); }; 9887 // struct S { S(Temp); }; 9888 // struct T { S a, b; } t = { Temp(), Temp() } 9889 // 9890 // we should destroy the first Temp before constructing the second. 9891 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9892 false, 9893 VDecl->isConstexpr()); 9894 if (Result.isInvalid()) { 9895 VDecl->setInvalidDecl(); 9896 return; 9897 } 9898 Init = Result.get(); 9899 9900 // Attach the initializer to the decl. 9901 VDecl->setInit(Init); 9902 9903 if (VDecl->isLocalVarDecl()) { 9904 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9905 // static storage duration shall be constant expressions or string literals. 9906 // C++ does not have this restriction. 9907 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9908 const Expr *Culprit; 9909 if (VDecl->getStorageClass() == SC_Static) 9910 CheckForConstantInitializer(Init, DclT); 9911 // C89 is stricter than C99 for non-static aggregate types. 9912 // C89 6.5.7p3: All the expressions [...] in an initializer list 9913 // for an object that has aggregate or union type shall be 9914 // constant expressions. 9915 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9916 isa<InitListExpr>(Init) && 9917 !Init->isConstantInitializer(Context, false, &Culprit)) 9918 Diag(Culprit->getExprLoc(), 9919 diag::ext_aggregate_init_not_constant) 9920 << Culprit->getSourceRange(); 9921 } 9922 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 9923 VDecl->getLexicalDeclContext()->isRecord()) { 9924 // This is an in-class initialization for a static data member, e.g., 9925 // 9926 // struct S { 9927 // static const int value = 17; 9928 // }; 9929 9930 // C++ [class.mem]p4: 9931 // A member-declarator can contain a constant-initializer only 9932 // if it declares a static member (9.4) of const integral or 9933 // const enumeration type, see 9.4.2. 9934 // 9935 // C++11 [class.static.data]p3: 9936 // If a non-volatile non-inline const static data member is of integral 9937 // or enumeration type, its declaration in the class definition can 9938 // specify a brace-or-equal-initializer in which every initalizer-clause 9939 // that is an assignment-expression is a constant expression. A static 9940 // data member of literal type can be declared in the class definition 9941 // with the constexpr specifier; if so, its declaration shall specify a 9942 // brace-or-equal-initializer in which every initializer-clause that is 9943 // an assignment-expression is a constant expression. 9944 9945 // Do nothing on dependent types. 9946 if (DclT->isDependentType()) { 9947 9948 // Allow any 'static constexpr' members, whether or not they are of literal 9949 // type. We separately check that every constexpr variable is of literal 9950 // type. 9951 } else if (VDecl->isConstexpr()) { 9952 9953 // Require constness. 9954 } else if (!DclT.isConstQualified()) { 9955 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9956 << Init->getSourceRange(); 9957 VDecl->setInvalidDecl(); 9958 9959 // We allow integer constant expressions in all cases. 9960 } else if (DclT->isIntegralOrEnumerationType()) { 9961 // Check whether the expression is a constant expression. 9962 SourceLocation Loc; 9963 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9964 // In C++11, a non-constexpr const static data member with an 9965 // in-class initializer cannot be volatile. 9966 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9967 else if (Init->isValueDependent()) 9968 ; // Nothing to check. 9969 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9970 ; // Ok, it's an ICE! 9971 else if (Init->isEvaluatable(Context)) { 9972 // If we can constant fold the initializer through heroics, accept it, 9973 // but report this as a use of an extension for -pedantic. 9974 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9975 << Init->getSourceRange(); 9976 } else { 9977 // Otherwise, this is some crazy unknown case. Report the issue at the 9978 // location provided by the isIntegerConstantExpr failed check. 9979 Diag(Loc, diag::err_in_class_initializer_non_constant) 9980 << Init->getSourceRange(); 9981 VDecl->setInvalidDecl(); 9982 } 9983 9984 // We allow foldable floating-point constants as an extension. 9985 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9986 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9987 // it anyway and provide a fixit to add the 'constexpr'. 9988 if (getLangOpts().CPlusPlus11) { 9989 Diag(VDecl->getLocation(), 9990 diag::ext_in_class_initializer_float_type_cxx11) 9991 << DclT << Init->getSourceRange(); 9992 Diag(VDecl->getLocStart(), 9993 diag::note_in_class_initializer_float_type_cxx11) 9994 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9995 } else { 9996 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9997 << DclT << Init->getSourceRange(); 9998 9999 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10000 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10001 << Init->getSourceRange(); 10002 VDecl->setInvalidDecl(); 10003 } 10004 } 10005 10006 // Suggest adding 'constexpr' in C++11 for literal types. 10007 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10008 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10009 << DclT << Init->getSourceRange() 10010 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10011 VDecl->setConstexpr(true); 10012 10013 } else { 10014 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10015 << DclT << Init->getSourceRange(); 10016 VDecl->setInvalidDecl(); 10017 } 10018 } else if (VDecl->isFileVarDecl()) { 10019 // In C, extern is typically used to avoid tentative definitions when 10020 // declaring variables in headers, but adding an intializer makes it a 10021 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10022 // In C++, extern is often used to give implictly static const variables 10023 // external linkage, so don't warn in that case. If selectany is present, 10024 // this might be header code intended for C and C++ inclusion, so apply the 10025 // C++ rules. 10026 if (VDecl->getStorageClass() == SC_Extern && 10027 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10028 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10029 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10030 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10031 Diag(VDecl->getLocation(), diag::warn_extern_init); 10032 10033 // C99 6.7.8p4. All file scoped initializers need to be constant. 10034 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10035 CheckForConstantInitializer(Init, DclT); 10036 } 10037 10038 // We will represent direct-initialization similarly to copy-initialization: 10039 // int x(1); -as-> int x = 1; 10040 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10041 // 10042 // Clients that want to distinguish between the two forms, can check for 10043 // direct initializer using VarDecl::getInitStyle(). 10044 // A major benefit is that clients that don't particularly care about which 10045 // exactly form was it (like the CodeGen) can handle both cases without 10046 // special case code. 10047 10048 // C++ 8.5p11: 10049 // The form of initialization (using parentheses or '=') is generally 10050 // insignificant, but does matter when the entity being initialized has a 10051 // class type. 10052 if (CXXDirectInit) { 10053 assert(DirectInit && "Call-style initializer must be direct init."); 10054 VDecl->setInitStyle(VarDecl::CallInit); 10055 } else if (DirectInit) { 10056 // This must be list-initialization. No other way is direct-initialization. 10057 VDecl->setInitStyle(VarDecl::ListInit); 10058 } 10059 10060 CheckCompleteVariableDeclaration(VDecl); 10061 } 10062 10063 /// ActOnInitializerError - Given that there was an error parsing an 10064 /// initializer for the given declaration, try to return to some form 10065 /// of sanity. 10066 void Sema::ActOnInitializerError(Decl *D) { 10067 // Our main concern here is re-establishing invariants like "a 10068 // variable's type is either dependent or complete". 10069 if (!D || D->isInvalidDecl()) return; 10070 10071 VarDecl *VD = dyn_cast<VarDecl>(D); 10072 if (!VD) return; 10073 10074 // Bindings are not usable if we can't make sense of the initializer. 10075 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10076 for (auto *BD : DD->bindings()) 10077 BD->setInvalidDecl(); 10078 10079 // Auto types are meaningless if we can't make sense of the initializer. 10080 if (ParsingInitForAutoVars.count(D)) { 10081 D->setInvalidDecl(); 10082 return; 10083 } 10084 10085 QualType Ty = VD->getType(); 10086 if (Ty->isDependentType()) return; 10087 10088 // Require a complete type. 10089 if (RequireCompleteType(VD->getLocation(), 10090 Context.getBaseElementType(Ty), 10091 diag::err_typecheck_decl_incomplete_type)) { 10092 VD->setInvalidDecl(); 10093 return; 10094 } 10095 10096 // Require a non-abstract type. 10097 if (RequireNonAbstractType(VD->getLocation(), Ty, 10098 diag::err_abstract_type_in_decl, 10099 AbstractVariableType)) { 10100 VD->setInvalidDecl(); 10101 return; 10102 } 10103 10104 // Don't bother complaining about constructors or destructors, 10105 // though. 10106 } 10107 10108 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 10109 bool TypeMayContainAuto) { 10110 // If there is no declaration, there was an error parsing it. Just ignore it. 10111 if (!RealDecl) 10112 return; 10113 10114 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10115 QualType Type = Var->getType(); 10116 10117 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10118 if (isa<DecompositionDecl>(RealDecl)) { 10119 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10120 Var->setInvalidDecl(); 10121 return; 10122 } 10123 10124 // C++11 [dcl.spec.auto]p3 10125 if (TypeMayContainAuto && Type->getContainedAutoType()) { 10126 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 10127 << Var->getDeclName() << Type; 10128 Var->setInvalidDecl(); 10129 return; 10130 } 10131 10132 // C++11 [class.static.data]p3: A static data member can be declared with 10133 // the constexpr specifier; if so, its declaration shall specify 10134 // a brace-or-equal-initializer. 10135 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10136 // the definition of a variable [...] or the declaration of a static data 10137 // member. 10138 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10139 !Var->isThisDeclarationADemotedDefinition()) { 10140 if (Var->isStaticDataMember()) { 10141 // C++1z removes the relevant rule; the in-class declaration is always 10142 // a definition there. 10143 if (!getLangOpts().CPlusPlus1z) { 10144 Diag(Var->getLocation(), 10145 diag::err_constexpr_static_mem_var_requires_init) 10146 << Var->getDeclName(); 10147 Var->setInvalidDecl(); 10148 return; 10149 } 10150 } else { 10151 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10152 Var->setInvalidDecl(); 10153 return; 10154 } 10155 } 10156 10157 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10158 // definition having the concept specifier is called a variable concept. A 10159 // concept definition refers to [...] a variable concept and its initializer. 10160 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10161 if (VTD->isConcept()) { 10162 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10163 Var->setInvalidDecl(); 10164 return; 10165 } 10166 } 10167 10168 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10169 // be initialized. 10170 if (!Var->isInvalidDecl() && 10171 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10172 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10173 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10174 Var->setInvalidDecl(); 10175 return; 10176 } 10177 10178 switch (Var->isThisDeclarationADefinition()) { 10179 case VarDecl::Definition: 10180 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10181 break; 10182 10183 // We have an out-of-line definition of a static data member 10184 // that has an in-class initializer, so we type-check this like 10185 // a declaration. 10186 // 10187 // Fall through 10188 10189 case VarDecl::DeclarationOnly: 10190 // It's only a declaration. 10191 10192 // Block scope. C99 6.7p7: If an identifier for an object is 10193 // declared with no linkage (C99 6.2.2p6), the type for the 10194 // object shall be complete. 10195 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10196 !Var->hasLinkage() && !Var->isInvalidDecl() && 10197 RequireCompleteType(Var->getLocation(), Type, 10198 diag::err_typecheck_decl_incomplete_type)) 10199 Var->setInvalidDecl(); 10200 10201 // Make sure that the type is not abstract. 10202 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10203 RequireNonAbstractType(Var->getLocation(), Type, 10204 diag::err_abstract_type_in_decl, 10205 AbstractVariableType)) 10206 Var->setInvalidDecl(); 10207 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10208 Var->getStorageClass() == SC_PrivateExtern) { 10209 Diag(Var->getLocation(), diag::warn_private_extern); 10210 Diag(Var->getLocation(), diag::note_private_extern); 10211 } 10212 10213 return; 10214 10215 case VarDecl::TentativeDefinition: 10216 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10217 // object that has file scope without an initializer, and without a 10218 // storage-class specifier or with the storage-class specifier "static", 10219 // constitutes a tentative definition. Note: A tentative definition with 10220 // external linkage is valid (C99 6.2.2p5). 10221 if (!Var->isInvalidDecl()) { 10222 if (const IncompleteArrayType *ArrayT 10223 = Context.getAsIncompleteArrayType(Type)) { 10224 if (RequireCompleteType(Var->getLocation(), 10225 ArrayT->getElementType(), 10226 diag::err_illegal_decl_array_incomplete_type)) 10227 Var->setInvalidDecl(); 10228 } else if (Var->getStorageClass() == SC_Static) { 10229 // C99 6.9.2p3: If the declaration of an identifier for an object is 10230 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10231 // declared type shall not be an incomplete type. 10232 // NOTE: code such as the following 10233 // static struct s; 10234 // struct s { int a; }; 10235 // is accepted by gcc. Hence here we issue a warning instead of 10236 // an error and we do not invalidate the static declaration. 10237 // NOTE: to avoid multiple warnings, only check the first declaration. 10238 if (Var->isFirstDecl()) 10239 RequireCompleteType(Var->getLocation(), Type, 10240 diag::ext_typecheck_decl_incomplete_type); 10241 } 10242 } 10243 10244 // Record the tentative definition; we're done. 10245 if (!Var->isInvalidDecl()) 10246 TentativeDefinitions.push_back(Var); 10247 return; 10248 } 10249 10250 // Provide a specific diagnostic for uninitialized variable 10251 // definitions with incomplete array type. 10252 if (Type->isIncompleteArrayType()) { 10253 Diag(Var->getLocation(), 10254 diag::err_typecheck_incomplete_array_needs_initializer); 10255 Var->setInvalidDecl(); 10256 return; 10257 } 10258 10259 // Provide a specific diagnostic for uninitialized variable 10260 // definitions with reference type. 10261 if (Type->isReferenceType()) { 10262 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10263 << Var->getDeclName() 10264 << SourceRange(Var->getLocation(), Var->getLocation()); 10265 Var->setInvalidDecl(); 10266 return; 10267 } 10268 10269 // Do not attempt to type-check the default initializer for a 10270 // variable with dependent type. 10271 if (Type->isDependentType()) 10272 return; 10273 10274 if (Var->isInvalidDecl()) 10275 return; 10276 10277 if (!Var->hasAttr<AliasAttr>()) { 10278 if (RequireCompleteType(Var->getLocation(), 10279 Context.getBaseElementType(Type), 10280 diag::err_typecheck_decl_incomplete_type)) { 10281 Var->setInvalidDecl(); 10282 return; 10283 } 10284 } else { 10285 return; 10286 } 10287 10288 // The variable can not have an abstract class type. 10289 if (RequireNonAbstractType(Var->getLocation(), Type, 10290 diag::err_abstract_type_in_decl, 10291 AbstractVariableType)) { 10292 Var->setInvalidDecl(); 10293 return; 10294 } 10295 10296 // Check for jumps past the implicit initializer. C++0x 10297 // clarifies that this applies to a "variable with automatic 10298 // storage duration", not a "local variable". 10299 // C++11 [stmt.dcl]p3 10300 // A program that jumps from a point where a variable with automatic 10301 // storage duration is not in scope to a point where it is in scope is 10302 // ill-formed unless the variable has scalar type, class type with a 10303 // trivial default constructor and a trivial destructor, a cv-qualified 10304 // version of one of these types, or an array of one of the preceding 10305 // types and is declared without an initializer. 10306 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10307 if (const RecordType *Record 10308 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10309 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10310 // Mark the function for further checking even if the looser rules of 10311 // C++11 do not require such checks, so that we can diagnose 10312 // incompatibilities with C++98. 10313 if (!CXXRecord->isPOD()) 10314 getCurFunction()->setHasBranchProtectedScope(); 10315 } 10316 } 10317 10318 // C++03 [dcl.init]p9: 10319 // If no initializer is specified for an object, and the 10320 // object is of (possibly cv-qualified) non-POD class type (or 10321 // array thereof), the object shall be default-initialized; if 10322 // the object is of const-qualified type, the underlying class 10323 // type shall have a user-declared default 10324 // constructor. Otherwise, if no initializer is specified for 10325 // a non- static object, the object and its subobjects, if 10326 // any, have an indeterminate initial value); if the object 10327 // or any of its subobjects are of const-qualified type, the 10328 // program is ill-formed. 10329 // C++0x [dcl.init]p11: 10330 // If no initializer is specified for an object, the object is 10331 // default-initialized; [...]. 10332 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10333 InitializationKind Kind 10334 = InitializationKind::CreateDefault(Var->getLocation()); 10335 10336 InitializationSequence InitSeq(*this, Entity, Kind, None); 10337 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10338 if (Init.isInvalid()) 10339 Var->setInvalidDecl(); 10340 else if (Init.get()) { 10341 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10342 // This is important for template substitution. 10343 Var->setInitStyle(VarDecl::CallInit); 10344 } 10345 10346 CheckCompleteVariableDeclaration(Var); 10347 } 10348 } 10349 10350 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10351 // If there is no declaration, there was an error parsing it. Ignore it. 10352 if (!D) 10353 return; 10354 10355 VarDecl *VD = dyn_cast<VarDecl>(D); 10356 if (!VD) { 10357 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10358 D->setInvalidDecl(); 10359 return; 10360 } 10361 10362 VD->setCXXForRangeDecl(true); 10363 10364 // for-range-declaration cannot be given a storage class specifier. 10365 int Error = -1; 10366 switch (VD->getStorageClass()) { 10367 case SC_None: 10368 break; 10369 case SC_Extern: 10370 Error = 0; 10371 break; 10372 case SC_Static: 10373 Error = 1; 10374 break; 10375 case SC_PrivateExtern: 10376 Error = 2; 10377 break; 10378 case SC_Auto: 10379 Error = 3; 10380 break; 10381 case SC_Register: 10382 Error = 4; 10383 break; 10384 } 10385 if (Error != -1) { 10386 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10387 << VD->getDeclName() << Error; 10388 D->setInvalidDecl(); 10389 } 10390 } 10391 10392 StmtResult 10393 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10394 IdentifierInfo *Ident, 10395 ParsedAttributes &Attrs, 10396 SourceLocation AttrEnd) { 10397 // C++1y [stmt.iter]p1: 10398 // A range-based for statement of the form 10399 // for ( for-range-identifier : for-range-initializer ) statement 10400 // is equivalent to 10401 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10402 DeclSpec DS(Attrs.getPool().getFactory()); 10403 10404 const char *PrevSpec; 10405 unsigned DiagID; 10406 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10407 getPrintingPolicy()); 10408 10409 Declarator D(DS, Declarator::ForContext); 10410 D.SetIdentifier(Ident, IdentLoc); 10411 D.takeAttributes(Attrs, AttrEnd); 10412 10413 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10414 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10415 EmptyAttrs, IdentLoc); 10416 Decl *Var = ActOnDeclarator(S, D); 10417 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10418 FinalizeDeclaration(Var); 10419 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10420 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10421 } 10422 10423 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10424 if (var->isInvalidDecl()) return; 10425 10426 if (getLangOpts().OpenCL) { 10427 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10428 // initialiser 10429 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10430 !var->hasInit()) { 10431 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10432 << 1 /*Init*/; 10433 var->setInvalidDecl(); 10434 return; 10435 } 10436 } 10437 10438 // In Objective-C, don't allow jumps past the implicit initialization of a 10439 // local retaining variable. 10440 if (getLangOpts().ObjC1 && 10441 var->hasLocalStorage()) { 10442 switch (var->getType().getObjCLifetime()) { 10443 case Qualifiers::OCL_None: 10444 case Qualifiers::OCL_ExplicitNone: 10445 case Qualifiers::OCL_Autoreleasing: 10446 break; 10447 10448 case Qualifiers::OCL_Weak: 10449 case Qualifiers::OCL_Strong: 10450 getCurFunction()->setHasBranchProtectedScope(); 10451 break; 10452 } 10453 } 10454 10455 // Warn about externally-visible variables being defined without a 10456 // prior declaration. We only want to do this for global 10457 // declarations, but we also specifically need to avoid doing it for 10458 // class members because the linkage of an anonymous class can 10459 // change if it's later given a typedef name. 10460 if (var->isThisDeclarationADefinition() && 10461 var->getDeclContext()->getRedeclContext()->isFileContext() && 10462 var->isExternallyVisible() && var->hasLinkage() && 10463 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10464 var->getLocation())) { 10465 // Find a previous declaration that's not a definition. 10466 VarDecl *prev = var->getPreviousDecl(); 10467 while (prev && prev->isThisDeclarationADefinition()) 10468 prev = prev->getPreviousDecl(); 10469 10470 if (!prev) 10471 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10472 } 10473 10474 // Cache the result of checking for constant initialization. 10475 Optional<bool> CacheHasConstInit; 10476 const Expr *CacheCulprit; 10477 auto checkConstInit = [&]() mutable { 10478 if (!CacheHasConstInit) 10479 CacheHasConstInit = var->getInit()->isConstantInitializer( 10480 Context, var->getType()->isReferenceType(), &CacheCulprit); 10481 return *CacheHasConstInit; 10482 }; 10483 10484 if (var->getTLSKind() == VarDecl::TLS_Static) { 10485 if (var->getType().isDestructedType()) { 10486 // GNU C++98 edits for __thread, [basic.start.term]p3: 10487 // The type of an object with thread storage duration shall not 10488 // have a non-trivial destructor. 10489 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10490 if (getLangOpts().CPlusPlus11) 10491 Diag(var->getLocation(), diag::note_use_thread_local); 10492 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10493 if (!checkConstInit()) { 10494 // GNU C++98 edits for __thread, [basic.start.init]p4: 10495 // An object of thread storage duration shall not require dynamic 10496 // initialization. 10497 // FIXME: Need strict checking here. 10498 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 10499 << CacheCulprit->getSourceRange(); 10500 if (getLangOpts().CPlusPlus11) 10501 Diag(var->getLocation(), diag::note_use_thread_local); 10502 } 10503 } 10504 } 10505 10506 // Apply section attributes and pragmas to global variables. 10507 bool GlobalStorage = var->hasGlobalStorage(); 10508 if (GlobalStorage && var->isThisDeclarationADefinition() && 10509 ActiveTemplateInstantiations.empty()) { 10510 PragmaStack<StringLiteral *> *Stack = nullptr; 10511 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10512 if (var->getType().isConstQualified()) 10513 Stack = &ConstSegStack; 10514 else if (!var->getInit()) { 10515 Stack = &BSSSegStack; 10516 SectionFlags |= ASTContext::PSF_Write; 10517 } else { 10518 Stack = &DataSegStack; 10519 SectionFlags |= ASTContext::PSF_Write; 10520 } 10521 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10522 var->addAttr(SectionAttr::CreateImplicit( 10523 Context, SectionAttr::Declspec_allocate, 10524 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10525 } 10526 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10527 if (UnifySection(SA->getName(), SectionFlags, var)) 10528 var->dropAttr<SectionAttr>(); 10529 10530 // Apply the init_seg attribute if this has an initializer. If the 10531 // initializer turns out to not be dynamic, we'll end up ignoring this 10532 // attribute. 10533 if (CurInitSeg && var->getInit()) 10534 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10535 CurInitSegLoc)); 10536 } 10537 10538 // All the following checks are C++ only. 10539 if (!getLangOpts().CPlusPlus) { 10540 // If this variable must be emitted, add it as an initializer for the 10541 // current module. 10542 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10543 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10544 return; 10545 } 10546 10547 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 10548 CheckCompleteDecompositionDeclaration(DD); 10549 10550 QualType type = var->getType(); 10551 if (type->isDependentType()) return; 10552 10553 // __block variables might require us to capture a copy-initializer. 10554 if (var->hasAttr<BlocksAttr>()) { 10555 // It's currently invalid to ever have a __block variable with an 10556 // array type; should we diagnose that here? 10557 10558 // Regardless, we don't want to ignore array nesting when 10559 // constructing this copy. 10560 if (type->isStructureOrClassType()) { 10561 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10562 SourceLocation poi = var->getLocation(); 10563 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10564 ExprResult result 10565 = PerformMoveOrCopyInitialization( 10566 InitializedEntity::InitializeBlock(poi, type, false), 10567 var, var->getType(), varRef, /*AllowNRVO=*/true); 10568 if (!result.isInvalid()) { 10569 result = MaybeCreateExprWithCleanups(result); 10570 Expr *init = result.getAs<Expr>(); 10571 Context.setBlockVarCopyInits(var, init); 10572 } 10573 } 10574 } 10575 10576 Expr *Init = var->getInit(); 10577 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10578 QualType baseType = Context.getBaseElementType(type); 10579 10580 if (!var->getDeclContext()->isDependentContext() && 10581 Init && !Init->isValueDependent()) { 10582 10583 if (var->isConstexpr()) { 10584 SmallVector<PartialDiagnosticAt, 8> Notes; 10585 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10586 SourceLocation DiagLoc = var->getLocation(); 10587 // If the note doesn't add any useful information other than a source 10588 // location, fold it into the primary diagnostic. 10589 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10590 diag::note_invalid_subexpr_in_const_expr) { 10591 DiagLoc = Notes[0].first; 10592 Notes.clear(); 10593 } 10594 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10595 << var << Init->getSourceRange(); 10596 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10597 Diag(Notes[I].first, Notes[I].second); 10598 } 10599 } else if (var->isUsableInConstantExpressions(Context)) { 10600 // Check whether the initializer of a const variable of integral or 10601 // enumeration type is an ICE now, since we can't tell whether it was 10602 // initialized by a constant expression if we check later. 10603 var->checkInitIsICE(); 10604 } 10605 10606 // Don't emit further diagnostics about constexpr globals since they 10607 // were just diagnosed. 10608 if (!var->isConstexpr() && GlobalStorage && 10609 var->hasAttr<RequireConstantInitAttr>()) { 10610 // FIXME: Need strict checking in C++03 here. 10611 bool DiagErr = getLangOpts().CPlusPlus11 10612 ? !var->checkInitIsICE() : !checkConstInit(); 10613 if (DiagErr) { 10614 auto attr = var->getAttr<RequireConstantInitAttr>(); 10615 Diag(var->getLocation(), diag::err_require_constant_init_failed) 10616 << Init->getSourceRange(); 10617 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 10618 << attr->getRange(); 10619 } 10620 } 10621 else if (!var->isConstexpr() && IsGlobal && 10622 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10623 var->getLocation())) { 10624 // Warn about globals which don't have a constant initializer. Don't 10625 // warn about globals with a non-trivial destructor because we already 10626 // warned about them. 10627 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10628 if (!(RD && !RD->hasTrivialDestructor())) { 10629 if (!checkConstInit()) 10630 Diag(var->getLocation(), diag::warn_global_constructor) 10631 << Init->getSourceRange(); 10632 } 10633 } 10634 } 10635 10636 // Require the destructor. 10637 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10638 FinalizeVarWithDestructor(var, recordType); 10639 10640 // If this variable must be emitted, add it as an initializer for the current 10641 // module. 10642 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10643 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10644 } 10645 10646 /// \brief Determines if a variable's alignment is dependent. 10647 static bool hasDependentAlignment(VarDecl *VD) { 10648 if (VD->getType()->isDependentType()) 10649 return true; 10650 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10651 if (I->isAlignmentDependent()) 10652 return true; 10653 return false; 10654 } 10655 10656 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10657 /// any semantic actions necessary after any initializer has been attached. 10658 void 10659 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10660 // Note that we are no longer parsing the initializer for this declaration. 10661 ParsingInitForAutoVars.erase(ThisDecl); 10662 10663 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10664 if (!VD) 10665 return; 10666 10667 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 10668 for (auto *BD : DD->bindings()) { 10669 if (ThisDecl->isInvalidDecl()) 10670 BD->setInvalidDecl(); 10671 FinalizeDeclaration(BD); 10672 } 10673 } 10674 10675 checkAttributesAfterMerging(*this, *VD); 10676 10677 // Perform TLS alignment check here after attributes attached to the variable 10678 // which may affect the alignment have been processed. Only perform the check 10679 // if the target has a maximum TLS alignment (zero means no constraints). 10680 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10681 // Protect the check so that it's not performed on dependent types and 10682 // dependent alignments (we can't determine the alignment in that case). 10683 if (VD->getTLSKind() && !hasDependentAlignment(VD)) { 10684 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10685 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10686 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10687 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10688 << (unsigned)MaxAlignChars.getQuantity(); 10689 } 10690 } 10691 } 10692 10693 if (VD->isStaticLocal()) { 10694 if (FunctionDecl *FD = 10695 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10696 // Static locals inherit dll attributes from their function. 10697 if (Attr *A = getDLLAttr(FD)) { 10698 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10699 NewAttr->setInherited(true); 10700 VD->addAttr(NewAttr); 10701 } 10702 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 10703 // function, only __shared__ variables may be declared with 10704 // static storage class. 10705 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 10706 CUDADiagIfDeviceCode(VD->getLocation(), 10707 diag::err_device_static_local_var) 10708 << CurrentCUDATarget()) 10709 VD->setInvalidDecl(); 10710 } 10711 } 10712 10713 // Perform check for initializers of device-side global variables. 10714 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 10715 // 7.5). We must also apply the same checks to all __shared__ 10716 // variables whether they are local or not. CUDA also allows 10717 // constant initializers for __constant__ and __device__ variables. 10718 if (getLangOpts().CUDA) { 10719 const Expr *Init = VD->getInit(); 10720 if (Init && VD->hasGlobalStorage()) { 10721 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 10722 VD->hasAttr<CUDASharedAttr>()) { 10723 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 10724 bool AllowedInit = false; 10725 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 10726 AllowedInit = 10727 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 10728 // We'll allow constant initializers even if it's a non-empty 10729 // constructor according to CUDA rules. This deviates from NVCC, 10730 // but allows us to handle things like constexpr constructors. 10731 if (!AllowedInit && 10732 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 10733 AllowedInit = VD->getInit()->isConstantInitializer( 10734 Context, VD->getType()->isReferenceType()); 10735 10736 // Also make sure that destructor, if there is one, is empty. 10737 if (AllowedInit) 10738 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 10739 AllowedInit = 10740 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 10741 10742 if (!AllowedInit) { 10743 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 10744 ? diag::err_shared_var_init 10745 : diag::err_dynamic_var_init) 10746 << Init->getSourceRange(); 10747 VD->setInvalidDecl(); 10748 } 10749 } else { 10750 // This is a host-side global variable. Check that the initializer is 10751 // callable from the host side. 10752 const FunctionDecl *InitFn = nullptr; 10753 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 10754 InitFn = CE->getConstructor(); 10755 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 10756 InitFn = CE->getDirectCallee(); 10757 } 10758 if (InitFn) { 10759 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 10760 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 10761 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 10762 << InitFnTarget << InitFn; 10763 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 10764 VD->setInvalidDecl(); 10765 } 10766 } 10767 } 10768 } 10769 } 10770 10771 // Grab the dllimport or dllexport attribute off of the VarDecl. 10772 const InheritableAttr *DLLAttr = getDLLAttr(VD); 10773 10774 // Imported static data members cannot be defined out-of-line. 10775 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 10776 if (VD->isStaticDataMember() && VD->isOutOfLine() && 10777 VD->isThisDeclarationADefinition()) { 10778 // We allow definitions of dllimport class template static data members 10779 // with a warning. 10780 CXXRecordDecl *Context = 10781 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 10782 bool IsClassTemplateMember = 10783 isa<ClassTemplatePartialSpecializationDecl>(Context) || 10784 Context->getDescribedClassTemplate(); 10785 10786 Diag(VD->getLocation(), 10787 IsClassTemplateMember 10788 ? diag::warn_attribute_dllimport_static_field_definition 10789 : diag::err_attribute_dllimport_static_field_definition); 10790 Diag(IA->getLocation(), diag::note_attribute); 10791 if (!IsClassTemplateMember) 10792 VD->setInvalidDecl(); 10793 } 10794 } 10795 10796 // dllimport/dllexport variables cannot be thread local, their TLS index 10797 // isn't exported with the variable. 10798 if (DLLAttr && VD->getTLSKind()) { 10799 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 10800 if (F && getDLLAttr(F)) { 10801 assert(VD->isStaticLocal()); 10802 // But if this is a static local in a dlimport/dllexport function, the 10803 // function will never be inlined, which means the var would never be 10804 // imported, so having it marked import/export is safe. 10805 } else { 10806 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 10807 << DLLAttr; 10808 VD->setInvalidDecl(); 10809 } 10810 } 10811 10812 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 10813 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 10814 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 10815 VD->dropAttr<UsedAttr>(); 10816 } 10817 } 10818 10819 const DeclContext *DC = VD->getDeclContext(); 10820 // If there's a #pragma GCC visibility in scope, and this isn't a class 10821 // member, set the visibility of this variable. 10822 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 10823 AddPushedVisibilityAttribute(VD); 10824 10825 // FIXME: Warn on unused templates. 10826 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 10827 !isa<VarTemplatePartialSpecializationDecl>(VD)) 10828 MarkUnusedFileScopedDecl(VD); 10829 10830 // Now we have parsed the initializer and can update the table of magic 10831 // tag values. 10832 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 10833 !VD->getType()->isIntegralOrEnumerationType()) 10834 return; 10835 10836 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 10837 const Expr *MagicValueExpr = VD->getInit(); 10838 if (!MagicValueExpr) { 10839 continue; 10840 } 10841 llvm::APSInt MagicValueInt; 10842 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 10843 Diag(I->getRange().getBegin(), 10844 diag::err_type_tag_for_datatype_not_ice) 10845 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10846 continue; 10847 } 10848 if (MagicValueInt.getActiveBits() > 64) { 10849 Diag(I->getRange().getBegin(), 10850 diag::err_type_tag_for_datatype_too_large) 10851 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10852 continue; 10853 } 10854 uint64_t MagicValue = MagicValueInt.getZExtValue(); 10855 RegisterTypeTagForDatatype(I->getArgumentKind(), 10856 MagicValue, 10857 I->getMatchingCType(), 10858 I->getLayoutCompatible(), 10859 I->getMustBeNull()); 10860 } 10861 } 10862 10863 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 10864 ArrayRef<Decl *> Group) { 10865 SmallVector<Decl*, 8> Decls; 10866 10867 if (DS.isTypeSpecOwned()) 10868 Decls.push_back(DS.getRepAsDecl()); 10869 10870 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 10871 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 10872 bool DiagnosedMultipleDecomps = false; 10873 10874 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10875 if (Decl *D = Group[i]) { 10876 auto *DD = dyn_cast<DeclaratorDecl>(D); 10877 if (DD && !FirstDeclaratorInGroup) 10878 FirstDeclaratorInGroup = DD; 10879 10880 auto *Decomp = dyn_cast<DecompositionDecl>(D); 10881 if (Decomp && !FirstDecompDeclaratorInGroup) 10882 FirstDecompDeclaratorInGroup = Decomp; 10883 10884 // A decomposition declaration cannot be combined with any other 10885 // declaration in the same group. 10886 auto *OtherDD = FirstDeclaratorInGroup; 10887 if (OtherDD == FirstDecompDeclaratorInGroup) 10888 OtherDD = DD; 10889 if (OtherDD && FirstDecompDeclaratorInGroup && 10890 OtherDD != FirstDecompDeclaratorInGroup && 10891 !DiagnosedMultipleDecomps) { 10892 Diag(FirstDecompDeclaratorInGroup->getLocation(), 10893 diag::err_decomp_decl_not_alone) 10894 << OtherDD->getSourceRange(); 10895 DiagnosedMultipleDecomps = true; 10896 } 10897 10898 Decls.push_back(D); 10899 } 10900 } 10901 10902 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 10903 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 10904 handleTagNumbering(Tag, S); 10905 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 10906 getLangOpts().CPlusPlus) 10907 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 10908 } 10909 } 10910 10911 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 10912 } 10913 10914 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 10915 /// group, performing any necessary semantic checking. 10916 Sema::DeclGroupPtrTy 10917 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 10918 bool TypeMayContainAuto) { 10919 // C++0x [dcl.spec.auto]p7: 10920 // If the type deduced for the template parameter U is not the same in each 10921 // deduction, the program is ill-formed. 10922 // FIXME: When initializer-list support is added, a distinction is needed 10923 // between the deduced type U and the deduced type which 'auto' stands for. 10924 // auto a = 0, b = { 1, 2, 3 }; 10925 // is legal because the deduced type U is 'int' in both cases. 10926 if (TypeMayContainAuto && Group.size() > 1) { 10927 QualType Deduced; 10928 CanQualType DeducedCanon; 10929 VarDecl *DeducedDecl = nullptr; 10930 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10931 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 10932 AutoType *AT = D->getType()->getContainedAutoType(); 10933 // Don't reissue diagnostics when instantiating a template. 10934 if (AT && D->isInvalidDecl()) 10935 break; 10936 QualType U = AT ? AT->getDeducedType() : QualType(); 10937 if (!U.isNull()) { 10938 CanQualType UCanon = Context.getCanonicalType(U); 10939 if (Deduced.isNull()) { 10940 Deduced = U; 10941 DeducedCanon = UCanon; 10942 DeducedDecl = D; 10943 } else if (DeducedCanon != UCanon) { 10944 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 10945 diag::err_auto_different_deductions) 10946 << (unsigned)AT->getKeyword() 10947 << Deduced << DeducedDecl->getDeclName() 10948 << U << D->getDeclName() 10949 << DeducedDecl->getInit()->getSourceRange() 10950 << D->getInit()->getSourceRange(); 10951 D->setInvalidDecl(); 10952 break; 10953 } 10954 } 10955 } 10956 } 10957 } 10958 10959 ActOnDocumentableDecls(Group); 10960 10961 return DeclGroupPtrTy::make( 10962 DeclGroupRef::Create(Context, Group.data(), Group.size())); 10963 } 10964 10965 void Sema::ActOnDocumentableDecl(Decl *D) { 10966 ActOnDocumentableDecls(D); 10967 } 10968 10969 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 10970 // Don't parse the comment if Doxygen diagnostics are ignored. 10971 if (Group.empty() || !Group[0]) 10972 return; 10973 10974 if (Diags.isIgnored(diag::warn_doc_param_not_found, 10975 Group[0]->getLocation()) && 10976 Diags.isIgnored(diag::warn_unknown_comment_command_name, 10977 Group[0]->getLocation())) 10978 return; 10979 10980 if (Group.size() >= 2) { 10981 // This is a decl group. Normally it will contain only declarations 10982 // produced from declarator list. But in case we have any definitions or 10983 // additional declaration references: 10984 // 'typedef struct S {} S;' 10985 // 'typedef struct S *S;' 10986 // 'struct S *pS;' 10987 // FinalizeDeclaratorGroup adds these as separate declarations. 10988 Decl *MaybeTagDecl = Group[0]; 10989 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 10990 Group = Group.slice(1); 10991 } 10992 } 10993 10994 // See if there are any new comments that are not attached to a decl. 10995 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 10996 if (!Comments.empty() && 10997 !Comments.back()->isAttached()) { 10998 // There is at least one comment that not attached to a decl. 10999 // Maybe it should be attached to one of these decls? 11000 // 11001 // Note that this way we pick up not only comments that precede the 11002 // declaration, but also comments that *follow* the declaration -- thanks to 11003 // the lookahead in the lexer: we've consumed the semicolon and looked 11004 // ahead through comments. 11005 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11006 Context.getCommentForDecl(Group[i], &PP); 11007 } 11008 } 11009 11010 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11011 /// to introduce parameters into function prototype scope. 11012 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11013 const DeclSpec &DS = D.getDeclSpec(); 11014 11015 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11016 11017 // C++03 [dcl.stc]p2 also permits 'auto'. 11018 StorageClass SC = SC_None; 11019 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11020 SC = SC_Register; 11021 } else if (getLangOpts().CPlusPlus && 11022 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11023 SC = SC_Auto; 11024 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11025 Diag(DS.getStorageClassSpecLoc(), 11026 diag::err_invalid_storage_class_in_func_decl); 11027 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11028 } 11029 11030 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11031 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11032 << DeclSpec::getSpecifierName(TSCS); 11033 if (DS.isInlineSpecified()) 11034 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11035 << getLangOpts().CPlusPlus1z; 11036 if (DS.isConstexprSpecified()) 11037 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11038 << 0; 11039 if (DS.isConceptSpecified()) 11040 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11041 11042 DiagnoseFunctionSpecifiers(DS); 11043 11044 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11045 QualType parmDeclType = TInfo->getType(); 11046 11047 if (getLangOpts().CPlusPlus) { 11048 // Check that there are no default arguments inside the type of this 11049 // parameter. 11050 CheckExtraCXXDefaultArguments(D); 11051 11052 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11053 if (D.getCXXScopeSpec().isSet()) { 11054 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11055 << D.getCXXScopeSpec().getRange(); 11056 D.getCXXScopeSpec().clear(); 11057 } 11058 } 11059 11060 // Ensure we have a valid name 11061 IdentifierInfo *II = nullptr; 11062 if (D.hasName()) { 11063 II = D.getIdentifier(); 11064 if (!II) { 11065 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11066 << GetNameForDeclarator(D).getName(); 11067 D.setInvalidType(true); 11068 } 11069 } 11070 11071 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11072 if (II) { 11073 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11074 ForRedeclaration); 11075 LookupName(R, S); 11076 if (R.isSingleResult()) { 11077 NamedDecl *PrevDecl = R.getFoundDecl(); 11078 if (PrevDecl->isTemplateParameter()) { 11079 // Maybe we will complain about the shadowed template parameter. 11080 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11081 // Just pretend that we didn't see the previous declaration. 11082 PrevDecl = nullptr; 11083 } else if (S->isDeclScope(PrevDecl)) { 11084 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11085 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11086 11087 // Recover by removing the name 11088 II = nullptr; 11089 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11090 D.setInvalidType(true); 11091 } 11092 } 11093 } 11094 11095 // Temporarily put parameter variables in the translation unit, not 11096 // the enclosing context. This prevents them from accidentally 11097 // looking like class members in C++. 11098 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11099 D.getLocStart(), 11100 D.getIdentifierLoc(), II, 11101 parmDeclType, TInfo, 11102 SC); 11103 11104 if (D.isInvalidType()) 11105 New->setInvalidDecl(); 11106 11107 assert(S->isFunctionPrototypeScope()); 11108 assert(S->getFunctionPrototypeDepth() >= 1); 11109 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11110 S->getNextFunctionPrototypeIndex()); 11111 11112 // Add the parameter declaration into this scope. 11113 S->AddDecl(New); 11114 if (II) 11115 IdResolver.AddDecl(New); 11116 11117 ProcessDeclAttributes(S, New, D); 11118 11119 if (D.getDeclSpec().isModulePrivateSpecified()) 11120 Diag(New->getLocation(), diag::err_module_private_local) 11121 << 1 << New->getDeclName() 11122 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11123 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11124 11125 if (New->hasAttr<BlocksAttr>()) { 11126 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11127 } 11128 return New; 11129 } 11130 11131 /// \brief Synthesizes a variable for a parameter arising from a 11132 /// typedef. 11133 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11134 SourceLocation Loc, 11135 QualType T) { 11136 /* FIXME: setting StartLoc == Loc. 11137 Would it be worth to modify callers so as to provide proper source 11138 location for the unnamed parameters, embedding the parameter's type? */ 11139 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11140 T, Context.getTrivialTypeSourceInfo(T, Loc), 11141 SC_None, nullptr); 11142 Param->setImplicit(); 11143 return Param; 11144 } 11145 11146 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11147 // Don't diagnose unused-parameter errors in template instantiations; we 11148 // will already have done so in the template itself. 11149 if (!ActiveTemplateInstantiations.empty()) 11150 return; 11151 11152 for (const ParmVarDecl *Parameter : Parameters) { 11153 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11154 !Parameter->hasAttr<UnusedAttr>()) { 11155 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11156 << Parameter->getDeclName(); 11157 } 11158 } 11159 } 11160 11161 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11162 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11163 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11164 return; 11165 11166 // Warn if the return value is pass-by-value and larger than the specified 11167 // threshold. 11168 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11169 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11170 if (Size > LangOpts.NumLargeByValueCopy) 11171 Diag(D->getLocation(), diag::warn_return_value_size) 11172 << D->getDeclName() << Size; 11173 } 11174 11175 // Warn if any parameter is pass-by-value and larger than the specified 11176 // threshold. 11177 for (const ParmVarDecl *Parameter : Parameters) { 11178 QualType T = Parameter->getType(); 11179 if (T->isDependentType() || !T.isPODType(Context)) 11180 continue; 11181 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11182 if (Size > LangOpts.NumLargeByValueCopy) 11183 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11184 << Parameter->getDeclName() << Size; 11185 } 11186 } 11187 11188 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11189 SourceLocation NameLoc, IdentifierInfo *Name, 11190 QualType T, TypeSourceInfo *TSInfo, 11191 StorageClass SC) { 11192 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11193 if (getLangOpts().ObjCAutoRefCount && 11194 T.getObjCLifetime() == Qualifiers::OCL_None && 11195 T->isObjCLifetimeType()) { 11196 11197 Qualifiers::ObjCLifetime lifetime; 11198 11199 // Special cases for arrays: 11200 // - if it's const, use __unsafe_unretained 11201 // - otherwise, it's an error 11202 if (T->isArrayType()) { 11203 if (!T.isConstQualified()) { 11204 DelayedDiagnostics.add( 11205 sema::DelayedDiagnostic::makeForbiddenType( 11206 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11207 } 11208 lifetime = Qualifiers::OCL_ExplicitNone; 11209 } else { 11210 lifetime = T->getObjCARCImplicitLifetime(); 11211 } 11212 T = Context.getLifetimeQualifiedType(T, lifetime); 11213 } 11214 11215 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11216 Context.getAdjustedParameterType(T), 11217 TSInfo, SC, nullptr); 11218 11219 // Parameters can not be abstract class types. 11220 // For record types, this is done by the AbstractClassUsageDiagnoser once 11221 // the class has been completely parsed. 11222 if (!CurContext->isRecord() && 11223 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11224 AbstractParamType)) 11225 New->setInvalidDecl(); 11226 11227 // Parameter declarators cannot be interface types. All ObjC objects are 11228 // passed by reference. 11229 if (T->isObjCObjectType()) { 11230 SourceLocation TypeEndLoc = 11231 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11232 Diag(NameLoc, 11233 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11234 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11235 T = Context.getObjCObjectPointerType(T); 11236 New->setType(T); 11237 } 11238 11239 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11240 // duration shall not be qualified by an address-space qualifier." 11241 // Since all parameters have automatic store duration, they can not have 11242 // an address space. 11243 if (T.getAddressSpace() != 0) { 11244 // OpenCL allows function arguments declared to be an array of a type 11245 // to be qualified with an address space. 11246 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11247 Diag(NameLoc, diag::err_arg_with_address_space); 11248 New->setInvalidDecl(); 11249 } 11250 } 11251 11252 return New; 11253 } 11254 11255 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11256 SourceLocation LocAfterDecls) { 11257 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11258 11259 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11260 // for a K&R function. 11261 if (!FTI.hasPrototype) { 11262 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11263 --i; 11264 if (FTI.Params[i].Param == nullptr) { 11265 SmallString<256> Code; 11266 llvm::raw_svector_ostream(Code) 11267 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11268 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11269 << FTI.Params[i].Ident 11270 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11271 11272 // Implicitly declare the argument as type 'int' for lack of a better 11273 // type. 11274 AttributeFactory attrs; 11275 DeclSpec DS(attrs); 11276 const char* PrevSpec; // unused 11277 unsigned DiagID; // unused 11278 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11279 DiagID, Context.getPrintingPolicy()); 11280 // Use the identifier location for the type source range. 11281 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11282 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11283 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11284 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11285 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11286 } 11287 } 11288 } 11289 } 11290 11291 Decl * 11292 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11293 MultiTemplateParamsArg TemplateParameterLists, 11294 SkipBodyInfo *SkipBody) { 11295 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11296 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11297 Scope *ParentScope = FnBodyScope->getParent(); 11298 11299 D.setFunctionDefinitionKind(FDK_Definition); 11300 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11301 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11302 } 11303 11304 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11305 Consumer.HandleInlineFunctionDefinition(D); 11306 } 11307 11308 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11309 const FunctionDecl*& PossibleZeroParamPrototype) { 11310 // Don't warn about invalid declarations. 11311 if (FD->isInvalidDecl()) 11312 return false; 11313 11314 // Or declarations that aren't global. 11315 if (!FD->isGlobal()) 11316 return false; 11317 11318 // Don't warn about C++ member functions. 11319 if (isa<CXXMethodDecl>(FD)) 11320 return false; 11321 11322 // Don't warn about 'main'. 11323 if (FD->isMain()) 11324 return false; 11325 11326 // Don't warn about inline functions. 11327 if (FD->isInlined()) 11328 return false; 11329 11330 // Don't warn about function templates. 11331 if (FD->getDescribedFunctionTemplate()) 11332 return false; 11333 11334 // Don't warn about function template specializations. 11335 if (FD->isFunctionTemplateSpecialization()) 11336 return false; 11337 11338 // Don't warn for OpenCL kernels. 11339 if (FD->hasAttr<OpenCLKernelAttr>()) 11340 return false; 11341 11342 // Don't warn on explicitly deleted functions. 11343 if (FD->isDeleted()) 11344 return false; 11345 11346 bool MissingPrototype = true; 11347 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11348 Prev; Prev = Prev->getPreviousDecl()) { 11349 // Ignore any declarations that occur in function or method 11350 // scope, because they aren't visible from the header. 11351 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11352 continue; 11353 11354 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11355 if (FD->getNumParams() == 0) 11356 PossibleZeroParamPrototype = Prev; 11357 break; 11358 } 11359 11360 return MissingPrototype; 11361 } 11362 11363 void 11364 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11365 const FunctionDecl *EffectiveDefinition, 11366 SkipBodyInfo *SkipBody) { 11367 // Don't complain if we're in GNU89 mode and the previous definition 11368 // was an extern inline function. 11369 const FunctionDecl *Definition = EffectiveDefinition; 11370 if (!Definition) 11371 if (!FD->isDefined(Definition)) 11372 return; 11373 11374 if (canRedefineFunction(Definition, getLangOpts())) 11375 return; 11376 11377 // If we don't have a visible definition of the function, and it's inline or 11378 // a template, skip the new definition. 11379 if (SkipBody && !hasVisibleDefinition(Definition) && 11380 (Definition->getFormalLinkage() == InternalLinkage || 11381 Definition->isInlined() || 11382 Definition->getDescribedFunctionTemplate() || 11383 Definition->getNumTemplateParameterLists())) { 11384 SkipBody->ShouldSkip = true; 11385 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11386 makeMergedDefinitionVisible(TD, FD->getLocation()); 11387 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 11388 FD->getLocation()); 11389 return; 11390 } 11391 11392 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11393 Definition->getStorageClass() == SC_Extern) 11394 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11395 << FD->getDeclName() << getLangOpts().CPlusPlus; 11396 else 11397 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11398 11399 Diag(Definition->getLocation(), diag::note_previous_definition); 11400 FD->setInvalidDecl(); 11401 } 11402 11403 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11404 Sema &S) { 11405 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11406 11407 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11408 LSI->CallOperator = CallOperator; 11409 LSI->Lambda = LambdaClass; 11410 LSI->ReturnType = CallOperator->getReturnType(); 11411 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11412 11413 if (LCD == LCD_None) 11414 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11415 else if (LCD == LCD_ByCopy) 11416 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11417 else if (LCD == LCD_ByRef) 11418 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11419 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11420 11421 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11422 LSI->Mutable = !CallOperator->isConst(); 11423 11424 // Add the captures to the LSI so they can be noted as already 11425 // captured within tryCaptureVar. 11426 auto I = LambdaClass->field_begin(); 11427 for (const auto &C : LambdaClass->captures()) { 11428 if (C.capturesVariable()) { 11429 VarDecl *VD = C.getCapturedVar(); 11430 if (VD->isInitCapture()) 11431 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11432 QualType CaptureType = VD->getType(); 11433 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11434 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11435 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11436 /*EllipsisLoc*/C.isPackExpansion() 11437 ? C.getEllipsisLoc() : SourceLocation(), 11438 CaptureType, /*Expr*/ nullptr); 11439 11440 } else if (C.capturesThis()) { 11441 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11442 /*Expr*/ nullptr, 11443 C.getCaptureKind() == LCK_StarThis); 11444 } else { 11445 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11446 } 11447 ++I; 11448 } 11449 } 11450 11451 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11452 SkipBodyInfo *SkipBody) { 11453 // Clear the last template instantiation error context. 11454 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 11455 11456 if (!D) 11457 return D; 11458 FunctionDecl *FD = nullptr; 11459 11460 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11461 FD = FunTmpl->getTemplatedDecl(); 11462 else 11463 FD = cast<FunctionDecl>(D); 11464 11465 // See if this is a redefinition. 11466 if (!FD->isLateTemplateParsed()) { 11467 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11468 11469 // If we're skipping the body, we're done. Don't enter the scope. 11470 if (SkipBody && SkipBody->ShouldSkip) 11471 return D; 11472 } 11473 11474 // Mark this function as "will have a body eventually". This lets users to 11475 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 11476 // this function. 11477 FD->setWillHaveBody(); 11478 11479 // If we are instantiating a generic lambda call operator, push 11480 // a LambdaScopeInfo onto the function stack. But use the information 11481 // that's already been calculated (ActOnLambdaExpr) to prime the current 11482 // LambdaScopeInfo. 11483 // When the template operator is being specialized, the LambdaScopeInfo, 11484 // has to be properly restored so that tryCaptureVariable doesn't try 11485 // and capture any new variables. In addition when calculating potential 11486 // captures during transformation of nested lambdas, it is necessary to 11487 // have the LSI properly restored. 11488 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11489 assert(ActiveTemplateInstantiations.size() && 11490 "There should be an active template instantiation on the stack " 11491 "when instantiating a generic lambda!"); 11492 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 11493 } 11494 else 11495 // Enter a new function scope 11496 PushFunctionScope(); 11497 11498 // Builtin functions cannot be defined. 11499 if (unsigned BuiltinID = FD->getBuiltinID()) { 11500 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 11501 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 11502 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 11503 FD->setInvalidDecl(); 11504 } 11505 } 11506 11507 // The return type of a function definition must be complete 11508 // (C99 6.9.1p3, C++ [dcl.fct]p6). 11509 QualType ResultType = FD->getReturnType(); 11510 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 11511 !FD->isInvalidDecl() && 11512 RequireCompleteType(FD->getLocation(), ResultType, 11513 diag::err_func_def_incomplete_result)) 11514 FD->setInvalidDecl(); 11515 11516 if (FnBodyScope) 11517 PushDeclContext(FnBodyScope, FD); 11518 11519 // Check the validity of our function parameters 11520 CheckParmsForFunctionDef(FD->parameters(), 11521 /*CheckParameterNames=*/true); 11522 11523 // Introduce our parameters into the function scope 11524 for (auto Param : FD->parameters()) { 11525 Param->setOwningFunction(FD); 11526 11527 // If this has an identifier, add it to the scope stack. 11528 if (Param->getIdentifier() && FnBodyScope) { 11529 CheckShadow(FnBodyScope, Param); 11530 11531 PushOnScopeChains(Param, FnBodyScope); 11532 } 11533 } 11534 11535 // If we had any tags defined in the function prototype, 11536 // introduce them into the function scope. 11537 if (FnBodyScope) { 11538 for (ArrayRef<NamedDecl *>::iterator 11539 I = FD->getDeclsInPrototypeScope().begin(), 11540 E = FD->getDeclsInPrototypeScope().end(); 11541 I != E; ++I) { 11542 NamedDecl *D = *I; 11543 11544 // Some of these decls (like enums) may have been pinned to the 11545 // translation unit for lack of a real context earlier. If so, remove 11546 // from the translation unit and reattach to the current context. 11547 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 11548 // Is the decl actually in the context? 11549 if (Context.getTranslationUnitDecl()->containsDecl(D)) 11550 Context.getTranslationUnitDecl()->removeDecl(D); 11551 // Either way, reassign the lexical decl context to our FunctionDecl. 11552 D->setLexicalDeclContext(CurContext); 11553 } 11554 11555 // If the decl has a non-null name, make accessible in the current scope. 11556 if (!D->getName().empty()) 11557 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 11558 11559 // Similarly, dive into enums and fish their constants out, making them 11560 // accessible in this scope. 11561 if (auto *ED = dyn_cast<EnumDecl>(D)) { 11562 for (auto *EI : ED->enumerators()) 11563 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11564 } 11565 } 11566 } 11567 11568 // Ensure that the function's exception specification is instantiated. 11569 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11570 ResolveExceptionSpec(D->getLocation(), FPT); 11571 11572 // dllimport cannot be applied to non-inline function definitions. 11573 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11574 !FD->isTemplateInstantiation()) { 11575 assert(!FD->hasAttr<DLLExportAttr>()); 11576 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11577 FD->setInvalidDecl(); 11578 return D; 11579 } 11580 // We want to attach documentation to original Decl (which might be 11581 // a function template). 11582 ActOnDocumentableDecl(D); 11583 if (getCurLexicalContext()->isObjCContainer() && 11584 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11585 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11586 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11587 11588 return D; 11589 } 11590 11591 /// \brief Given the set of return statements within a function body, 11592 /// compute the variables that are subject to the named return value 11593 /// optimization. 11594 /// 11595 /// Each of the variables that is subject to the named return value 11596 /// optimization will be marked as NRVO variables in the AST, and any 11597 /// return statement that has a marked NRVO variable as its NRVO candidate can 11598 /// use the named return value optimization. 11599 /// 11600 /// This function applies a very simplistic algorithm for NRVO: if every return 11601 /// statement in the scope of a variable has the same NRVO candidate, that 11602 /// candidate is an NRVO variable. 11603 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11604 ReturnStmt **Returns = Scope->Returns.data(); 11605 11606 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11607 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11608 if (!NRVOCandidate->isNRVOVariable()) 11609 Returns[I]->setNRVOCandidate(nullptr); 11610 } 11611 } 11612 } 11613 11614 bool Sema::canDelayFunctionBody(const Declarator &D) { 11615 // We can't delay parsing the body of a constexpr function template (yet). 11616 if (D.getDeclSpec().isConstexprSpecified()) 11617 return false; 11618 11619 // We can't delay parsing the body of a function template with a deduced 11620 // return type (yet). 11621 if (D.getDeclSpec().containsPlaceholderType()) { 11622 // If the placeholder introduces a non-deduced trailing return type, 11623 // we can still delay parsing it. 11624 if (D.getNumTypeObjects()) { 11625 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11626 if (Outer.Kind == DeclaratorChunk::Function && 11627 Outer.Fun.hasTrailingReturnType()) { 11628 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11629 return Ty.isNull() || !Ty->isUndeducedType(); 11630 } 11631 } 11632 return false; 11633 } 11634 11635 return true; 11636 } 11637 11638 bool Sema::canSkipFunctionBody(Decl *D) { 11639 // We cannot skip the body of a function (or function template) which is 11640 // constexpr, since we may need to evaluate its body in order to parse the 11641 // rest of the file. 11642 // We cannot skip the body of a function with an undeduced return type, 11643 // because any callers of that function need to know the type. 11644 if (const FunctionDecl *FD = D->getAsFunction()) 11645 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11646 return false; 11647 return Consumer.shouldSkipFunctionBody(D); 11648 } 11649 11650 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11651 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11652 FD->setHasSkippedBody(); 11653 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11654 MD->setHasSkippedBody(); 11655 return Decl; 11656 } 11657 11658 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11659 return ActOnFinishFunctionBody(D, BodyArg, false); 11660 } 11661 11662 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11663 bool IsInstantiation) { 11664 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11665 11666 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11667 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11668 11669 if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty()) 11670 CheckCompletedCoroutineBody(FD, Body); 11671 11672 if (FD) { 11673 FD->setBody(Body); 11674 11675 if (getLangOpts().CPlusPlus14) { 11676 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 11677 FD->getReturnType()->isUndeducedType()) { 11678 // If the function has a deduced result type but contains no 'return' 11679 // statements, the result type as written must be exactly 'auto', and 11680 // the deduced result type is 'void'. 11681 if (!FD->getReturnType()->getAs<AutoType>()) { 11682 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 11683 << FD->getReturnType(); 11684 FD->setInvalidDecl(); 11685 } else { 11686 // Substitute 'void' for the 'auto' in the type. 11687 TypeLoc ResultType = getReturnTypeLoc(FD); 11688 Context.adjustDeducedFunctionResultType( 11689 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 11690 } 11691 } 11692 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11693 // In C++11, we don't use 'auto' deduction rules for lambda call 11694 // operators because we don't support return type deduction. 11695 auto *LSI = getCurLambda(); 11696 if (LSI->HasImplicitReturnType) { 11697 deduceClosureReturnType(*LSI); 11698 11699 // C++11 [expr.prim.lambda]p4: 11700 // [...] if there are no return statements in the compound-statement 11701 // [the deduced type is] the type void 11702 QualType RetType = 11703 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11704 11705 // Update the return type to the deduced type. 11706 const FunctionProtoType *Proto = 11707 FD->getType()->getAs<FunctionProtoType>(); 11708 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11709 Proto->getExtProtoInfo())); 11710 } 11711 } 11712 11713 // The only way to be included in UndefinedButUsed is if there is an 11714 // ODR use before the definition. Avoid the expensive map lookup if this 11715 // is the first declaration. 11716 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11717 if (!FD->isExternallyVisible()) 11718 UndefinedButUsed.erase(FD); 11719 else if (FD->isInlined() && 11720 !LangOpts.GNUInline && 11721 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11722 UndefinedButUsed.erase(FD); 11723 } 11724 11725 // If the function implicitly returns zero (like 'main') or is naked, 11726 // don't complain about missing return statements. 11727 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11728 WP.disableCheckFallThrough(); 11729 11730 // MSVC permits the use of pure specifier (=0) on function definition, 11731 // defined at class scope, warn about this non-standard construct. 11732 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11733 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11734 11735 if (!FD->isInvalidDecl()) { 11736 // Don't diagnose unused parameters of defaulted or deleted functions. 11737 if (!FD->isDeleted() && !FD->isDefaulted()) 11738 DiagnoseUnusedParameters(FD->parameters()); 11739 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 11740 FD->getReturnType(), FD); 11741 11742 // If this is a structor, we need a vtable. 11743 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11744 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11745 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 11746 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 11747 11748 // Try to apply the named return value optimization. We have to check 11749 // if we can do this here because lambdas keep return statements around 11750 // to deduce an implicit return type. 11751 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 11752 !FD->isDependentContext()) 11753 computeNRVO(Body, getCurFunction()); 11754 } 11755 11756 // GNU warning -Wmissing-prototypes: 11757 // Warn if a global function is defined without a previous 11758 // prototype declaration. This warning is issued even if the 11759 // definition itself provides a prototype. The aim is to detect 11760 // global functions that fail to be declared in header files. 11761 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 11762 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 11763 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 11764 11765 if (PossibleZeroParamPrototype) { 11766 // We found a declaration that is not a prototype, 11767 // but that could be a zero-parameter prototype 11768 if (TypeSourceInfo *TI = 11769 PossibleZeroParamPrototype->getTypeSourceInfo()) { 11770 TypeLoc TL = TI->getTypeLoc(); 11771 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 11772 Diag(PossibleZeroParamPrototype->getLocation(), 11773 diag::note_declaration_not_a_prototype) 11774 << PossibleZeroParamPrototype 11775 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 11776 } 11777 } 11778 } 11779 11780 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11781 const CXXMethodDecl *KeyFunction; 11782 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 11783 MD->isVirtual() && 11784 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 11785 MD == KeyFunction->getCanonicalDecl()) { 11786 // Update the key-function state if necessary for this ABI. 11787 if (FD->isInlined() && 11788 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11789 Context.setNonKeyFunction(MD); 11790 11791 // If the newly-chosen key function is already defined, then we 11792 // need to mark the vtable as used retroactively. 11793 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 11794 const FunctionDecl *Definition; 11795 if (KeyFunction && KeyFunction->isDefined(Definition)) 11796 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 11797 } else { 11798 // We just defined they key function; mark the vtable as used. 11799 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 11800 } 11801 } 11802 } 11803 11804 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 11805 "Function parsing confused"); 11806 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 11807 assert(MD == getCurMethodDecl() && "Method parsing confused"); 11808 MD->setBody(Body); 11809 if (!MD->isInvalidDecl()) { 11810 DiagnoseUnusedParameters(MD->parameters()); 11811 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 11812 MD->getReturnType(), MD); 11813 11814 if (Body) 11815 computeNRVO(Body, getCurFunction()); 11816 } 11817 if (getCurFunction()->ObjCShouldCallSuper) { 11818 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 11819 << MD->getSelector().getAsString(); 11820 getCurFunction()->ObjCShouldCallSuper = false; 11821 } 11822 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 11823 const ObjCMethodDecl *InitMethod = nullptr; 11824 bool isDesignated = 11825 MD->isDesignatedInitializerForTheInterface(&InitMethod); 11826 assert(isDesignated && InitMethod); 11827 (void)isDesignated; 11828 11829 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 11830 auto IFace = MD->getClassInterface(); 11831 if (!IFace) 11832 return false; 11833 auto SuperD = IFace->getSuperClass(); 11834 if (!SuperD) 11835 return false; 11836 return SuperD->getIdentifier() == 11837 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 11838 }; 11839 // Don't issue this warning for unavailable inits or direct subclasses 11840 // of NSObject. 11841 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 11842 Diag(MD->getLocation(), 11843 diag::warn_objc_designated_init_missing_super_call); 11844 Diag(InitMethod->getLocation(), 11845 diag::note_objc_designated_init_marked_here); 11846 } 11847 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 11848 } 11849 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 11850 // Don't issue this warning for unavaialable inits. 11851 if (!MD->isUnavailable()) 11852 Diag(MD->getLocation(), 11853 diag::warn_objc_secondary_init_missing_init_call); 11854 getCurFunction()->ObjCWarnForNoInitDelegation = false; 11855 } 11856 } else { 11857 return nullptr; 11858 } 11859 11860 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 11861 DiagnoseUnguardedAvailabilityViolations(dcl); 11862 11863 assert(!getCurFunction()->ObjCShouldCallSuper && 11864 "This should only be set for ObjC methods, which should have been " 11865 "handled in the block above."); 11866 11867 // Verify and clean out per-function state. 11868 if (Body && (!FD || !FD->isDefaulted())) { 11869 // C++ constructors that have function-try-blocks can't have return 11870 // statements in the handlers of that block. (C++ [except.handle]p14) 11871 // Verify this. 11872 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 11873 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 11874 11875 // Verify that gotos and switch cases don't jump into scopes illegally. 11876 if (getCurFunction()->NeedsScopeChecking() && 11877 !PP.isCodeCompletionEnabled()) 11878 DiagnoseInvalidJumps(Body); 11879 11880 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 11881 if (!Destructor->getParent()->isDependentType()) 11882 CheckDestructor(Destructor); 11883 11884 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11885 Destructor->getParent()); 11886 } 11887 11888 // If any errors have occurred, clear out any temporaries that may have 11889 // been leftover. This ensures that these temporaries won't be picked up for 11890 // deletion in some later function. 11891 if (getDiagnostics().hasErrorOccurred() || 11892 getDiagnostics().getSuppressAllDiagnostics()) { 11893 DiscardCleanupsInEvaluationContext(); 11894 } 11895 if (!getDiagnostics().hasUncompilableErrorOccurred() && 11896 !isa<FunctionTemplateDecl>(dcl)) { 11897 // Since the body is valid, issue any analysis-based warnings that are 11898 // enabled. 11899 ActivePolicy = &WP; 11900 } 11901 11902 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 11903 (!CheckConstexprFunctionDecl(FD) || 11904 !CheckConstexprFunctionBody(FD, Body))) 11905 FD->setInvalidDecl(); 11906 11907 if (FD && FD->hasAttr<NakedAttr>()) { 11908 for (const Stmt *S : Body->children()) { 11909 // Allow local register variables without initializer as they don't 11910 // require prologue. 11911 bool RegisterVariables = false; 11912 if (auto *DS = dyn_cast<DeclStmt>(S)) { 11913 for (const auto *Decl : DS->decls()) { 11914 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 11915 RegisterVariables = 11916 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 11917 if (!RegisterVariables) 11918 break; 11919 } 11920 } 11921 } 11922 if (RegisterVariables) 11923 continue; 11924 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 11925 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 11926 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 11927 FD->setInvalidDecl(); 11928 break; 11929 } 11930 } 11931 } 11932 11933 assert(ExprCleanupObjects.size() == 11934 ExprEvalContexts.back().NumCleanupObjects && 11935 "Leftover temporaries in function"); 11936 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 11937 assert(MaybeODRUseExprs.empty() && 11938 "Leftover expressions for odr-use checking"); 11939 } 11940 11941 if (!IsInstantiation) 11942 PopDeclContext(); 11943 11944 PopFunctionScopeInfo(ActivePolicy, dcl); 11945 // If any errors have occurred, clear out any temporaries that may have 11946 // been leftover. This ensures that these temporaries won't be picked up for 11947 // deletion in some later function. 11948 if (getDiagnostics().hasErrorOccurred()) { 11949 DiscardCleanupsInEvaluationContext(); 11950 } 11951 11952 return dcl; 11953 } 11954 11955 /// When we finish delayed parsing of an attribute, we must attach it to the 11956 /// relevant Decl. 11957 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 11958 ParsedAttributes &Attrs) { 11959 // Always attach attributes to the underlying decl. 11960 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 11961 D = TD->getTemplatedDecl(); 11962 ProcessDeclAttributeList(S, D, Attrs.getList()); 11963 11964 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 11965 if (Method->isStatic()) 11966 checkThisInStaticMemberFunctionAttributes(Method); 11967 } 11968 11969 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 11970 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 11971 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 11972 IdentifierInfo &II, Scope *S) { 11973 // Before we produce a declaration for an implicitly defined 11974 // function, see whether there was a locally-scoped declaration of 11975 // this name as a function or variable. If so, use that 11976 // (non-visible) declaration, and complain about it. 11977 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 11978 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 11979 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 11980 return ExternCPrev; 11981 } 11982 11983 // Extension in C99. Legal in C90, but warn about it. 11984 unsigned diag_id; 11985 if (II.getName().startswith("__builtin_")) 11986 diag_id = diag::warn_builtin_unknown; 11987 else if (getLangOpts().C99) 11988 diag_id = diag::ext_implicit_function_decl; 11989 else 11990 diag_id = diag::warn_implicit_function_decl; 11991 Diag(Loc, diag_id) << &II; 11992 11993 // Because typo correction is expensive, only do it if the implicit 11994 // function declaration is going to be treated as an error. 11995 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 11996 TypoCorrection Corrected; 11997 if (S && 11998 (Corrected = CorrectTypo( 11999 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12000 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12001 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12002 /*ErrorRecovery*/false); 12003 } 12004 12005 // Set a Declarator for the implicit definition: int foo(); 12006 const char *Dummy; 12007 AttributeFactory attrFactory; 12008 DeclSpec DS(attrFactory); 12009 unsigned DiagID; 12010 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12011 Context.getPrintingPolicy()); 12012 (void)Error; // Silence warning. 12013 assert(!Error && "Error setting up implicit decl!"); 12014 SourceLocation NoLoc; 12015 Declarator D(DS, Declarator::BlockContext); 12016 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12017 /*IsAmbiguous=*/false, 12018 /*LParenLoc=*/NoLoc, 12019 /*Params=*/nullptr, 12020 /*NumParams=*/0, 12021 /*EllipsisLoc=*/NoLoc, 12022 /*RParenLoc=*/NoLoc, 12023 /*TypeQuals=*/0, 12024 /*RefQualifierIsLvalueRef=*/true, 12025 /*RefQualifierLoc=*/NoLoc, 12026 /*ConstQualifierLoc=*/NoLoc, 12027 /*VolatileQualifierLoc=*/NoLoc, 12028 /*RestrictQualifierLoc=*/NoLoc, 12029 /*MutableLoc=*/NoLoc, 12030 EST_None, 12031 /*ESpecRange=*/SourceRange(), 12032 /*Exceptions=*/nullptr, 12033 /*ExceptionRanges=*/nullptr, 12034 /*NumExceptions=*/0, 12035 /*NoexceptExpr=*/nullptr, 12036 /*ExceptionSpecTokens=*/nullptr, 12037 Loc, Loc, D), 12038 DS.getAttributes(), 12039 SourceLocation()); 12040 D.SetIdentifier(&II, Loc); 12041 12042 // Insert this function into translation-unit scope. 12043 12044 DeclContext *PrevDC = CurContext; 12045 CurContext = Context.getTranslationUnitDecl(); 12046 12047 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12048 FD->setImplicit(); 12049 12050 CurContext = PrevDC; 12051 12052 AddKnownFunctionAttributes(FD); 12053 12054 return FD; 12055 } 12056 12057 /// \brief Adds any function attributes that we know a priori based on 12058 /// the declaration of this function. 12059 /// 12060 /// These attributes can apply both to implicitly-declared builtins 12061 /// (like __builtin___printf_chk) or to library-declared functions 12062 /// like NSLog or printf. 12063 /// 12064 /// We need to check for duplicate attributes both here and where user-written 12065 /// attributes are applied to declarations. 12066 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12067 if (FD->isInvalidDecl()) 12068 return; 12069 12070 // If this is a built-in function, map its builtin attributes to 12071 // actual attributes. 12072 if (unsigned BuiltinID = FD->getBuiltinID()) { 12073 // Handle printf-formatting attributes. 12074 unsigned FormatIdx; 12075 bool HasVAListArg; 12076 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12077 if (!FD->hasAttr<FormatAttr>()) { 12078 const char *fmt = "printf"; 12079 unsigned int NumParams = FD->getNumParams(); 12080 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12081 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12082 fmt = "NSString"; 12083 FD->addAttr(FormatAttr::CreateImplicit(Context, 12084 &Context.Idents.get(fmt), 12085 FormatIdx+1, 12086 HasVAListArg ? 0 : FormatIdx+2, 12087 FD->getLocation())); 12088 } 12089 } 12090 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12091 HasVAListArg)) { 12092 if (!FD->hasAttr<FormatAttr>()) 12093 FD->addAttr(FormatAttr::CreateImplicit(Context, 12094 &Context.Idents.get("scanf"), 12095 FormatIdx+1, 12096 HasVAListArg ? 0 : FormatIdx+2, 12097 FD->getLocation())); 12098 } 12099 12100 // Mark const if we don't care about errno and that is the only 12101 // thing preventing the function from being const. This allows 12102 // IRgen to use LLVM intrinsics for such functions. 12103 if (!getLangOpts().MathErrno && 12104 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12105 if (!FD->hasAttr<ConstAttr>()) 12106 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12107 } 12108 12109 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12110 !FD->hasAttr<ReturnsTwiceAttr>()) 12111 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12112 FD->getLocation())); 12113 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12114 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12115 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12116 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12117 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12118 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12119 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12120 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12121 // Add the appropriate attribute, depending on the CUDA compilation mode 12122 // and which target the builtin belongs to. For example, during host 12123 // compilation, aux builtins are __device__, while the rest are __host__. 12124 if (getLangOpts().CUDAIsDevice != 12125 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12126 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12127 else 12128 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12129 } 12130 } 12131 12132 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12133 // throw, add an implicit nothrow attribute to any extern "C" function we come 12134 // across. 12135 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12136 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12137 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12138 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12139 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12140 } 12141 12142 IdentifierInfo *Name = FD->getIdentifier(); 12143 if (!Name) 12144 return; 12145 if ((!getLangOpts().CPlusPlus && 12146 FD->getDeclContext()->isTranslationUnit()) || 12147 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12148 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12149 LinkageSpecDecl::lang_c)) { 12150 // Okay: this could be a libc/libm/Objective-C function we know 12151 // about. 12152 } else 12153 return; 12154 12155 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12156 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12157 // target-specific builtins, perhaps? 12158 if (!FD->hasAttr<FormatAttr>()) 12159 FD->addAttr(FormatAttr::CreateImplicit(Context, 12160 &Context.Idents.get("printf"), 2, 12161 Name->isStr("vasprintf") ? 0 : 3, 12162 FD->getLocation())); 12163 } 12164 12165 if (Name->isStr("__CFStringMakeConstantString")) { 12166 // We already have a __builtin___CFStringMakeConstantString, 12167 // but builds that use -fno-constant-cfstrings don't go through that. 12168 if (!FD->hasAttr<FormatArgAttr>()) 12169 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12170 FD->getLocation())); 12171 } 12172 } 12173 12174 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12175 TypeSourceInfo *TInfo) { 12176 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12177 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12178 12179 if (!TInfo) { 12180 assert(D.isInvalidType() && "no declarator info for valid type"); 12181 TInfo = Context.getTrivialTypeSourceInfo(T); 12182 } 12183 12184 // Scope manipulation handled by caller. 12185 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12186 D.getLocStart(), 12187 D.getIdentifierLoc(), 12188 D.getIdentifier(), 12189 TInfo); 12190 12191 // Bail out immediately if we have an invalid declaration. 12192 if (D.isInvalidType()) { 12193 NewTD->setInvalidDecl(); 12194 return NewTD; 12195 } 12196 12197 if (D.getDeclSpec().isModulePrivateSpecified()) { 12198 if (CurContext->isFunctionOrMethod()) 12199 Diag(NewTD->getLocation(), diag::err_module_private_local) 12200 << 2 << NewTD->getDeclName() 12201 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12202 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12203 else 12204 NewTD->setModulePrivate(); 12205 } 12206 12207 // C++ [dcl.typedef]p8: 12208 // If the typedef declaration defines an unnamed class (or 12209 // enum), the first typedef-name declared by the declaration 12210 // to be that class type (or enum type) is used to denote the 12211 // class type (or enum type) for linkage purposes only. 12212 // We need to check whether the type was declared in the declaration. 12213 switch (D.getDeclSpec().getTypeSpecType()) { 12214 case TST_enum: 12215 case TST_struct: 12216 case TST_interface: 12217 case TST_union: 12218 case TST_class: { 12219 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12220 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12221 break; 12222 } 12223 12224 default: 12225 break; 12226 } 12227 12228 return NewTD; 12229 } 12230 12231 /// \brief Check that this is a valid underlying type for an enum declaration. 12232 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12233 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12234 QualType T = TI->getType(); 12235 12236 if (T->isDependentType()) 12237 return false; 12238 12239 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12240 if (BT->isInteger()) 12241 return false; 12242 12243 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12244 return true; 12245 } 12246 12247 /// Check whether this is a valid redeclaration of a previous enumeration. 12248 /// \return true if the redeclaration was invalid. 12249 bool Sema::CheckEnumRedeclaration( 12250 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12251 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12252 bool IsFixed = !EnumUnderlyingTy.isNull(); 12253 12254 if (IsScoped != Prev->isScoped()) { 12255 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12256 << Prev->isScoped(); 12257 Diag(Prev->getLocation(), diag::note_previous_declaration); 12258 return true; 12259 } 12260 12261 if (IsFixed && Prev->isFixed()) { 12262 if (!EnumUnderlyingTy->isDependentType() && 12263 !Prev->getIntegerType()->isDependentType() && 12264 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12265 Prev->getIntegerType())) { 12266 // TODO: Highlight the underlying type of the redeclaration. 12267 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12268 << EnumUnderlyingTy << Prev->getIntegerType(); 12269 Diag(Prev->getLocation(), diag::note_previous_declaration) 12270 << Prev->getIntegerTypeRange(); 12271 return true; 12272 } 12273 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12274 ; 12275 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12276 ; 12277 } else if (IsFixed != Prev->isFixed()) { 12278 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12279 << Prev->isFixed(); 12280 Diag(Prev->getLocation(), diag::note_previous_declaration); 12281 return true; 12282 } 12283 12284 return false; 12285 } 12286 12287 /// \brief Get diagnostic %select index for tag kind for 12288 /// redeclaration diagnostic message. 12289 /// WARNING: Indexes apply to particular diagnostics only! 12290 /// 12291 /// \returns diagnostic %select index. 12292 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12293 switch (Tag) { 12294 case TTK_Struct: return 0; 12295 case TTK_Interface: return 1; 12296 case TTK_Class: return 2; 12297 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12298 } 12299 } 12300 12301 /// \brief Determine if tag kind is a class-key compatible with 12302 /// class for redeclaration (class, struct, or __interface). 12303 /// 12304 /// \returns true iff the tag kind is compatible. 12305 static bool isClassCompatTagKind(TagTypeKind Tag) 12306 { 12307 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12308 } 12309 12310 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl) { 12311 if (isa<TypedefDecl>(PrevDecl)) 12312 return NTK_Typedef; 12313 else if (isa<TypeAliasDecl>(PrevDecl)) 12314 return NTK_TypeAlias; 12315 else if (isa<ClassTemplateDecl>(PrevDecl)) 12316 return NTK_Template; 12317 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12318 return NTK_TypeAliasTemplate; 12319 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12320 return NTK_TemplateTemplateArgument; 12321 return NTK_Unknown; 12322 } 12323 12324 /// \brief Determine whether a tag with a given kind is acceptable 12325 /// as a redeclaration of the given tag declaration. 12326 /// 12327 /// \returns true if the new tag kind is acceptable, false otherwise. 12328 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12329 TagTypeKind NewTag, bool isDefinition, 12330 SourceLocation NewTagLoc, 12331 const IdentifierInfo *Name) { 12332 // C++ [dcl.type.elab]p3: 12333 // The class-key or enum keyword present in the 12334 // elaborated-type-specifier shall agree in kind with the 12335 // declaration to which the name in the elaborated-type-specifier 12336 // refers. This rule also applies to the form of 12337 // elaborated-type-specifier that declares a class-name or 12338 // friend class since it can be construed as referring to the 12339 // definition of the class. Thus, in any 12340 // elaborated-type-specifier, the enum keyword shall be used to 12341 // refer to an enumeration (7.2), the union class-key shall be 12342 // used to refer to a union (clause 9), and either the class or 12343 // struct class-key shall be used to refer to a class (clause 9) 12344 // declared using the class or struct class-key. 12345 TagTypeKind OldTag = Previous->getTagKind(); 12346 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12347 if (OldTag == NewTag) 12348 return true; 12349 12350 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12351 // Warn about the struct/class tag mismatch. 12352 bool isTemplate = false; 12353 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12354 isTemplate = Record->getDescribedClassTemplate(); 12355 12356 if (!ActiveTemplateInstantiations.empty()) { 12357 // In a template instantiation, do not offer fix-its for tag mismatches 12358 // since they usually mess up the template instead of fixing the problem. 12359 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12360 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12361 << getRedeclDiagFromTagKind(OldTag); 12362 return true; 12363 } 12364 12365 if (isDefinition) { 12366 // On definitions, check previous tags and issue a fix-it for each 12367 // one that doesn't match the current tag. 12368 if (Previous->getDefinition()) { 12369 // Don't suggest fix-its for redefinitions. 12370 return true; 12371 } 12372 12373 bool previousMismatch = false; 12374 for (auto I : Previous->redecls()) { 12375 if (I->getTagKind() != NewTag) { 12376 if (!previousMismatch) { 12377 previousMismatch = true; 12378 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12379 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12380 << getRedeclDiagFromTagKind(I->getTagKind()); 12381 } 12382 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12383 << getRedeclDiagFromTagKind(NewTag) 12384 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12385 TypeWithKeyword::getTagTypeKindName(NewTag)); 12386 } 12387 } 12388 return true; 12389 } 12390 12391 // Check for a previous definition. If current tag and definition 12392 // are same type, do nothing. If no definition, but disagree with 12393 // with previous tag type, give a warning, but no fix-it. 12394 const TagDecl *Redecl = Previous->getDefinition() ? 12395 Previous->getDefinition() : Previous; 12396 if (Redecl->getTagKind() == NewTag) { 12397 return true; 12398 } 12399 12400 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12401 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12402 << getRedeclDiagFromTagKind(OldTag); 12403 Diag(Redecl->getLocation(), diag::note_previous_use); 12404 12405 // If there is a previous definition, suggest a fix-it. 12406 if (Previous->getDefinition()) { 12407 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12408 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12409 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12410 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12411 } 12412 12413 return true; 12414 } 12415 return false; 12416 } 12417 12418 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12419 /// from an outer enclosing namespace or file scope inside a friend declaration. 12420 /// This should provide the commented out code in the following snippet: 12421 /// namespace N { 12422 /// struct X; 12423 /// namespace M { 12424 /// struct Y { friend struct /*N::*/ X; }; 12425 /// } 12426 /// } 12427 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12428 SourceLocation NameLoc) { 12429 // While the decl is in a namespace, do repeated lookup of that name and see 12430 // if we get the same namespace back. If we do not, continue until 12431 // translation unit scope, at which point we have a fully qualified NNS. 12432 SmallVector<IdentifierInfo *, 4> Namespaces; 12433 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12434 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12435 // This tag should be declared in a namespace, which can only be enclosed by 12436 // other namespaces. Bail if there's an anonymous namespace in the chain. 12437 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12438 if (!Namespace || Namespace->isAnonymousNamespace()) 12439 return FixItHint(); 12440 IdentifierInfo *II = Namespace->getIdentifier(); 12441 Namespaces.push_back(II); 12442 NamedDecl *Lookup = SemaRef.LookupSingleName( 12443 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12444 if (Lookup == Namespace) 12445 break; 12446 } 12447 12448 // Once we have all the namespaces, reverse them to go outermost first, and 12449 // build an NNS. 12450 SmallString<64> Insertion; 12451 llvm::raw_svector_ostream OS(Insertion); 12452 if (DC->isTranslationUnit()) 12453 OS << "::"; 12454 std::reverse(Namespaces.begin(), Namespaces.end()); 12455 for (auto *II : Namespaces) 12456 OS << II->getName() << "::"; 12457 return FixItHint::CreateInsertion(NameLoc, Insertion); 12458 } 12459 12460 /// \brief Determine whether a tag originally declared in context \p OldDC can 12461 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12462 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12463 /// using-declaration). 12464 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12465 DeclContext *NewDC) { 12466 OldDC = OldDC->getRedeclContext(); 12467 NewDC = NewDC->getRedeclContext(); 12468 12469 if (OldDC->Equals(NewDC)) 12470 return true; 12471 12472 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12473 // encloses the other). 12474 if (S.getLangOpts().MSVCCompat && 12475 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 12476 return true; 12477 12478 return false; 12479 } 12480 12481 /// Find the DeclContext in which a tag is implicitly declared if we see an 12482 /// elaborated type specifier in the specified context, and lookup finds 12483 /// nothing. 12484 static DeclContext *getTagInjectionContext(DeclContext *DC) { 12485 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 12486 DC = DC->getParent(); 12487 return DC; 12488 } 12489 12490 /// Find the Scope in which a tag is implicitly declared if we see an 12491 /// elaborated type specifier in the specified context, and lookup finds 12492 /// nothing. 12493 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 12494 while (S->isClassScope() || 12495 (LangOpts.CPlusPlus && 12496 S->isFunctionPrototypeScope()) || 12497 ((S->getFlags() & Scope::DeclScope) == 0) || 12498 (S->getEntity() && S->getEntity()->isTransparentContext())) 12499 S = S->getParent(); 12500 return S; 12501 } 12502 12503 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 12504 /// former case, Name will be non-null. In the later case, Name will be null. 12505 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 12506 /// reference/declaration/definition of a tag. 12507 /// 12508 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 12509 /// trailing-type-specifier) other than one in an alias-declaration. 12510 /// 12511 /// \param SkipBody If non-null, will be set to indicate if the caller should 12512 /// skip the definition of this tag and treat it as if it were a declaration. 12513 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12514 SourceLocation KWLoc, CXXScopeSpec &SS, 12515 IdentifierInfo *Name, SourceLocation NameLoc, 12516 AttributeList *Attr, AccessSpecifier AS, 12517 SourceLocation ModulePrivateLoc, 12518 MultiTemplateParamsArg TemplateParameterLists, 12519 bool &OwnedDecl, bool &IsDependent, 12520 SourceLocation ScopedEnumKWLoc, 12521 bool ScopedEnumUsesClassTag, 12522 TypeResult UnderlyingType, 12523 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 12524 // If this is not a definition, it must have a name. 12525 IdentifierInfo *OrigName = Name; 12526 assert((Name != nullptr || TUK == TUK_Definition) && 12527 "Nameless record must be a definition!"); 12528 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 12529 12530 OwnedDecl = false; 12531 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12532 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 12533 12534 // FIXME: Check explicit specializations more carefully. 12535 bool isExplicitSpecialization = false; 12536 bool Invalid = false; 12537 12538 // We only need to do this matching if we have template parameters 12539 // or a scope specifier, which also conveniently avoids this work 12540 // for non-C++ cases. 12541 if (TemplateParameterLists.size() > 0 || 12542 (SS.isNotEmpty() && TUK != TUK_Reference)) { 12543 if (TemplateParameterList *TemplateParams = 12544 MatchTemplateParametersToScopeSpecifier( 12545 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 12546 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 12547 if (Kind == TTK_Enum) { 12548 Diag(KWLoc, diag::err_enum_template); 12549 return nullptr; 12550 } 12551 12552 if (TemplateParams->size() > 0) { 12553 // This is a declaration or definition of a class template (which may 12554 // be a member of another template). 12555 12556 if (Invalid) 12557 return nullptr; 12558 12559 OwnedDecl = false; 12560 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 12561 SS, Name, NameLoc, Attr, 12562 TemplateParams, AS, 12563 ModulePrivateLoc, 12564 /*FriendLoc*/SourceLocation(), 12565 TemplateParameterLists.size()-1, 12566 TemplateParameterLists.data(), 12567 SkipBody); 12568 return Result.get(); 12569 } else { 12570 // The "template<>" header is extraneous. 12571 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12572 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12573 isExplicitSpecialization = true; 12574 } 12575 } 12576 } 12577 12578 // Figure out the underlying type if this a enum declaration. We need to do 12579 // this early, because it's needed to detect if this is an incompatible 12580 // redeclaration. 12581 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12582 bool EnumUnderlyingIsImplicit = false; 12583 12584 if (Kind == TTK_Enum) { 12585 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12586 // No underlying type explicitly specified, or we failed to parse the 12587 // type, default to int. 12588 EnumUnderlying = Context.IntTy.getTypePtr(); 12589 else if (UnderlyingType.get()) { 12590 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12591 // integral type; any cv-qualification is ignored. 12592 TypeSourceInfo *TI = nullptr; 12593 GetTypeFromParser(UnderlyingType.get(), &TI); 12594 EnumUnderlying = TI; 12595 12596 if (CheckEnumUnderlyingType(TI)) 12597 // Recover by falling back to int. 12598 EnumUnderlying = Context.IntTy.getTypePtr(); 12599 12600 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12601 UPPC_FixedUnderlyingType)) 12602 EnumUnderlying = Context.IntTy.getTypePtr(); 12603 12604 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12605 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12606 // Microsoft enums are always of int type. 12607 EnumUnderlying = Context.IntTy.getTypePtr(); 12608 EnumUnderlyingIsImplicit = true; 12609 } 12610 } 12611 } 12612 12613 DeclContext *SearchDC = CurContext; 12614 DeclContext *DC = CurContext; 12615 bool isStdBadAlloc = false; 12616 bool isStdAlignValT = false; 12617 12618 RedeclarationKind Redecl = ForRedeclaration; 12619 if (TUK == TUK_Friend || TUK == TUK_Reference) 12620 Redecl = NotForRedeclaration; 12621 12622 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12623 if (Name && SS.isNotEmpty()) { 12624 // We have a nested-name tag ('struct foo::bar'). 12625 12626 // Check for invalid 'foo::'. 12627 if (SS.isInvalid()) { 12628 Name = nullptr; 12629 goto CreateNewDecl; 12630 } 12631 12632 // If this is a friend or a reference to a class in a dependent 12633 // context, don't try to make a decl for it. 12634 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12635 DC = computeDeclContext(SS, false); 12636 if (!DC) { 12637 IsDependent = true; 12638 return nullptr; 12639 } 12640 } else { 12641 DC = computeDeclContext(SS, true); 12642 if (!DC) { 12643 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12644 << SS.getRange(); 12645 return nullptr; 12646 } 12647 } 12648 12649 if (RequireCompleteDeclContext(SS, DC)) 12650 return nullptr; 12651 12652 SearchDC = DC; 12653 // Look-up name inside 'foo::'. 12654 LookupQualifiedName(Previous, DC); 12655 12656 if (Previous.isAmbiguous()) 12657 return nullptr; 12658 12659 if (Previous.empty()) { 12660 // Name lookup did not find anything. However, if the 12661 // nested-name-specifier refers to the current instantiation, 12662 // and that current instantiation has any dependent base 12663 // classes, we might find something at instantiation time: treat 12664 // this as a dependent elaborated-type-specifier. 12665 // But this only makes any sense for reference-like lookups. 12666 if (Previous.wasNotFoundInCurrentInstantiation() && 12667 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12668 IsDependent = true; 12669 return nullptr; 12670 } 12671 12672 // A tag 'foo::bar' must already exist. 12673 Diag(NameLoc, diag::err_not_tag_in_scope) 12674 << Kind << Name << DC << SS.getRange(); 12675 Name = nullptr; 12676 Invalid = true; 12677 goto CreateNewDecl; 12678 } 12679 } else if (Name) { 12680 // C++14 [class.mem]p14: 12681 // If T is the name of a class, then each of the following shall have a 12682 // name different from T: 12683 // -- every member of class T that is itself a type 12684 if (TUK != TUK_Reference && TUK != TUK_Friend && 12685 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 12686 return nullptr; 12687 12688 // If this is a named struct, check to see if there was a previous forward 12689 // declaration or definition. 12690 // FIXME: We're looking into outer scopes here, even when we 12691 // shouldn't be. Doing so can result in ambiguities that we 12692 // shouldn't be diagnosing. 12693 LookupName(Previous, S); 12694 12695 // When declaring or defining a tag, ignore ambiguities introduced 12696 // by types using'ed into this scope. 12697 if (Previous.isAmbiguous() && 12698 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 12699 LookupResult::Filter F = Previous.makeFilter(); 12700 while (F.hasNext()) { 12701 NamedDecl *ND = F.next(); 12702 if (!ND->getDeclContext()->getRedeclContext()->Equals( 12703 SearchDC->getRedeclContext())) 12704 F.erase(); 12705 } 12706 F.done(); 12707 } 12708 12709 // C++11 [namespace.memdef]p3: 12710 // If the name in a friend declaration is neither qualified nor 12711 // a template-id and the declaration is a function or an 12712 // elaborated-type-specifier, the lookup to determine whether 12713 // the entity has been previously declared shall not consider 12714 // any scopes outside the innermost enclosing namespace. 12715 // 12716 // MSVC doesn't implement the above rule for types, so a friend tag 12717 // declaration may be a redeclaration of a type declared in an enclosing 12718 // scope. They do implement this rule for friend functions. 12719 // 12720 // Does it matter that this should be by scope instead of by 12721 // semantic context? 12722 if (!Previous.empty() && TUK == TUK_Friend) { 12723 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 12724 LookupResult::Filter F = Previous.makeFilter(); 12725 bool FriendSawTagOutsideEnclosingNamespace = false; 12726 while (F.hasNext()) { 12727 NamedDecl *ND = F.next(); 12728 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12729 if (DC->isFileContext() && 12730 !EnclosingNS->Encloses(ND->getDeclContext())) { 12731 if (getLangOpts().MSVCCompat) 12732 FriendSawTagOutsideEnclosingNamespace = true; 12733 else 12734 F.erase(); 12735 } 12736 } 12737 F.done(); 12738 12739 // Diagnose this MSVC extension in the easy case where lookup would have 12740 // unambiguously found something outside the enclosing namespace. 12741 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 12742 NamedDecl *ND = Previous.getFoundDecl(); 12743 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 12744 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 12745 } 12746 } 12747 12748 // Note: there used to be some attempt at recovery here. 12749 if (Previous.isAmbiguous()) 12750 return nullptr; 12751 12752 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 12753 // FIXME: This makes sure that we ignore the contexts associated 12754 // with C structs, unions, and enums when looking for a matching 12755 // tag declaration or definition. See the similar lookup tweak 12756 // in Sema::LookupName; is there a better way to deal with this? 12757 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 12758 SearchDC = SearchDC->getParent(); 12759 } 12760 } 12761 12762 if (Previous.isSingleResult() && 12763 Previous.getFoundDecl()->isTemplateParameter()) { 12764 // Maybe we will complain about the shadowed template parameter. 12765 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 12766 // Just pretend that we didn't see the previous declaration. 12767 Previous.clear(); 12768 } 12769 12770 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 12771 DC->Equals(getStdNamespace())) { 12772 if (Name->isStr("bad_alloc")) { 12773 // This is a declaration of or a reference to "std::bad_alloc". 12774 isStdBadAlloc = true; 12775 12776 // If std::bad_alloc has been implicitly declared (but made invisible to 12777 // name lookup), fill in this implicit declaration as the previous 12778 // declaration, so that the declarations get chained appropriately. 12779 if (Previous.empty() && StdBadAlloc) 12780 Previous.addDecl(getStdBadAlloc()); 12781 } else if (Name->isStr("align_val_t")) { 12782 isStdAlignValT = true; 12783 if (Previous.empty() && StdAlignValT) 12784 Previous.addDecl(getStdAlignValT()); 12785 } 12786 } 12787 12788 // If we didn't find a previous declaration, and this is a reference 12789 // (or friend reference), move to the correct scope. In C++, we 12790 // also need to do a redeclaration lookup there, just in case 12791 // there's a shadow friend decl. 12792 if (Name && Previous.empty() && 12793 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12794 if (Invalid) goto CreateNewDecl; 12795 assert(SS.isEmpty()); 12796 12797 if (TUK == TUK_Reference) { 12798 // C++ [basic.scope.pdecl]p5: 12799 // -- for an elaborated-type-specifier of the form 12800 // 12801 // class-key identifier 12802 // 12803 // if the elaborated-type-specifier is used in the 12804 // decl-specifier-seq or parameter-declaration-clause of a 12805 // function defined in namespace scope, the identifier is 12806 // declared as a class-name in the namespace that contains 12807 // the declaration; otherwise, except as a friend 12808 // declaration, the identifier is declared in the smallest 12809 // non-class, non-function-prototype scope that contains the 12810 // declaration. 12811 // 12812 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 12813 // C structs and unions. 12814 // 12815 // It is an error in C++ to declare (rather than define) an enum 12816 // type, including via an elaborated type specifier. We'll 12817 // diagnose that later; for now, declare the enum in the same 12818 // scope as we would have picked for any other tag type. 12819 // 12820 // GNU C also supports this behavior as part of its incomplete 12821 // enum types extension, while GNU C++ does not. 12822 // 12823 // Find the context where we'll be declaring the tag. 12824 // FIXME: We would like to maintain the current DeclContext as the 12825 // lexical context, 12826 SearchDC = getTagInjectionContext(SearchDC); 12827 12828 // Find the scope where we'll be declaring the tag. 12829 S = getTagInjectionScope(S, getLangOpts()); 12830 } else { 12831 assert(TUK == TUK_Friend); 12832 // C++ [namespace.memdef]p3: 12833 // If a friend declaration in a non-local class first declares a 12834 // class or function, the friend class or function is a member of 12835 // the innermost enclosing namespace. 12836 SearchDC = SearchDC->getEnclosingNamespaceContext(); 12837 } 12838 12839 // In C++, we need to do a redeclaration lookup to properly 12840 // diagnose some problems. 12841 // FIXME: redeclaration lookup is also used (with and without C++) to find a 12842 // hidden declaration so that we don't get ambiguity errors when using a 12843 // type declared by an elaborated-type-specifier. In C that is not correct 12844 // and we should instead merge compatible types found by lookup. 12845 if (getLangOpts().CPlusPlus) { 12846 Previous.setRedeclarationKind(ForRedeclaration); 12847 LookupQualifiedName(Previous, SearchDC); 12848 } else { 12849 Previous.setRedeclarationKind(ForRedeclaration); 12850 LookupName(Previous, S); 12851 } 12852 } 12853 12854 // If we have a known previous declaration to use, then use it. 12855 if (Previous.empty() && SkipBody && SkipBody->Previous) 12856 Previous.addDecl(SkipBody->Previous); 12857 12858 if (!Previous.empty()) { 12859 NamedDecl *PrevDecl = Previous.getFoundDecl(); 12860 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 12861 12862 // It's okay to have a tag decl in the same scope as a typedef 12863 // which hides a tag decl in the same scope. Finding this 12864 // insanity with a redeclaration lookup can only actually happen 12865 // in C++. 12866 // 12867 // This is also okay for elaborated-type-specifiers, which is 12868 // technically forbidden by the current standard but which is 12869 // okay according to the likely resolution of an open issue; 12870 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 12871 if (getLangOpts().CPlusPlus) { 12872 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12873 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 12874 TagDecl *Tag = TT->getDecl(); 12875 if (Tag->getDeclName() == Name && 12876 Tag->getDeclContext()->getRedeclContext() 12877 ->Equals(TD->getDeclContext()->getRedeclContext())) { 12878 PrevDecl = Tag; 12879 Previous.clear(); 12880 Previous.addDecl(Tag); 12881 Previous.resolveKind(); 12882 } 12883 } 12884 } 12885 } 12886 12887 // If this is a redeclaration of a using shadow declaration, it must 12888 // declare a tag in the same context. In MSVC mode, we allow a 12889 // redefinition if either context is within the other. 12890 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 12891 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 12892 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 12893 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 12894 !(OldTag && isAcceptableTagRedeclContext( 12895 *this, OldTag->getDeclContext(), SearchDC))) { 12896 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 12897 Diag(Shadow->getTargetDecl()->getLocation(), 12898 diag::note_using_decl_target); 12899 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 12900 << 0; 12901 // Recover by ignoring the old declaration. 12902 Previous.clear(); 12903 goto CreateNewDecl; 12904 } 12905 } 12906 12907 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 12908 // If this is a use of a previous tag, or if the tag is already declared 12909 // in the same scope (so that the definition/declaration completes or 12910 // rementions the tag), reuse the decl. 12911 if (TUK == TUK_Reference || TUK == TUK_Friend || 12912 isDeclInScope(DirectPrevDecl, SearchDC, S, 12913 SS.isNotEmpty() || isExplicitSpecialization)) { 12914 // Make sure that this wasn't declared as an enum and now used as a 12915 // struct or something similar. 12916 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 12917 TUK == TUK_Definition, KWLoc, 12918 Name)) { 12919 bool SafeToContinue 12920 = (PrevTagDecl->getTagKind() != TTK_Enum && 12921 Kind != TTK_Enum); 12922 if (SafeToContinue) 12923 Diag(KWLoc, diag::err_use_with_wrong_tag) 12924 << Name 12925 << FixItHint::CreateReplacement(SourceRange(KWLoc), 12926 PrevTagDecl->getKindName()); 12927 else 12928 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 12929 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 12930 12931 if (SafeToContinue) 12932 Kind = PrevTagDecl->getTagKind(); 12933 else { 12934 // Recover by making this an anonymous redefinition. 12935 Name = nullptr; 12936 Previous.clear(); 12937 Invalid = true; 12938 } 12939 } 12940 12941 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 12942 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 12943 12944 // If this is an elaborated-type-specifier for a scoped enumeration, 12945 // the 'class' keyword is not necessary and not permitted. 12946 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12947 if (ScopedEnum) 12948 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 12949 << PrevEnum->isScoped() 12950 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 12951 return PrevTagDecl; 12952 } 12953 12954 QualType EnumUnderlyingTy; 12955 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12956 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 12957 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 12958 EnumUnderlyingTy = QualType(T, 0); 12959 12960 // All conflicts with previous declarations are recovered by 12961 // returning the previous declaration, unless this is a definition, 12962 // in which case we want the caller to bail out. 12963 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 12964 ScopedEnum, EnumUnderlyingTy, 12965 EnumUnderlyingIsImplicit, PrevEnum)) 12966 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 12967 } 12968 12969 // C++11 [class.mem]p1: 12970 // A member shall not be declared twice in the member-specification, 12971 // except that a nested class or member class template can be declared 12972 // and then later defined. 12973 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 12974 S->isDeclScope(PrevDecl)) { 12975 Diag(NameLoc, diag::ext_member_redeclared); 12976 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 12977 } 12978 12979 if (!Invalid) { 12980 // If this is a use, just return the declaration we found, unless 12981 // we have attributes. 12982 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12983 if (Attr) { 12984 // FIXME: Diagnose these attributes. For now, we create a new 12985 // declaration to hold them. 12986 } else if (TUK == TUK_Reference && 12987 (PrevTagDecl->getFriendObjectKind() == 12988 Decl::FOK_Undeclared || 12989 PP.getModuleContainingLocation( 12990 PrevDecl->getLocation()) != 12991 PP.getModuleContainingLocation(KWLoc)) && 12992 SS.isEmpty()) { 12993 // This declaration is a reference to an existing entity, but 12994 // has different visibility from that entity: it either makes 12995 // a friend visible or it makes a type visible in a new module. 12996 // In either case, create a new declaration. We only do this if 12997 // the declaration would have meant the same thing if no prior 12998 // declaration were found, that is, if it was found in the same 12999 // scope where we would have injected a declaration. 13000 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13001 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13002 return PrevTagDecl; 13003 // This is in the injected scope, create a new declaration in 13004 // that scope. 13005 S = getTagInjectionScope(S, getLangOpts()); 13006 } else { 13007 return PrevTagDecl; 13008 } 13009 } 13010 13011 // Diagnose attempts to redefine a tag. 13012 if (TUK == TUK_Definition) { 13013 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13014 // If we're defining a specialization and the previous definition 13015 // is from an implicit instantiation, don't emit an error 13016 // here; we'll catch this in the general case below. 13017 bool IsExplicitSpecializationAfterInstantiation = false; 13018 if (isExplicitSpecialization) { 13019 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13020 IsExplicitSpecializationAfterInstantiation = 13021 RD->getTemplateSpecializationKind() != 13022 TSK_ExplicitSpecialization; 13023 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13024 IsExplicitSpecializationAfterInstantiation = 13025 ED->getTemplateSpecializationKind() != 13026 TSK_ExplicitSpecialization; 13027 } 13028 13029 NamedDecl *Hidden = nullptr; 13030 if (SkipBody && getLangOpts().CPlusPlus && 13031 !hasVisibleDefinition(Def, &Hidden)) { 13032 // There is a definition of this tag, but it is not visible. We 13033 // explicitly make use of C++'s one definition rule here, and 13034 // assume that this definition is identical to the hidden one 13035 // we already have. Make the existing definition visible and 13036 // use it in place of this one. 13037 SkipBody->ShouldSkip = true; 13038 makeMergedDefinitionVisible(Hidden, KWLoc); 13039 return Def; 13040 } else if (!IsExplicitSpecializationAfterInstantiation) { 13041 // A redeclaration in function prototype scope in C isn't 13042 // visible elsewhere, so merely issue a warning. 13043 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13044 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13045 else 13046 Diag(NameLoc, diag::err_redefinition) << Name; 13047 Diag(Def->getLocation(), diag::note_previous_definition); 13048 // If this is a redefinition, recover by making this 13049 // struct be anonymous, which will make any later 13050 // references get the previous definition. 13051 Name = nullptr; 13052 Previous.clear(); 13053 Invalid = true; 13054 } 13055 } else { 13056 // If the type is currently being defined, complain 13057 // about a nested redefinition. 13058 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13059 if (TD->isBeingDefined()) { 13060 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13061 Diag(PrevTagDecl->getLocation(), 13062 diag::note_previous_definition); 13063 Name = nullptr; 13064 Previous.clear(); 13065 Invalid = true; 13066 } 13067 } 13068 13069 // Okay, this is definition of a previously declared or referenced 13070 // tag. We're going to create a new Decl for it. 13071 } 13072 13073 // Okay, we're going to make a redeclaration. If this is some kind 13074 // of reference, make sure we build the redeclaration in the same DC 13075 // as the original, and ignore the current access specifier. 13076 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13077 SearchDC = PrevTagDecl->getDeclContext(); 13078 AS = AS_none; 13079 } 13080 } 13081 // If we get here we have (another) forward declaration or we 13082 // have a definition. Just create a new decl. 13083 13084 } else { 13085 // If we get here, this is a definition of a new tag type in a nested 13086 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13087 // new decl/type. We set PrevDecl to NULL so that the entities 13088 // have distinct types. 13089 Previous.clear(); 13090 } 13091 // If we get here, we're going to create a new Decl. If PrevDecl 13092 // is non-NULL, it's a definition of the tag declared by 13093 // PrevDecl. If it's NULL, we have a new definition. 13094 13095 // Otherwise, PrevDecl is not a tag, but was found with tag 13096 // lookup. This is only actually possible in C++, where a few 13097 // things like templates still live in the tag namespace. 13098 } else { 13099 // Use a better diagnostic if an elaborated-type-specifier 13100 // found the wrong kind of type on the first 13101 // (non-redeclaration) lookup. 13102 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13103 !Previous.isForRedeclaration()) { 13104 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl); 13105 Diag(NameLoc, diag::err_tag_reference_non_tag) << NTK; 13106 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13107 Invalid = true; 13108 13109 // Otherwise, only diagnose if the declaration is in scope. 13110 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13111 SS.isNotEmpty() || isExplicitSpecialization)) { 13112 // do nothing 13113 13114 // Diagnose implicit declarations introduced by elaborated types. 13115 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13116 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl); 13117 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13118 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13119 Invalid = true; 13120 13121 // Otherwise it's a declaration. Call out a particularly common 13122 // case here. 13123 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13124 unsigned Kind = 0; 13125 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13126 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13127 << Name << Kind << TND->getUnderlyingType(); 13128 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13129 Invalid = true; 13130 13131 // Otherwise, diagnose. 13132 } else { 13133 // The tag name clashes with something else in the target scope, 13134 // issue an error and recover by making this tag be anonymous. 13135 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13136 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13137 Name = nullptr; 13138 Invalid = true; 13139 } 13140 13141 // The existing declaration isn't relevant to us; we're in a 13142 // new scope, so clear out the previous declaration. 13143 Previous.clear(); 13144 } 13145 } 13146 13147 CreateNewDecl: 13148 13149 TagDecl *PrevDecl = nullptr; 13150 if (Previous.isSingleResult()) 13151 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13152 13153 // If there is an identifier, use the location of the identifier as the 13154 // location of the decl, otherwise use the location of the struct/union 13155 // keyword. 13156 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13157 13158 // Otherwise, create a new declaration. If there is a previous 13159 // declaration of the same entity, the two will be linked via 13160 // PrevDecl. 13161 TagDecl *New; 13162 13163 bool IsForwardReference = false; 13164 if (Kind == TTK_Enum) { 13165 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13166 // enum X { A, B, C } D; D should chain to X. 13167 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13168 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13169 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13170 13171 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13172 StdAlignValT = cast<EnumDecl>(New); 13173 13174 // If this is an undefined enum, warn. 13175 if (TUK != TUK_Definition && !Invalid) { 13176 TagDecl *Def; 13177 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13178 cast<EnumDecl>(New)->isFixed()) { 13179 // C++0x: 7.2p2: opaque-enum-declaration. 13180 // Conflicts are diagnosed above. Do nothing. 13181 } 13182 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13183 Diag(Loc, diag::ext_forward_ref_enum_def) 13184 << New; 13185 Diag(Def->getLocation(), diag::note_previous_definition); 13186 } else { 13187 unsigned DiagID = diag::ext_forward_ref_enum; 13188 if (getLangOpts().MSVCCompat) 13189 DiagID = diag::ext_ms_forward_ref_enum; 13190 else if (getLangOpts().CPlusPlus) 13191 DiagID = diag::err_forward_ref_enum; 13192 Diag(Loc, DiagID); 13193 13194 // If this is a forward-declared reference to an enumeration, make a 13195 // note of it; we won't actually be introducing the declaration into 13196 // the declaration context. 13197 if (TUK == TUK_Reference) 13198 IsForwardReference = true; 13199 } 13200 } 13201 13202 if (EnumUnderlying) { 13203 EnumDecl *ED = cast<EnumDecl>(New); 13204 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13205 ED->setIntegerTypeSourceInfo(TI); 13206 else 13207 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13208 ED->setPromotionType(ED->getIntegerType()); 13209 } 13210 } else { 13211 // struct/union/class 13212 13213 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13214 // struct X { int A; } D; D should chain to X. 13215 if (getLangOpts().CPlusPlus) { 13216 // FIXME: Look for a way to use RecordDecl for simple structs. 13217 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13218 cast_or_null<CXXRecordDecl>(PrevDecl)); 13219 13220 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13221 StdBadAlloc = cast<CXXRecordDecl>(New); 13222 } else 13223 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13224 cast_or_null<RecordDecl>(PrevDecl)); 13225 } 13226 13227 // C++11 [dcl.type]p3: 13228 // A type-specifier-seq shall not define a class or enumeration [...]. 13229 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13230 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13231 << Context.getTagDeclType(New); 13232 Invalid = true; 13233 } 13234 13235 // Maybe add qualifier info. 13236 if (SS.isNotEmpty()) { 13237 if (SS.isSet()) { 13238 // If this is either a declaration or a definition, check the 13239 // nested-name-specifier against the current context. We don't do this 13240 // for explicit specializations, because they have similar checking 13241 // (with more specific diagnostics) in the call to 13242 // CheckMemberSpecialization, below. 13243 if (!isExplicitSpecialization && 13244 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13245 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13246 Invalid = true; 13247 13248 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13249 if (TemplateParameterLists.size() > 0) { 13250 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13251 } 13252 } 13253 else 13254 Invalid = true; 13255 } 13256 13257 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13258 // Add alignment attributes if necessary; these attributes are checked when 13259 // the ASTContext lays out the structure. 13260 // 13261 // It is important for implementing the correct semantics that this 13262 // happen here (in act on tag decl). The #pragma pack stack is 13263 // maintained as a result of parser callbacks which can occur at 13264 // many points during the parsing of a struct declaration (because 13265 // the #pragma tokens are effectively skipped over during the 13266 // parsing of the struct). 13267 if (TUK == TUK_Definition) { 13268 AddAlignmentAttributesForRecord(RD); 13269 AddMsStructLayoutForRecord(RD); 13270 } 13271 } 13272 13273 if (ModulePrivateLoc.isValid()) { 13274 if (isExplicitSpecialization) 13275 Diag(New->getLocation(), diag::err_module_private_specialization) 13276 << 2 13277 << FixItHint::CreateRemoval(ModulePrivateLoc); 13278 // __module_private__ does not apply to local classes. However, we only 13279 // diagnose this as an error when the declaration specifiers are 13280 // freestanding. Here, we just ignore the __module_private__. 13281 else if (!SearchDC->isFunctionOrMethod()) 13282 New->setModulePrivate(); 13283 } 13284 13285 // If this is a specialization of a member class (of a class template), 13286 // check the specialization. 13287 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 13288 Invalid = true; 13289 13290 // If we're declaring or defining a tag in function prototype scope in C, 13291 // note that this type can only be used within the function and add it to 13292 // the list of decls to inject into the function definition scope. 13293 if ((Name || Kind == TTK_Enum) && 13294 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13295 if (getLangOpts().CPlusPlus) { 13296 // C++ [dcl.fct]p6: 13297 // Types shall not be defined in return or parameter types. 13298 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13299 Diag(Loc, diag::err_type_defined_in_param_type) 13300 << Name; 13301 Invalid = true; 13302 } 13303 } else if (!PrevDecl) { 13304 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13305 } 13306 DeclsInPrototypeScope.push_back(New); 13307 } 13308 13309 if (Invalid) 13310 New->setInvalidDecl(); 13311 13312 if (Attr) 13313 ProcessDeclAttributeList(S, New, Attr); 13314 13315 // Set the lexical context. If the tag has a C++ scope specifier, the 13316 // lexical context will be different from the semantic context. 13317 New->setLexicalDeclContext(CurContext); 13318 13319 // Mark this as a friend decl if applicable. 13320 // In Microsoft mode, a friend declaration also acts as a forward 13321 // declaration so we always pass true to setObjectOfFriendDecl to make 13322 // the tag name visible. 13323 if (TUK == TUK_Friend) 13324 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13325 13326 // Set the access specifier. 13327 if (!Invalid && SearchDC->isRecord()) 13328 SetMemberAccessSpecifier(New, PrevDecl, AS); 13329 13330 if (TUK == TUK_Definition) 13331 New->startDefinition(); 13332 13333 // If this has an identifier, add it to the scope stack. 13334 if (TUK == TUK_Friend) { 13335 // We might be replacing an existing declaration in the lookup tables; 13336 // if so, borrow its access specifier. 13337 if (PrevDecl) 13338 New->setAccess(PrevDecl->getAccess()); 13339 13340 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13341 DC->makeDeclVisibleInContext(New); 13342 if (Name) // can be null along some error paths 13343 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13344 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13345 } else if (Name) { 13346 S = getNonFieldDeclScope(S); 13347 PushOnScopeChains(New, S, !IsForwardReference); 13348 if (IsForwardReference) 13349 SearchDC->makeDeclVisibleInContext(New); 13350 } else { 13351 CurContext->addDecl(New); 13352 } 13353 13354 // If this is the C FILE type, notify the AST context. 13355 if (IdentifierInfo *II = New->getIdentifier()) 13356 if (!New->isInvalidDecl() && 13357 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13358 II->isStr("FILE")) 13359 Context.setFILEDecl(New); 13360 13361 if (PrevDecl) 13362 mergeDeclAttributes(New, PrevDecl); 13363 13364 // If there's a #pragma GCC visibility in scope, set the visibility of this 13365 // record. 13366 AddPushedVisibilityAttribute(New); 13367 13368 OwnedDecl = true; 13369 // In C++, don't return an invalid declaration. We can't recover well from 13370 // the cases where we make the type anonymous. 13371 if (Invalid && getLangOpts().CPlusPlus) { 13372 if (New->isBeingDefined()) 13373 if (auto RD = dyn_cast<RecordDecl>(New)) 13374 RD->completeDefinition(); 13375 return nullptr; 13376 } else { 13377 return New; 13378 } 13379 } 13380 13381 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13382 AdjustDeclIfTemplate(TagD); 13383 TagDecl *Tag = cast<TagDecl>(TagD); 13384 13385 // Enter the tag context. 13386 PushDeclContext(S, Tag); 13387 13388 ActOnDocumentableDecl(TagD); 13389 13390 // If there's a #pragma GCC visibility in scope, set the visibility of this 13391 // record. 13392 AddPushedVisibilityAttribute(Tag); 13393 } 13394 13395 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13396 assert(isa<ObjCContainerDecl>(IDecl) && 13397 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13398 DeclContext *OCD = cast<DeclContext>(IDecl); 13399 assert(getContainingDC(OCD) == CurContext && 13400 "The next DeclContext should be lexically contained in the current one."); 13401 CurContext = OCD; 13402 return IDecl; 13403 } 13404 13405 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13406 SourceLocation FinalLoc, 13407 bool IsFinalSpelledSealed, 13408 SourceLocation LBraceLoc) { 13409 AdjustDeclIfTemplate(TagD); 13410 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13411 13412 FieldCollector->StartClass(); 13413 13414 if (!Record->getIdentifier()) 13415 return; 13416 13417 if (FinalLoc.isValid()) 13418 Record->addAttr(new (Context) 13419 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13420 13421 // C++ [class]p2: 13422 // [...] The class-name is also inserted into the scope of the 13423 // class itself; this is known as the injected-class-name. For 13424 // purposes of access checking, the injected-class-name is treated 13425 // as if it were a public member name. 13426 CXXRecordDecl *InjectedClassName 13427 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13428 Record->getLocStart(), Record->getLocation(), 13429 Record->getIdentifier(), 13430 /*PrevDecl=*/nullptr, 13431 /*DelayTypeCreation=*/true); 13432 Context.getTypeDeclType(InjectedClassName, Record); 13433 InjectedClassName->setImplicit(); 13434 InjectedClassName->setAccess(AS_public); 13435 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13436 InjectedClassName->setDescribedClassTemplate(Template); 13437 PushOnScopeChains(InjectedClassName, S); 13438 assert(InjectedClassName->isInjectedClassName() && 13439 "Broken injected-class-name"); 13440 } 13441 13442 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13443 SourceRange BraceRange) { 13444 AdjustDeclIfTemplate(TagD); 13445 TagDecl *Tag = cast<TagDecl>(TagD); 13446 Tag->setBraceRange(BraceRange); 13447 13448 // Make sure we "complete" the definition even it is invalid. 13449 if (Tag->isBeingDefined()) { 13450 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13451 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13452 RD->completeDefinition(); 13453 } 13454 13455 if (isa<CXXRecordDecl>(Tag)) 13456 FieldCollector->FinishClass(); 13457 13458 // Exit this scope of this tag's definition. 13459 PopDeclContext(); 13460 13461 if (getCurLexicalContext()->isObjCContainer() && 13462 Tag->getDeclContext()->isFileContext()) 13463 Tag->setTopLevelDeclInObjCContainer(); 13464 13465 // Notify the consumer that we've defined a tag. 13466 if (!Tag->isInvalidDecl()) 13467 Consumer.HandleTagDeclDefinition(Tag); 13468 } 13469 13470 void Sema::ActOnObjCContainerFinishDefinition() { 13471 // Exit this scope of this interface definition. 13472 PopDeclContext(); 13473 } 13474 13475 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13476 assert(DC == CurContext && "Mismatch of container contexts"); 13477 OriginalLexicalContext = DC; 13478 ActOnObjCContainerFinishDefinition(); 13479 } 13480 13481 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13482 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13483 OriginalLexicalContext = nullptr; 13484 } 13485 13486 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13487 AdjustDeclIfTemplate(TagD); 13488 TagDecl *Tag = cast<TagDecl>(TagD); 13489 Tag->setInvalidDecl(); 13490 13491 // Make sure we "complete" the definition even it is invalid. 13492 if (Tag->isBeingDefined()) { 13493 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13494 RD->completeDefinition(); 13495 } 13496 13497 // We're undoing ActOnTagStartDefinition here, not 13498 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 13499 // the FieldCollector. 13500 13501 PopDeclContext(); 13502 } 13503 13504 // Note that FieldName may be null for anonymous bitfields. 13505 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 13506 IdentifierInfo *FieldName, 13507 QualType FieldTy, bool IsMsStruct, 13508 Expr *BitWidth, bool *ZeroWidth) { 13509 // Default to true; that shouldn't confuse checks for emptiness 13510 if (ZeroWidth) 13511 *ZeroWidth = true; 13512 13513 // C99 6.7.2.1p4 - verify the field type. 13514 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 13515 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 13516 // Handle incomplete types with specific error. 13517 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 13518 return ExprError(); 13519 if (FieldName) 13520 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 13521 << FieldName << FieldTy << BitWidth->getSourceRange(); 13522 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 13523 << FieldTy << BitWidth->getSourceRange(); 13524 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 13525 UPPC_BitFieldWidth)) 13526 return ExprError(); 13527 13528 // If the bit-width is type- or value-dependent, don't try to check 13529 // it now. 13530 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 13531 return BitWidth; 13532 13533 llvm::APSInt Value; 13534 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 13535 if (ICE.isInvalid()) 13536 return ICE; 13537 BitWidth = ICE.get(); 13538 13539 if (Value != 0 && ZeroWidth) 13540 *ZeroWidth = false; 13541 13542 // Zero-width bitfield is ok for anonymous field. 13543 if (Value == 0 && FieldName) 13544 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 13545 13546 if (Value.isSigned() && Value.isNegative()) { 13547 if (FieldName) 13548 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 13549 << FieldName << Value.toString(10); 13550 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 13551 << Value.toString(10); 13552 } 13553 13554 if (!FieldTy->isDependentType()) { 13555 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 13556 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 13557 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 13558 13559 // Over-wide bitfields are an error in C or when using the MSVC bitfield 13560 // ABI. 13561 bool CStdConstraintViolation = 13562 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 13563 bool MSBitfieldViolation = 13564 Value.ugt(TypeStorageSize) && 13565 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 13566 if (CStdConstraintViolation || MSBitfieldViolation) { 13567 unsigned DiagWidth = 13568 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 13569 if (FieldName) 13570 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 13571 << FieldName << (unsigned)Value.getZExtValue() 13572 << !CStdConstraintViolation << DiagWidth; 13573 13574 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 13575 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 13576 << DiagWidth; 13577 } 13578 13579 // Warn on types where the user might conceivably expect to get all 13580 // specified bits as value bits: that's all integral types other than 13581 // 'bool'. 13582 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13583 if (FieldName) 13584 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13585 << FieldName << (unsigned)Value.getZExtValue() 13586 << (unsigned)TypeWidth; 13587 else 13588 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13589 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13590 } 13591 } 13592 13593 return BitWidth; 13594 } 13595 13596 /// ActOnField - Each field of a C struct/union is passed into this in order 13597 /// to create a FieldDecl object for it. 13598 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13599 Declarator &D, Expr *BitfieldWidth) { 13600 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13601 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13602 /*InitStyle=*/ICIS_NoInit, AS_public); 13603 return Res; 13604 } 13605 13606 /// HandleField - Analyze a field of a C struct or a C++ data member. 13607 /// 13608 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13609 SourceLocation DeclStart, 13610 Declarator &D, Expr *BitWidth, 13611 InClassInitStyle InitStyle, 13612 AccessSpecifier AS) { 13613 if (D.isDecompositionDeclarator()) { 13614 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 13615 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 13616 << Decomp.getSourceRange(); 13617 return nullptr; 13618 } 13619 13620 IdentifierInfo *II = D.getIdentifier(); 13621 SourceLocation Loc = DeclStart; 13622 if (II) Loc = D.getIdentifierLoc(); 13623 13624 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13625 QualType T = TInfo->getType(); 13626 if (getLangOpts().CPlusPlus) { 13627 CheckExtraCXXDefaultArguments(D); 13628 13629 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13630 UPPC_DataMemberType)) { 13631 D.setInvalidType(); 13632 T = Context.IntTy; 13633 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13634 } 13635 } 13636 13637 // TR 18037 does not allow fields to be declared with address spaces. 13638 if (T.getQualifiers().hasAddressSpace()) { 13639 Diag(Loc, diag::err_field_with_address_space); 13640 D.setInvalidType(); 13641 } 13642 13643 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 13644 // used as structure or union field: image, sampler, event or block types. 13645 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 13646 T->isSamplerT() || T->isBlockPointerType())) { 13647 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 13648 D.setInvalidType(); 13649 } 13650 13651 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13652 13653 if (D.getDeclSpec().isInlineSpecified()) 13654 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 13655 << getLangOpts().CPlusPlus1z; 13656 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13657 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13658 diag::err_invalid_thread) 13659 << DeclSpec::getSpecifierName(TSCS); 13660 13661 // Check to see if this name was declared as a member previously 13662 NamedDecl *PrevDecl = nullptr; 13663 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13664 LookupName(Previous, S); 13665 switch (Previous.getResultKind()) { 13666 case LookupResult::Found: 13667 case LookupResult::FoundUnresolvedValue: 13668 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13669 break; 13670 13671 case LookupResult::FoundOverloaded: 13672 PrevDecl = Previous.getRepresentativeDecl(); 13673 break; 13674 13675 case LookupResult::NotFound: 13676 case LookupResult::NotFoundInCurrentInstantiation: 13677 case LookupResult::Ambiguous: 13678 break; 13679 } 13680 Previous.suppressDiagnostics(); 13681 13682 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13683 // Maybe we will complain about the shadowed template parameter. 13684 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13685 // Just pretend that we didn't see the previous declaration. 13686 PrevDecl = nullptr; 13687 } 13688 13689 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13690 PrevDecl = nullptr; 13691 13692 bool Mutable 13693 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 13694 SourceLocation TSSL = D.getLocStart(); 13695 FieldDecl *NewFD 13696 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 13697 TSSL, AS, PrevDecl, &D); 13698 13699 if (NewFD->isInvalidDecl()) 13700 Record->setInvalidDecl(); 13701 13702 if (D.getDeclSpec().isModulePrivateSpecified()) 13703 NewFD->setModulePrivate(); 13704 13705 if (NewFD->isInvalidDecl() && PrevDecl) { 13706 // Don't introduce NewFD into scope; there's already something 13707 // with the same name in the same scope. 13708 } else if (II) { 13709 PushOnScopeChains(NewFD, S); 13710 } else 13711 Record->addDecl(NewFD); 13712 13713 return NewFD; 13714 } 13715 13716 /// \brief Build a new FieldDecl and check its well-formedness. 13717 /// 13718 /// This routine builds a new FieldDecl given the fields name, type, 13719 /// record, etc. \p PrevDecl should refer to any previous declaration 13720 /// with the same name and in the same scope as the field to be 13721 /// created. 13722 /// 13723 /// \returns a new FieldDecl. 13724 /// 13725 /// \todo The Declarator argument is a hack. It will be removed once 13726 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 13727 TypeSourceInfo *TInfo, 13728 RecordDecl *Record, SourceLocation Loc, 13729 bool Mutable, Expr *BitWidth, 13730 InClassInitStyle InitStyle, 13731 SourceLocation TSSL, 13732 AccessSpecifier AS, NamedDecl *PrevDecl, 13733 Declarator *D) { 13734 IdentifierInfo *II = Name.getAsIdentifierInfo(); 13735 bool InvalidDecl = false; 13736 if (D) InvalidDecl = D->isInvalidType(); 13737 13738 // If we receive a broken type, recover by assuming 'int' and 13739 // marking this declaration as invalid. 13740 if (T.isNull()) { 13741 InvalidDecl = true; 13742 T = Context.IntTy; 13743 } 13744 13745 QualType EltTy = Context.getBaseElementType(T); 13746 if (!EltTy->isDependentType()) { 13747 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 13748 // Fields of incomplete type force their record to be invalid. 13749 Record->setInvalidDecl(); 13750 InvalidDecl = true; 13751 } else { 13752 NamedDecl *Def; 13753 EltTy->isIncompleteType(&Def); 13754 if (Def && Def->isInvalidDecl()) { 13755 Record->setInvalidDecl(); 13756 InvalidDecl = true; 13757 } 13758 } 13759 } 13760 13761 // OpenCL v1.2 s6.9.c: bitfields are not supported. 13762 if (BitWidth && getLangOpts().OpenCL) { 13763 Diag(Loc, diag::err_opencl_bitfields); 13764 InvalidDecl = true; 13765 } 13766 13767 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13768 // than a variably modified type. 13769 if (!InvalidDecl && T->isVariablyModifiedType()) { 13770 bool SizeIsNegative; 13771 llvm::APSInt Oversized; 13772 13773 TypeSourceInfo *FixedTInfo = 13774 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 13775 SizeIsNegative, 13776 Oversized); 13777 if (FixedTInfo) { 13778 Diag(Loc, diag::warn_illegal_constant_array_size); 13779 TInfo = FixedTInfo; 13780 T = FixedTInfo->getType(); 13781 } else { 13782 if (SizeIsNegative) 13783 Diag(Loc, diag::err_typecheck_negative_array_size); 13784 else if (Oversized.getBoolValue()) 13785 Diag(Loc, diag::err_array_too_large) 13786 << Oversized.toString(10); 13787 else 13788 Diag(Loc, diag::err_typecheck_field_variable_size); 13789 InvalidDecl = true; 13790 } 13791 } 13792 13793 // Fields can not have abstract class types 13794 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 13795 diag::err_abstract_type_in_decl, 13796 AbstractFieldType)) 13797 InvalidDecl = true; 13798 13799 bool ZeroWidth = false; 13800 if (InvalidDecl) 13801 BitWidth = nullptr; 13802 // If this is declared as a bit-field, check the bit-field. 13803 if (BitWidth) { 13804 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 13805 &ZeroWidth).get(); 13806 if (!BitWidth) { 13807 InvalidDecl = true; 13808 BitWidth = nullptr; 13809 ZeroWidth = false; 13810 } 13811 } 13812 13813 // Check that 'mutable' is consistent with the type of the declaration. 13814 if (!InvalidDecl && Mutable) { 13815 unsigned DiagID = 0; 13816 if (T->isReferenceType()) 13817 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 13818 : diag::err_mutable_reference; 13819 else if (T.isConstQualified()) 13820 DiagID = diag::err_mutable_const; 13821 13822 if (DiagID) { 13823 SourceLocation ErrLoc = Loc; 13824 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 13825 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 13826 Diag(ErrLoc, DiagID); 13827 if (DiagID != diag::ext_mutable_reference) { 13828 Mutable = false; 13829 InvalidDecl = true; 13830 } 13831 } 13832 } 13833 13834 // C++11 [class.union]p8 (DR1460): 13835 // At most one variant member of a union may have a 13836 // brace-or-equal-initializer. 13837 if (InitStyle != ICIS_NoInit) 13838 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 13839 13840 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 13841 BitWidth, Mutable, InitStyle); 13842 if (InvalidDecl) 13843 NewFD->setInvalidDecl(); 13844 13845 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 13846 Diag(Loc, diag::err_duplicate_member) << II; 13847 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13848 NewFD->setInvalidDecl(); 13849 } 13850 13851 if (!InvalidDecl && getLangOpts().CPlusPlus) { 13852 if (Record->isUnion()) { 13853 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13854 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13855 if (RDecl->getDefinition()) { 13856 // C++ [class.union]p1: An object of a class with a non-trivial 13857 // constructor, a non-trivial copy constructor, a non-trivial 13858 // destructor, or a non-trivial copy assignment operator 13859 // cannot be a member of a union, nor can an array of such 13860 // objects. 13861 if (CheckNontrivialField(NewFD)) 13862 NewFD->setInvalidDecl(); 13863 } 13864 } 13865 13866 // C++ [class.union]p1: If a union contains a member of reference type, 13867 // the program is ill-formed, except when compiling with MSVC extensions 13868 // enabled. 13869 if (EltTy->isReferenceType()) { 13870 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 13871 diag::ext_union_member_of_reference_type : 13872 diag::err_union_member_of_reference_type) 13873 << NewFD->getDeclName() << EltTy; 13874 if (!getLangOpts().MicrosoftExt) 13875 NewFD->setInvalidDecl(); 13876 } 13877 } 13878 } 13879 13880 // FIXME: We need to pass in the attributes given an AST 13881 // representation, not a parser representation. 13882 if (D) { 13883 // FIXME: The current scope is almost... but not entirely... correct here. 13884 ProcessDeclAttributes(getCurScope(), NewFD, *D); 13885 13886 if (NewFD->hasAttrs()) 13887 CheckAlignasUnderalignment(NewFD); 13888 } 13889 13890 // In auto-retain/release, infer strong retension for fields of 13891 // retainable type. 13892 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 13893 NewFD->setInvalidDecl(); 13894 13895 if (T.isObjCGCWeak()) 13896 Diag(Loc, diag::warn_attribute_weak_on_field); 13897 13898 NewFD->setAccess(AS); 13899 return NewFD; 13900 } 13901 13902 bool Sema::CheckNontrivialField(FieldDecl *FD) { 13903 assert(FD); 13904 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 13905 13906 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 13907 return false; 13908 13909 QualType EltTy = Context.getBaseElementType(FD->getType()); 13910 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13911 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13912 if (RDecl->getDefinition()) { 13913 // We check for copy constructors before constructors 13914 // because otherwise we'll never get complaints about 13915 // copy constructors. 13916 13917 CXXSpecialMember member = CXXInvalid; 13918 // We're required to check for any non-trivial constructors. Since the 13919 // implicit default constructor is suppressed if there are any 13920 // user-declared constructors, we just need to check that there is a 13921 // trivial default constructor and a trivial copy constructor. (We don't 13922 // worry about move constructors here, since this is a C++98 check.) 13923 if (RDecl->hasNonTrivialCopyConstructor()) 13924 member = CXXCopyConstructor; 13925 else if (!RDecl->hasTrivialDefaultConstructor()) 13926 member = CXXDefaultConstructor; 13927 else if (RDecl->hasNonTrivialCopyAssignment()) 13928 member = CXXCopyAssignment; 13929 else if (RDecl->hasNonTrivialDestructor()) 13930 member = CXXDestructor; 13931 13932 if (member != CXXInvalid) { 13933 if (!getLangOpts().CPlusPlus11 && 13934 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 13935 // Objective-C++ ARC: it is an error to have a non-trivial field of 13936 // a union. However, system headers in Objective-C programs 13937 // occasionally have Objective-C lifetime objects within unions, 13938 // and rather than cause the program to fail, we make those 13939 // members unavailable. 13940 SourceLocation Loc = FD->getLocation(); 13941 if (getSourceManager().isInSystemHeader(Loc)) { 13942 if (!FD->hasAttr<UnavailableAttr>()) 13943 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13944 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 13945 return false; 13946 } 13947 } 13948 13949 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 13950 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 13951 diag::err_illegal_union_or_anon_struct_member) 13952 << FD->getParent()->isUnion() << FD->getDeclName() << member; 13953 DiagnoseNontrivial(RDecl, member); 13954 return !getLangOpts().CPlusPlus11; 13955 } 13956 } 13957 } 13958 13959 return false; 13960 } 13961 13962 /// TranslateIvarVisibility - Translate visibility from a token ID to an 13963 /// AST enum value. 13964 static ObjCIvarDecl::AccessControl 13965 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 13966 switch (ivarVisibility) { 13967 default: llvm_unreachable("Unknown visitibility kind"); 13968 case tok::objc_private: return ObjCIvarDecl::Private; 13969 case tok::objc_public: return ObjCIvarDecl::Public; 13970 case tok::objc_protected: return ObjCIvarDecl::Protected; 13971 case tok::objc_package: return ObjCIvarDecl::Package; 13972 } 13973 } 13974 13975 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 13976 /// in order to create an IvarDecl object for it. 13977 Decl *Sema::ActOnIvar(Scope *S, 13978 SourceLocation DeclStart, 13979 Declarator &D, Expr *BitfieldWidth, 13980 tok::ObjCKeywordKind Visibility) { 13981 13982 IdentifierInfo *II = D.getIdentifier(); 13983 Expr *BitWidth = (Expr*)BitfieldWidth; 13984 SourceLocation Loc = DeclStart; 13985 if (II) Loc = D.getIdentifierLoc(); 13986 13987 // FIXME: Unnamed fields can be handled in various different ways, for 13988 // example, unnamed unions inject all members into the struct namespace! 13989 13990 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13991 QualType T = TInfo->getType(); 13992 13993 if (BitWidth) { 13994 // 6.7.2.1p3, 6.7.2.1p4 13995 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 13996 if (!BitWidth) 13997 D.setInvalidType(); 13998 } else { 13999 // Not a bitfield. 14000 14001 // validate II. 14002 14003 } 14004 if (T->isReferenceType()) { 14005 Diag(Loc, diag::err_ivar_reference_type); 14006 D.setInvalidType(); 14007 } 14008 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14009 // than a variably modified type. 14010 else if (T->isVariablyModifiedType()) { 14011 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14012 D.setInvalidType(); 14013 } 14014 14015 // Get the visibility (access control) for this ivar. 14016 ObjCIvarDecl::AccessControl ac = 14017 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14018 : ObjCIvarDecl::None; 14019 // Must set ivar's DeclContext to its enclosing interface. 14020 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14021 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14022 return nullptr; 14023 ObjCContainerDecl *EnclosingContext; 14024 if (ObjCImplementationDecl *IMPDecl = 14025 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14026 if (LangOpts.ObjCRuntime.isFragile()) { 14027 // Case of ivar declared in an implementation. Context is that of its class. 14028 EnclosingContext = IMPDecl->getClassInterface(); 14029 assert(EnclosingContext && "Implementation has no class interface!"); 14030 } 14031 else 14032 EnclosingContext = EnclosingDecl; 14033 } else { 14034 if (ObjCCategoryDecl *CDecl = 14035 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14036 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14037 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14038 return nullptr; 14039 } 14040 } 14041 EnclosingContext = EnclosingDecl; 14042 } 14043 14044 // Construct the decl. 14045 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14046 DeclStart, Loc, II, T, 14047 TInfo, ac, (Expr *)BitfieldWidth); 14048 14049 if (II) { 14050 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14051 ForRedeclaration); 14052 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14053 && !isa<TagDecl>(PrevDecl)) { 14054 Diag(Loc, diag::err_duplicate_member) << II; 14055 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14056 NewID->setInvalidDecl(); 14057 } 14058 } 14059 14060 // Process attributes attached to the ivar. 14061 ProcessDeclAttributes(S, NewID, D); 14062 14063 if (D.isInvalidType()) 14064 NewID->setInvalidDecl(); 14065 14066 // In ARC, infer 'retaining' for ivars of retainable type. 14067 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14068 NewID->setInvalidDecl(); 14069 14070 if (D.getDeclSpec().isModulePrivateSpecified()) 14071 NewID->setModulePrivate(); 14072 14073 if (II) { 14074 // FIXME: When interfaces are DeclContexts, we'll need to add 14075 // these to the interface. 14076 S->AddDecl(NewID); 14077 IdResolver.AddDecl(NewID); 14078 } 14079 14080 if (LangOpts.ObjCRuntime.isNonFragile() && 14081 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14082 Diag(Loc, diag::warn_ivars_in_interface); 14083 14084 return NewID; 14085 } 14086 14087 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14088 /// class and class extensions. For every class \@interface and class 14089 /// extension \@interface, if the last ivar is a bitfield of any type, 14090 /// then add an implicit `char :0` ivar to the end of that interface. 14091 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14092 SmallVectorImpl<Decl *> &AllIvarDecls) { 14093 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14094 return; 14095 14096 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14097 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14098 14099 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14100 return; 14101 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14102 if (!ID) { 14103 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14104 if (!CD->IsClassExtension()) 14105 return; 14106 } 14107 // No need to add this to end of @implementation. 14108 else 14109 return; 14110 } 14111 // All conditions are met. Add a new bitfield to the tail end of ivars. 14112 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14113 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14114 14115 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14116 DeclLoc, DeclLoc, nullptr, 14117 Context.CharTy, 14118 Context.getTrivialTypeSourceInfo(Context.CharTy, 14119 DeclLoc), 14120 ObjCIvarDecl::Private, BW, 14121 true); 14122 AllIvarDecls.push_back(Ivar); 14123 } 14124 14125 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14126 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14127 SourceLocation RBrac, AttributeList *Attr) { 14128 assert(EnclosingDecl && "missing record or interface decl"); 14129 14130 // If this is an Objective-C @implementation or category and we have 14131 // new fields here we should reset the layout of the interface since 14132 // it will now change. 14133 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14134 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14135 switch (DC->getKind()) { 14136 default: break; 14137 case Decl::ObjCCategory: 14138 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14139 break; 14140 case Decl::ObjCImplementation: 14141 Context. 14142 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14143 break; 14144 } 14145 } 14146 14147 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14148 14149 // Start counting up the number of named members; make sure to include 14150 // members of anonymous structs and unions in the total. 14151 unsigned NumNamedMembers = 0; 14152 if (Record) { 14153 for (const auto *I : Record->decls()) { 14154 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14155 if (IFD->getDeclName()) 14156 ++NumNamedMembers; 14157 } 14158 } 14159 14160 // Verify that all the fields are okay. 14161 SmallVector<FieldDecl*, 32> RecFields; 14162 14163 bool ARCErrReported = false; 14164 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14165 i != end; ++i) { 14166 FieldDecl *FD = cast<FieldDecl>(*i); 14167 14168 // Get the type for the field. 14169 const Type *FDTy = FD->getType().getTypePtr(); 14170 14171 if (!FD->isAnonymousStructOrUnion()) { 14172 // Remember all fields written by the user. 14173 RecFields.push_back(FD); 14174 } 14175 14176 // If the field is already invalid for some reason, don't emit more 14177 // diagnostics about it. 14178 if (FD->isInvalidDecl()) { 14179 EnclosingDecl->setInvalidDecl(); 14180 continue; 14181 } 14182 14183 // C99 6.7.2.1p2: 14184 // A structure or union shall not contain a member with 14185 // incomplete or function type (hence, a structure shall not 14186 // contain an instance of itself, but may contain a pointer to 14187 // an instance of itself), except that the last member of a 14188 // structure with more than one named member may have incomplete 14189 // array type; such a structure (and any union containing, 14190 // possibly recursively, a member that is such a structure) 14191 // shall not be a member of a structure or an element of an 14192 // array. 14193 if (FDTy->isFunctionType()) { 14194 // Field declared as a function. 14195 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14196 << FD->getDeclName(); 14197 FD->setInvalidDecl(); 14198 EnclosingDecl->setInvalidDecl(); 14199 continue; 14200 } else if (FDTy->isIncompleteArrayType() && Record && 14201 ((i + 1 == Fields.end() && !Record->isUnion()) || 14202 ((getLangOpts().MicrosoftExt || 14203 getLangOpts().CPlusPlus) && 14204 (i + 1 == Fields.end() || Record->isUnion())))) { 14205 // Flexible array member. 14206 // Microsoft and g++ is more permissive regarding flexible array. 14207 // It will accept flexible array in union and also 14208 // as the sole element of a struct/class. 14209 unsigned DiagID = 0; 14210 if (Record->isUnion()) 14211 DiagID = getLangOpts().MicrosoftExt 14212 ? diag::ext_flexible_array_union_ms 14213 : getLangOpts().CPlusPlus 14214 ? diag::ext_flexible_array_union_gnu 14215 : diag::err_flexible_array_union; 14216 else if (NumNamedMembers < 1) 14217 DiagID = getLangOpts().MicrosoftExt 14218 ? diag::ext_flexible_array_empty_aggregate_ms 14219 : getLangOpts().CPlusPlus 14220 ? diag::ext_flexible_array_empty_aggregate_gnu 14221 : diag::err_flexible_array_empty_aggregate; 14222 14223 if (DiagID) 14224 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14225 << Record->getTagKind(); 14226 // While the layout of types that contain virtual bases is not specified 14227 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14228 // virtual bases after the derived members. This would make a flexible 14229 // array member declared at the end of an object not adjacent to the end 14230 // of the type. 14231 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14232 if (RD->getNumVBases() != 0) 14233 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14234 << FD->getDeclName() << Record->getTagKind(); 14235 if (!getLangOpts().C99) 14236 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14237 << FD->getDeclName() << Record->getTagKind(); 14238 14239 // If the element type has a non-trivial destructor, we would not 14240 // implicitly destroy the elements, so disallow it for now. 14241 // 14242 // FIXME: GCC allows this. We should probably either implicitly delete 14243 // the destructor of the containing class, or just allow this. 14244 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14245 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14246 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14247 << FD->getDeclName() << FD->getType(); 14248 FD->setInvalidDecl(); 14249 EnclosingDecl->setInvalidDecl(); 14250 continue; 14251 } 14252 // Okay, we have a legal flexible array member at the end of the struct. 14253 Record->setHasFlexibleArrayMember(true); 14254 } else if (!FDTy->isDependentType() && 14255 RequireCompleteType(FD->getLocation(), FD->getType(), 14256 diag::err_field_incomplete)) { 14257 // Incomplete type 14258 FD->setInvalidDecl(); 14259 EnclosingDecl->setInvalidDecl(); 14260 continue; 14261 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14262 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14263 // A type which contains a flexible array member is considered to be a 14264 // flexible array member. 14265 Record->setHasFlexibleArrayMember(true); 14266 if (!Record->isUnion()) { 14267 // If this is a struct/class and this is not the last element, reject 14268 // it. Note that GCC supports variable sized arrays in the middle of 14269 // structures. 14270 if (i + 1 != Fields.end()) 14271 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14272 << FD->getDeclName() << FD->getType(); 14273 else { 14274 // We support flexible arrays at the end of structs in 14275 // other structs as an extension. 14276 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14277 << FD->getDeclName(); 14278 } 14279 } 14280 } 14281 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14282 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14283 diag::err_abstract_type_in_decl, 14284 AbstractIvarType)) { 14285 // Ivars can not have abstract class types 14286 FD->setInvalidDecl(); 14287 } 14288 if (Record && FDTTy->getDecl()->hasObjectMember()) 14289 Record->setHasObjectMember(true); 14290 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14291 Record->setHasVolatileMember(true); 14292 } else if (FDTy->isObjCObjectType()) { 14293 /// A field cannot be an Objective-c object 14294 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14295 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14296 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14297 FD->setType(T); 14298 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 14299 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14300 // It's an error in ARC if a field has lifetime. 14301 // We don't want to report this in a system header, though, 14302 // so we just make the field unavailable. 14303 // FIXME: that's really not sufficient; we need to make the type 14304 // itself invalid to, say, initialize or copy. 14305 QualType T = FD->getType(); 14306 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 14307 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 14308 SourceLocation loc = FD->getLocation(); 14309 if (getSourceManager().isInSystemHeader(loc)) { 14310 if (!FD->hasAttr<UnavailableAttr>()) { 14311 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14312 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14313 } 14314 } else { 14315 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14316 << T->isBlockPointerType() << Record->getTagKind(); 14317 } 14318 ARCErrReported = true; 14319 } 14320 } else if (getLangOpts().ObjC1 && 14321 getLangOpts().getGC() != LangOptions::NonGC && 14322 Record && !Record->hasObjectMember()) { 14323 if (FD->getType()->isObjCObjectPointerType() || 14324 FD->getType().isObjCGCStrong()) 14325 Record->setHasObjectMember(true); 14326 else if (Context.getAsArrayType(FD->getType())) { 14327 QualType BaseType = Context.getBaseElementType(FD->getType()); 14328 if (BaseType->isRecordType() && 14329 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14330 Record->setHasObjectMember(true); 14331 else if (BaseType->isObjCObjectPointerType() || 14332 BaseType.isObjCGCStrong()) 14333 Record->setHasObjectMember(true); 14334 } 14335 } 14336 if (Record && FD->getType().isVolatileQualified()) 14337 Record->setHasVolatileMember(true); 14338 // Keep track of the number of named members. 14339 if (FD->getIdentifier()) 14340 ++NumNamedMembers; 14341 } 14342 14343 // Okay, we successfully defined 'Record'. 14344 if (Record) { 14345 bool Completed = false; 14346 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14347 if (!CXXRecord->isInvalidDecl()) { 14348 // Set access bits correctly on the directly-declared conversions. 14349 for (CXXRecordDecl::conversion_iterator 14350 I = CXXRecord->conversion_begin(), 14351 E = CXXRecord->conversion_end(); I != E; ++I) 14352 I.setAccess((*I)->getAccess()); 14353 } 14354 14355 if (!CXXRecord->isDependentType()) { 14356 if (CXXRecord->hasUserDeclaredDestructor()) { 14357 // Adjust user-defined destructor exception spec. 14358 if (getLangOpts().CPlusPlus11) 14359 AdjustDestructorExceptionSpec(CXXRecord, 14360 CXXRecord->getDestructor()); 14361 } 14362 14363 if (!CXXRecord->isInvalidDecl()) { 14364 // Add any implicitly-declared members to this class. 14365 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14366 14367 // If we have virtual base classes, we may end up finding multiple 14368 // final overriders for a given virtual function. Check for this 14369 // problem now. 14370 if (CXXRecord->getNumVBases()) { 14371 CXXFinalOverriderMap FinalOverriders; 14372 CXXRecord->getFinalOverriders(FinalOverriders); 14373 14374 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14375 MEnd = FinalOverriders.end(); 14376 M != MEnd; ++M) { 14377 for (OverridingMethods::iterator SO = M->second.begin(), 14378 SOEnd = M->second.end(); 14379 SO != SOEnd; ++SO) { 14380 assert(SO->second.size() > 0 && 14381 "Virtual function without overridding functions?"); 14382 if (SO->second.size() == 1) 14383 continue; 14384 14385 // C++ [class.virtual]p2: 14386 // In a derived class, if a virtual member function of a base 14387 // class subobject has more than one final overrider the 14388 // program is ill-formed. 14389 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14390 << (const NamedDecl *)M->first << Record; 14391 Diag(M->first->getLocation(), 14392 diag::note_overridden_virtual_function); 14393 for (OverridingMethods::overriding_iterator 14394 OM = SO->second.begin(), 14395 OMEnd = SO->second.end(); 14396 OM != OMEnd; ++OM) 14397 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14398 << (const NamedDecl *)M->first << OM->Method->getParent(); 14399 14400 Record->setInvalidDecl(); 14401 } 14402 } 14403 CXXRecord->completeDefinition(&FinalOverriders); 14404 Completed = true; 14405 } 14406 } 14407 } 14408 } 14409 14410 if (!Completed) 14411 Record->completeDefinition(); 14412 14413 // We may have deferred checking for a deleted destructor. Check now. 14414 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14415 auto *Dtor = CXXRecord->getDestructor(); 14416 if (Dtor && Dtor->isImplicit() && 14417 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14418 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14419 } 14420 14421 if (Record->hasAttrs()) { 14422 CheckAlignasUnderalignment(Record); 14423 14424 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14425 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14426 IA->getRange(), IA->getBestCase(), 14427 IA->getSemanticSpelling()); 14428 } 14429 14430 // Check if the structure/union declaration is a type that can have zero 14431 // size in C. For C this is a language extension, for C++ it may cause 14432 // compatibility problems. 14433 bool CheckForZeroSize; 14434 if (!getLangOpts().CPlusPlus) { 14435 CheckForZeroSize = true; 14436 } else { 14437 // For C++ filter out types that cannot be referenced in C code. 14438 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14439 CheckForZeroSize = 14440 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14441 !CXXRecord->isDependentType() && 14442 CXXRecord->isCLike(); 14443 } 14444 if (CheckForZeroSize) { 14445 bool ZeroSize = true; 14446 bool IsEmpty = true; 14447 unsigned NonBitFields = 0; 14448 for (RecordDecl::field_iterator I = Record->field_begin(), 14449 E = Record->field_end(); 14450 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14451 IsEmpty = false; 14452 if (I->isUnnamedBitfield()) { 14453 if (I->getBitWidthValue(Context) > 0) 14454 ZeroSize = false; 14455 } else { 14456 ++NonBitFields; 14457 QualType FieldType = I->getType(); 14458 if (FieldType->isIncompleteType() || 14459 !Context.getTypeSizeInChars(FieldType).isZero()) 14460 ZeroSize = false; 14461 } 14462 } 14463 14464 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14465 // allowed in C++, but warn if its declaration is inside 14466 // extern "C" block. 14467 if (ZeroSize) { 14468 Diag(RecLoc, getLangOpts().CPlusPlus ? 14469 diag::warn_zero_size_struct_union_in_extern_c : 14470 diag::warn_zero_size_struct_union_compat) 14471 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14472 } 14473 14474 // Structs without named members are extension in C (C99 6.7.2.1p7), 14475 // but are accepted by GCC. 14476 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14477 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14478 diag::ext_no_named_members_in_struct_union) 14479 << Record->isUnion(); 14480 } 14481 } 14482 } else { 14483 ObjCIvarDecl **ClsFields = 14484 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14485 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14486 ID->setEndOfDefinitionLoc(RBrac); 14487 // Add ivar's to class's DeclContext. 14488 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14489 ClsFields[i]->setLexicalDeclContext(ID); 14490 ID->addDecl(ClsFields[i]); 14491 } 14492 // Must enforce the rule that ivars in the base classes may not be 14493 // duplicates. 14494 if (ID->getSuperClass()) 14495 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 14496 } else if (ObjCImplementationDecl *IMPDecl = 14497 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14498 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 14499 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 14500 // Ivar declared in @implementation never belongs to the implementation. 14501 // Only it is in implementation's lexical context. 14502 ClsFields[I]->setLexicalDeclContext(IMPDecl); 14503 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 14504 IMPDecl->setIvarLBraceLoc(LBrac); 14505 IMPDecl->setIvarRBraceLoc(RBrac); 14506 } else if (ObjCCategoryDecl *CDecl = 14507 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14508 // case of ivars in class extension; all other cases have been 14509 // reported as errors elsewhere. 14510 // FIXME. Class extension does not have a LocEnd field. 14511 // CDecl->setLocEnd(RBrac); 14512 // Add ivar's to class extension's DeclContext. 14513 // Diagnose redeclaration of private ivars. 14514 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 14515 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14516 if (IDecl) { 14517 if (const ObjCIvarDecl *ClsIvar = 14518 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 14519 Diag(ClsFields[i]->getLocation(), 14520 diag::err_duplicate_ivar_declaration); 14521 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 14522 continue; 14523 } 14524 for (const auto *Ext : IDecl->known_extensions()) { 14525 if (const ObjCIvarDecl *ClsExtIvar 14526 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 14527 Diag(ClsFields[i]->getLocation(), 14528 diag::err_duplicate_ivar_declaration); 14529 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 14530 continue; 14531 } 14532 } 14533 } 14534 ClsFields[i]->setLexicalDeclContext(CDecl); 14535 CDecl->addDecl(ClsFields[i]); 14536 } 14537 CDecl->setIvarLBraceLoc(LBrac); 14538 CDecl->setIvarRBraceLoc(RBrac); 14539 } 14540 } 14541 14542 if (Attr) 14543 ProcessDeclAttributeList(S, Record, Attr); 14544 } 14545 14546 /// \brief Determine whether the given integral value is representable within 14547 /// the given type T. 14548 static bool isRepresentableIntegerValue(ASTContext &Context, 14549 llvm::APSInt &Value, 14550 QualType T) { 14551 assert(T->isIntegralType(Context) && "Integral type required!"); 14552 unsigned BitWidth = Context.getIntWidth(T); 14553 14554 if (Value.isUnsigned() || Value.isNonNegative()) { 14555 if (T->isSignedIntegerOrEnumerationType()) 14556 --BitWidth; 14557 return Value.getActiveBits() <= BitWidth; 14558 } 14559 return Value.getMinSignedBits() <= BitWidth; 14560 } 14561 14562 // \brief Given an integral type, return the next larger integral type 14563 // (or a NULL type of no such type exists). 14564 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 14565 // FIXME: Int128/UInt128 support, which also needs to be introduced into 14566 // enum checking below. 14567 assert(T->isIntegralType(Context) && "Integral type required!"); 14568 const unsigned NumTypes = 4; 14569 QualType SignedIntegralTypes[NumTypes] = { 14570 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 14571 }; 14572 QualType UnsignedIntegralTypes[NumTypes] = { 14573 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 14574 Context.UnsignedLongLongTy 14575 }; 14576 14577 unsigned BitWidth = Context.getTypeSize(T); 14578 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 14579 : UnsignedIntegralTypes; 14580 for (unsigned I = 0; I != NumTypes; ++I) 14581 if (Context.getTypeSize(Types[I]) > BitWidth) 14582 return Types[I]; 14583 14584 return QualType(); 14585 } 14586 14587 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 14588 EnumConstantDecl *LastEnumConst, 14589 SourceLocation IdLoc, 14590 IdentifierInfo *Id, 14591 Expr *Val) { 14592 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14593 llvm::APSInt EnumVal(IntWidth); 14594 QualType EltTy; 14595 14596 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 14597 Val = nullptr; 14598 14599 if (Val) 14600 Val = DefaultLvalueConversion(Val).get(); 14601 14602 if (Val) { 14603 if (Enum->isDependentType() || Val->isTypeDependent()) 14604 EltTy = Context.DependentTy; 14605 else { 14606 SourceLocation ExpLoc; 14607 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14608 !getLangOpts().MSVCCompat) { 14609 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14610 // constant-expression in the enumerator-definition shall be a converted 14611 // constant expression of the underlying type. 14612 EltTy = Enum->getIntegerType(); 14613 ExprResult Converted = 14614 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14615 CCEK_Enumerator); 14616 if (Converted.isInvalid()) 14617 Val = nullptr; 14618 else 14619 Val = Converted.get(); 14620 } else if (!Val->isValueDependent() && 14621 !(Val = VerifyIntegerConstantExpression(Val, 14622 &EnumVal).get())) { 14623 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14624 } else { 14625 if (Enum->isFixed()) { 14626 EltTy = Enum->getIntegerType(); 14627 14628 // In Obj-C and Microsoft mode, require the enumeration value to be 14629 // representable in the underlying type of the enumeration. In C++11, 14630 // we perform a non-narrowing conversion as part of converted constant 14631 // expression checking. 14632 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14633 if (getLangOpts().MSVCCompat) { 14634 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14635 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14636 } else 14637 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14638 } else 14639 Val = ImpCastExprToType(Val, EltTy, 14640 EltTy->isBooleanType() ? 14641 CK_IntegralToBoolean : CK_IntegralCast) 14642 .get(); 14643 } else if (getLangOpts().CPlusPlus) { 14644 // C++11 [dcl.enum]p5: 14645 // If the underlying type is not fixed, the type of each enumerator 14646 // is the type of its initializing value: 14647 // - If an initializer is specified for an enumerator, the 14648 // initializing value has the same type as the expression. 14649 EltTy = Val->getType(); 14650 } else { 14651 // C99 6.7.2.2p2: 14652 // The expression that defines the value of an enumeration constant 14653 // shall be an integer constant expression that has a value 14654 // representable as an int. 14655 14656 // Complain if the value is not representable in an int. 14657 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14658 Diag(IdLoc, diag::ext_enum_value_not_int) 14659 << EnumVal.toString(10) << Val->getSourceRange() 14660 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14661 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14662 // Force the type of the expression to 'int'. 14663 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14664 } 14665 EltTy = Val->getType(); 14666 } 14667 } 14668 } 14669 } 14670 14671 if (!Val) { 14672 if (Enum->isDependentType()) 14673 EltTy = Context.DependentTy; 14674 else if (!LastEnumConst) { 14675 // C++0x [dcl.enum]p5: 14676 // If the underlying type is not fixed, the type of each enumerator 14677 // is the type of its initializing value: 14678 // - If no initializer is specified for the first enumerator, the 14679 // initializing value has an unspecified integral type. 14680 // 14681 // GCC uses 'int' for its unspecified integral type, as does 14682 // C99 6.7.2.2p3. 14683 if (Enum->isFixed()) { 14684 EltTy = Enum->getIntegerType(); 14685 } 14686 else { 14687 EltTy = Context.IntTy; 14688 } 14689 } else { 14690 // Assign the last value + 1. 14691 EnumVal = LastEnumConst->getInitVal(); 14692 ++EnumVal; 14693 EltTy = LastEnumConst->getType(); 14694 14695 // Check for overflow on increment. 14696 if (EnumVal < LastEnumConst->getInitVal()) { 14697 // C++0x [dcl.enum]p5: 14698 // If the underlying type is not fixed, the type of each enumerator 14699 // is the type of its initializing value: 14700 // 14701 // - Otherwise the type of the initializing value is the same as 14702 // the type of the initializing value of the preceding enumerator 14703 // unless the incremented value is not representable in that type, 14704 // in which case the type is an unspecified integral type 14705 // sufficient to contain the incremented value. If no such type 14706 // exists, the program is ill-formed. 14707 QualType T = getNextLargerIntegralType(Context, EltTy); 14708 if (T.isNull() || Enum->isFixed()) { 14709 // There is no integral type larger enough to represent this 14710 // value. Complain, then allow the value to wrap around. 14711 EnumVal = LastEnumConst->getInitVal(); 14712 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 14713 ++EnumVal; 14714 if (Enum->isFixed()) 14715 // When the underlying type is fixed, this is ill-formed. 14716 Diag(IdLoc, diag::err_enumerator_wrapped) 14717 << EnumVal.toString(10) 14718 << EltTy; 14719 else 14720 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 14721 << EnumVal.toString(10); 14722 } else { 14723 EltTy = T; 14724 } 14725 14726 // Retrieve the last enumerator's value, extent that type to the 14727 // type that is supposed to be large enough to represent the incremented 14728 // value, then increment. 14729 EnumVal = LastEnumConst->getInitVal(); 14730 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14731 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 14732 ++EnumVal; 14733 14734 // If we're not in C++, diagnose the overflow of enumerator values, 14735 // which in C99 means that the enumerator value is not representable in 14736 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 14737 // permits enumerator values that are representable in some larger 14738 // integral type. 14739 if (!getLangOpts().CPlusPlus && !T.isNull()) 14740 Diag(IdLoc, diag::warn_enum_value_overflow); 14741 } else if (!getLangOpts().CPlusPlus && 14742 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14743 // Enforce C99 6.7.2.2p2 even when we compute the next value. 14744 Diag(IdLoc, diag::ext_enum_value_not_int) 14745 << EnumVal.toString(10) << 1; 14746 } 14747 } 14748 } 14749 14750 if (!EltTy->isDependentType()) { 14751 // Make the enumerator value match the signedness and size of the 14752 // enumerator's type. 14753 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 14754 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14755 } 14756 14757 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 14758 Val, EnumVal); 14759 } 14760 14761 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 14762 SourceLocation IILoc) { 14763 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 14764 !getLangOpts().CPlusPlus) 14765 return SkipBodyInfo(); 14766 14767 // We have an anonymous enum definition. Look up the first enumerator to 14768 // determine if we should merge the definition with an existing one and 14769 // skip the body. 14770 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 14771 ForRedeclaration); 14772 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 14773 if (!PrevECD) 14774 return SkipBodyInfo(); 14775 14776 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 14777 NamedDecl *Hidden; 14778 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 14779 SkipBodyInfo Skip; 14780 Skip.Previous = Hidden; 14781 return Skip; 14782 } 14783 14784 return SkipBodyInfo(); 14785 } 14786 14787 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 14788 SourceLocation IdLoc, IdentifierInfo *Id, 14789 AttributeList *Attr, 14790 SourceLocation EqualLoc, Expr *Val) { 14791 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 14792 EnumConstantDecl *LastEnumConst = 14793 cast_or_null<EnumConstantDecl>(lastEnumConst); 14794 14795 // The scope passed in may not be a decl scope. Zip up the scope tree until 14796 // we find one that is. 14797 S = getNonFieldDeclScope(S); 14798 14799 // Verify that there isn't already something declared with this name in this 14800 // scope. 14801 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 14802 ForRedeclaration); 14803 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14804 // Maybe we will complain about the shadowed template parameter. 14805 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 14806 // Just pretend that we didn't see the previous declaration. 14807 PrevDecl = nullptr; 14808 } 14809 14810 // C++ [class.mem]p15: 14811 // If T is the name of a class, then each of the following shall have a name 14812 // different from T: 14813 // - every enumerator of every member of class T that is an unscoped 14814 // enumerated type 14815 if (!TheEnumDecl->isScoped()) 14816 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 14817 DeclarationNameInfo(Id, IdLoc)); 14818 14819 EnumConstantDecl *New = 14820 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 14821 if (!New) 14822 return nullptr; 14823 14824 if (PrevDecl) { 14825 // When in C++, we may get a TagDecl with the same name; in this case the 14826 // enum constant will 'hide' the tag. 14827 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 14828 "Received TagDecl when not in C++!"); 14829 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 14830 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 14831 if (isa<EnumConstantDecl>(PrevDecl)) 14832 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 14833 else 14834 Diag(IdLoc, diag::err_redefinition) << Id; 14835 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14836 return nullptr; 14837 } 14838 } 14839 14840 // Process attributes. 14841 if (Attr) ProcessDeclAttributeList(S, New, Attr); 14842 14843 // Register this decl in the current scope stack. 14844 New->setAccess(TheEnumDecl->getAccess()); 14845 PushOnScopeChains(New, S); 14846 14847 ActOnDocumentableDecl(New); 14848 14849 return New; 14850 } 14851 14852 // Returns true when the enum initial expression does not trigger the 14853 // duplicate enum warning. A few common cases are exempted as follows: 14854 // Element2 = Element1 14855 // Element2 = Element1 + 1 14856 // Element2 = Element1 - 1 14857 // Where Element2 and Element1 are from the same enum. 14858 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 14859 Expr *InitExpr = ECD->getInitExpr(); 14860 if (!InitExpr) 14861 return true; 14862 InitExpr = InitExpr->IgnoreImpCasts(); 14863 14864 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 14865 if (!BO->isAdditiveOp()) 14866 return true; 14867 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 14868 if (!IL) 14869 return true; 14870 if (IL->getValue() != 1) 14871 return true; 14872 14873 InitExpr = BO->getLHS(); 14874 } 14875 14876 // This checks if the elements are from the same enum. 14877 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 14878 if (!DRE) 14879 return true; 14880 14881 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 14882 if (!EnumConstant) 14883 return true; 14884 14885 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 14886 Enum) 14887 return true; 14888 14889 return false; 14890 } 14891 14892 namespace { 14893 struct DupKey { 14894 int64_t val; 14895 bool isTombstoneOrEmptyKey; 14896 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 14897 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 14898 }; 14899 14900 static DupKey GetDupKey(const llvm::APSInt& Val) { 14901 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 14902 false); 14903 } 14904 14905 struct DenseMapInfoDupKey { 14906 static DupKey getEmptyKey() { return DupKey(0, true); } 14907 static DupKey getTombstoneKey() { return DupKey(1, true); } 14908 static unsigned getHashValue(const DupKey Key) { 14909 return (unsigned)(Key.val * 37); 14910 } 14911 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 14912 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 14913 LHS.val == RHS.val; 14914 } 14915 }; 14916 } // end anonymous namespace 14917 14918 // Emits a warning when an element is implicitly set a value that 14919 // a previous element has already been set to. 14920 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 14921 EnumDecl *Enum, 14922 QualType EnumType) { 14923 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 14924 return; 14925 // Avoid anonymous enums 14926 if (!Enum->getIdentifier()) 14927 return; 14928 14929 // Only check for small enums. 14930 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 14931 return; 14932 14933 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 14934 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 14935 14936 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 14937 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 14938 ValueToVectorMap; 14939 14940 DuplicatesVector DupVector; 14941 ValueToVectorMap EnumMap; 14942 14943 // Populate the EnumMap with all values represented by enum constants without 14944 // an initialier. 14945 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14946 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 14947 14948 // Null EnumConstantDecl means a previous diagnostic has been emitted for 14949 // this constant. Skip this enum since it may be ill-formed. 14950 if (!ECD) { 14951 return; 14952 } 14953 14954 if (ECD->getInitExpr()) 14955 continue; 14956 14957 DupKey Key = GetDupKey(ECD->getInitVal()); 14958 DeclOrVector &Entry = EnumMap[Key]; 14959 14960 // First time encountering this value. 14961 if (Entry.isNull()) 14962 Entry = ECD; 14963 } 14964 14965 // Create vectors for any values that has duplicates. 14966 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14967 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 14968 if (!ValidDuplicateEnum(ECD, Enum)) 14969 continue; 14970 14971 DupKey Key = GetDupKey(ECD->getInitVal()); 14972 14973 DeclOrVector& Entry = EnumMap[Key]; 14974 if (Entry.isNull()) 14975 continue; 14976 14977 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 14978 // Ensure constants are different. 14979 if (D == ECD) 14980 continue; 14981 14982 // Create new vector and push values onto it. 14983 ECDVector *Vec = new ECDVector(); 14984 Vec->push_back(D); 14985 Vec->push_back(ECD); 14986 14987 // Update entry to point to the duplicates vector. 14988 Entry = Vec; 14989 14990 // Store the vector somewhere we can consult later for quick emission of 14991 // diagnostics. 14992 DupVector.push_back(Vec); 14993 continue; 14994 } 14995 14996 ECDVector *Vec = Entry.get<ECDVector*>(); 14997 // Make sure constants are not added more than once. 14998 if (*Vec->begin() == ECD) 14999 continue; 15000 15001 Vec->push_back(ECD); 15002 } 15003 15004 // Emit diagnostics. 15005 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15006 DupVectorEnd = DupVector.end(); 15007 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15008 ECDVector *Vec = *DupVectorIter; 15009 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15010 15011 // Emit warning for one enum constant. 15012 ECDVector::iterator I = Vec->begin(); 15013 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15014 << (*I)->getName() << (*I)->getInitVal().toString(10) 15015 << (*I)->getSourceRange(); 15016 ++I; 15017 15018 // Emit one note for each of the remaining enum constants with 15019 // the same value. 15020 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15021 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15022 << (*I)->getName() << (*I)->getInitVal().toString(10) 15023 << (*I)->getSourceRange(); 15024 delete Vec; 15025 } 15026 } 15027 15028 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15029 bool AllowMask) const { 15030 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 15031 assert(ED->isCompleteDefinition() && "expected enum definition"); 15032 15033 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15034 llvm::APInt &FlagBits = R.first->second; 15035 15036 if (R.second) { 15037 for (auto *E : ED->enumerators()) { 15038 const auto &EVal = E->getInitVal(); 15039 // Only single-bit enumerators introduce new flag values. 15040 if (EVal.isPowerOf2()) 15041 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15042 } 15043 } 15044 15045 // A value is in a flag enum if either its bits are a subset of the enum's 15046 // flag bits (the first condition) or we are allowing masks and the same is 15047 // true of its complement (the second condition). When masks are allowed, we 15048 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15049 // 15050 // While it's true that any value could be used as a mask, the assumption is 15051 // that a mask will have all of the insignificant bits set. Anything else is 15052 // likely a logic error. 15053 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15054 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15055 } 15056 15057 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15058 Decl *EnumDeclX, 15059 ArrayRef<Decl *> Elements, 15060 Scope *S, AttributeList *Attr) { 15061 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15062 QualType EnumType = Context.getTypeDeclType(Enum); 15063 15064 if (Attr) 15065 ProcessDeclAttributeList(S, Enum, Attr); 15066 15067 if (Enum->isDependentType()) { 15068 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15069 EnumConstantDecl *ECD = 15070 cast_or_null<EnumConstantDecl>(Elements[i]); 15071 if (!ECD) continue; 15072 15073 ECD->setType(EnumType); 15074 } 15075 15076 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15077 return; 15078 } 15079 15080 // TODO: If the result value doesn't fit in an int, it must be a long or long 15081 // long value. ISO C does not support this, but GCC does as an extension, 15082 // emit a warning. 15083 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15084 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15085 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15086 15087 // Verify that all the values are okay, compute the size of the values, and 15088 // reverse the list. 15089 unsigned NumNegativeBits = 0; 15090 unsigned NumPositiveBits = 0; 15091 15092 // Keep track of whether all elements have type int. 15093 bool AllElementsInt = true; 15094 15095 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15096 EnumConstantDecl *ECD = 15097 cast_or_null<EnumConstantDecl>(Elements[i]); 15098 if (!ECD) continue; // Already issued a diagnostic. 15099 15100 const llvm::APSInt &InitVal = ECD->getInitVal(); 15101 15102 // Keep track of the size of positive and negative values. 15103 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15104 NumPositiveBits = std::max(NumPositiveBits, 15105 (unsigned)InitVal.getActiveBits()); 15106 else 15107 NumNegativeBits = std::max(NumNegativeBits, 15108 (unsigned)InitVal.getMinSignedBits()); 15109 15110 // Keep track of whether every enum element has type int (very commmon). 15111 if (AllElementsInt) 15112 AllElementsInt = ECD->getType() == Context.IntTy; 15113 } 15114 15115 // Figure out the type that should be used for this enum. 15116 QualType BestType; 15117 unsigned BestWidth; 15118 15119 // C++0x N3000 [conv.prom]p3: 15120 // An rvalue of an unscoped enumeration type whose underlying 15121 // type is not fixed can be converted to an rvalue of the first 15122 // of the following types that can represent all the values of 15123 // the enumeration: int, unsigned int, long int, unsigned long 15124 // int, long long int, or unsigned long long int. 15125 // C99 6.4.4.3p2: 15126 // An identifier declared as an enumeration constant has type int. 15127 // The C99 rule is modified by a gcc extension 15128 QualType BestPromotionType; 15129 15130 bool Packed = Enum->hasAttr<PackedAttr>(); 15131 // -fshort-enums is the equivalent to specifying the packed attribute on all 15132 // enum definitions. 15133 if (LangOpts.ShortEnums) 15134 Packed = true; 15135 15136 if (Enum->isFixed()) { 15137 BestType = Enum->getIntegerType(); 15138 if (BestType->isPromotableIntegerType()) 15139 BestPromotionType = Context.getPromotedIntegerType(BestType); 15140 else 15141 BestPromotionType = BestType; 15142 15143 BestWidth = Context.getIntWidth(BestType); 15144 } 15145 else if (NumNegativeBits) { 15146 // If there is a negative value, figure out the smallest integer type (of 15147 // int/long/longlong) that fits. 15148 // If it's packed, check also if it fits a char or a short. 15149 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15150 BestType = Context.SignedCharTy; 15151 BestWidth = CharWidth; 15152 } else if (Packed && NumNegativeBits <= ShortWidth && 15153 NumPositiveBits < ShortWidth) { 15154 BestType = Context.ShortTy; 15155 BestWidth = ShortWidth; 15156 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15157 BestType = Context.IntTy; 15158 BestWidth = IntWidth; 15159 } else { 15160 BestWidth = Context.getTargetInfo().getLongWidth(); 15161 15162 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15163 BestType = Context.LongTy; 15164 } else { 15165 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15166 15167 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15168 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15169 BestType = Context.LongLongTy; 15170 } 15171 } 15172 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15173 } else { 15174 // If there is no negative value, figure out the smallest type that fits 15175 // all of the enumerator values. 15176 // If it's packed, check also if it fits a char or a short. 15177 if (Packed && NumPositiveBits <= CharWidth) { 15178 BestType = Context.UnsignedCharTy; 15179 BestPromotionType = Context.IntTy; 15180 BestWidth = CharWidth; 15181 } else if (Packed && NumPositiveBits <= ShortWidth) { 15182 BestType = Context.UnsignedShortTy; 15183 BestPromotionType = Context.IntTy; 15184 BestWidth = ShortWidth; 15185 } else if (NumPositiveBits <= IntWidth) { 15186 BestType = Context.UnsignedIntTy; 15187 BestWidth = IntWidth; 15188 BestPromotionType 15189 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15190 ? Context.UnsignedIntTy : Context.IntTy; 15191 } else if (NumPositiveBits <= 15192 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15193 BestType = Context.UnsignedLongTy; 15194 BestPromotionType 15195 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15196 ? Context.UnsignedLongTy : Context.LongTy; 15197 } else { 15198 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15199 assert(NumPositiveBits <= BestWidth && 15200 "How could an initializer get larger than ULL?"); 15201 BestType = Context.UnsignedLongLongTy; 15202 BestPromotionType 15203 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15204 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15205 } 15206 } 15207 15208 // Loop over all of the enumerator constants, changing their types to match 15209 // the type of the enum if needed. 15210 for (auto *D : Elements) { 15211 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15212 if (!ECD) continue; // Already issued a diagnostic. 15213 15214 // Standard C says the enumerators have int type, but we allow, as an 15215 // extension, the enumerators to be larger than int size. If each 15216 // enumerator value fits in an int, type it as an int, otherwise type it the 15217 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15218 // that X has type 'int', not 'unsigned'. 15219 15220 // Determine whether the value fits into an int. 15221 llvm::APSInt InitVal = ECD->getInitVal(); 15222 15223 // If it fits into an integer type, force it. Otherwise force it to match 15224 // the enum decl type. 15225 QualType NewTy; 15226 unsigned NewWidth; 15227 bool NewSign; 15228 if (!getLangOpts().CPlusPlus && 15229 !Enum->isFixed() && 15230 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15231 NewTy = Context.IntTy; 15232 NewWidth = IntWidth; 15233 NewSign = true; 15234 } else if (ECD->getType() == BestType) { 15235 // Already the right type! 15236 if (getLangOpts().CPlusPlus) 15237 // C++ [dcl.enum]p4: Following the closing brace of an 15238 // enum-specifier, each enumerator has the type of its 15239 // enumeration. 15240 ECD->setType(EnumType); 15241 continue; 15242 } else { 15243 NewTy = BestType; 15244 NewWidth = BestWidth; 15245 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15246 } 15247 15248 // Adjust the APSInt value. 15249 InitVal = InitVal.extOrTrunc(NewWidth); 15250 InitVal.setIsSigned(NewSign); 15251 ECD->setInitVal(InitVal); 15252 15253 // Adjust the Expr initializer and type. 15254 if (ECD->getInitExpr() && 15255 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15256 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15257 CK_IntegralCast, 15258 ECD->getInitExpr(), 15259 /*base paths*/ nullptr, 15260 VK_RValue)); 15261 if (getLangOpts().CPlusPlus) 15262 // C++ [dcl.enum]p4: Following the closing brace of an 15263 // enum-specifier, each enumerator has the type of its 15264 // enumeration. 15265 ECD->setType(EnumType); 15266 else 15267 ECD->setType(NewTy); 15268 } 15269 15270 Enum->completeDefinition(BestType, BestPromotionType, 15271 NumPositiveBits, NumNegativeBits); 15272 15273 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15274 15275 if (Enum->hasAttr<FlagEnumAttr>()) { 15276 for (Decl *D : Elements) { 15277 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15278 if (!ECD) continue; // Already issued a diagnostic. 15279 15280 llvm::APSInt InitVal = ECD->getInitVal(); 15281 if (InitVal != 0 && !InitVal.isPowerOf2() && 15282 !IsValueInFlagEnum(Enum, InitVal, true)) 15283 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15284 << ECD << Enum; 15285 } 15286 } 15287 15288 // Now that the enum type is defined, ensure it's not been underaligned. 15289 if (Enum->hasAttrs()) 15290 CheckAlignasUnderalignment(Enum); 15291 } 15292 15293 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15294 SourceLocation StartLoc, 15295 SourceLocation EndLoc) { 15296 StringLiteral *AsmString = cast<StringLiteral>(expr); 15297 15298 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15299 AsmString, StartLoc, 15300 EndLoc); 15301 CurContext->addDecl(New); 15302 return New; 15303 } 15304 15305 static void checkModuleImportContext(Sema &S, Module *M, 15306 SourceLocation ImportLoc, DeclContext *DC, 15307 bool FromInclude = false) { 15308 SourceLocation ExternCLoc; 15309 15310 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15311 switch (LSD->getLanguage()) { 15312 case LinkageSpecDecl::lang_c: 15313 if (ExternCLoc.isInvalid()) 15314 ExternCLoc = LSD->getLocStart(); 15315 break; 15316 case LinkageSpecDecl::lang_cxx: 15317 break; 15318 } 15319 DC = LSD->getParent(); 15320 } 15321 15322 while (isa<LinkageSpecDecl>(DC)) 15323 DC = DC->getParent(); 15324 15325 if (!isa<TranslationUnitDecl>(DC)) { 15326 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15327 ? diag::ext_module_import_not_at_top_level_noop 15328 : diag::err_module_import_not_at_top_level_fatal) 15329 << M->getFullModuleName() << DC; 15330 S.Diag(cast<Decl>(DC)->getLocStart(), 15331 diag::note_module_import_not_at_top_level) << DC; 15332 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15333 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15334 << M->getFullModuleName(); 15335 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c); 15336 } 15337 } 15338 15339 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) { 15340 return checkModuleImportContext(*this, M, ImportLoc, CurContext); 15341 } 15342 15343 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc, 15344 ModuleDeclKind MDK, 15345 ModuleIdPath Path) { 15346 // 'module implementation' requires that we are not compiling a module of any 15347 // kind. 'module' and 'module partition' require that we are compiling a 15348 // module inteface (not a module map). 15349 auto CMK = getLangOpts().getCompilingModule(); 15350 if (MDK == ModuleDeclKind::Implementation 15351 ? CMK != LangOptions::CMK_None 15352 : CMK != LangOptions::CMK_ModuleInterface) { 15353 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15354 << (unsigned)MDK; 15355 return nullptr; 15356 } 15357 15358 // FIXME: Create a ModuleDecl and return it. 15359 15360 // FIXME: Most of this work should be done by the preprocessor rather than 15361 // here, in case we look ahead across something where the current 15362 // module matters (eg a #include). 15363 15364 // The dots in a module name in the Modules TS are a lie. Unlike Clang's 15365 // hierarchical module map modules, the dots here are just another character 15366 // that can appear in a module name. Flatten down to the actual module name. 15367 std::string ModuleName; 15368 for (auto &Piece : Path) { 15369 if (!ModuleName.empty()) 15370 ModuleName += "."; 15371 ModuleName += Piece.first->getName(); 15372 } 15373 15374 // If a module name was explicitly specified on the command line, it must be 15375 // correct. 15376 if (!getLangOpts().CurrentModule.empty() && 15377 getLangOpts().CurrentModule != ModuleName) { 15378 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15379 << SourceRange(Path.front().second, Path.back().second) 15380 << getLangOpts().CurrentModule; 15381 return nullptr; 15382 } 15383 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15384 15385 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15386 15387 switch (MDK) { 15388 case ModuleDeclKind::Module: { 15389 // FIXME: Check we're not in a submodule. 15390 15391 // We can't have imported a definition of this module or parsed a module 15392 // map defining it already. 15393 if (auto *M = Map.findModule(ModuleName)) { 15394 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15395 if (M->DefinitionLoc.isValid()) 15396 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15397 else if (const auto *FE = M->getASTFile()) 15398 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15399 << FE->getName(); 15400 return nullptr; 15401 } 15402 15403 // Create a Module for the module that we're defining. 15404 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15405 assert(Mod && "module creation should not fail"); 15406 15407 // Enter the semantic scope of the module. 15408 ActOnModuleBegin(ModuleLoc, Mod); 15409 return nullptr; 15410 } 15411 15412 case ModuleDeclKind::Partition: 15413 // FIXME: Check we are in a submodule of the named module. 15414 return nullptr; 15415 15416 case ModuleDeclKind::Implementation: 15417 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15418 PP.getIdentifierInfo(ModuleName), Path[0].second); 15419 15420 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15421 if (Import.isInvalid()) 15422 return nullptr; 15423 return ConvertDeclToDeclGroup(Import.get()); 15424 } 15425 15426 llvm_unreachable("unexpected module decl kind"); 15427 } 15428 15429 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15430 SourceLocation ImportLoc, 15431 ModuleIdPath Path) { 15432 Module *Mod = 15433 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15434 /*IsIncludeDirective=*/false); 15435 if (!Mod) 15436 return true; 15437 15438 VisibleModules.setVisible(Mod, ImportLoc); 15439 15440 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15441 15442 // FIXME: we should support importing a submodule within a different submodule 15443 // of the same top-level module. Until we do, make it an error rather than 15444 // silently ignoring the import. 15445 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15446 // warn on a redundant import of the current module? 15447 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15448 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15449 Diag(ImportLoc, getLangOpts().isCompilingModule() 15450 ? diag::err_module_self_import 15451 : diag::err_module_import_in_implementation) 15452 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15453 15454 SmallVector<SourceLocation, 2> IdentifierLocs; 15455 Module *ModCheck = Mod; 15456 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15457 // If we've run out of module parents, just drop the remaining identifiers. 15458 // We need the length to be consistent. 15459 if (!ModCheck) 15460 break; 15461 ModCheck = ModCheck->Parent; 15462 15463 IdentifierLocs.push_back(Path[I].second); 15464 } 15465 15466 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15467 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15468 Mod, IdentifierLocs); 15469 if (!ModuleScopes.empty()) 15470 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 15471 TU->addDecl(Import); 15472 return Import; 15473 } 15474 15475 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15476 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15477 BuildModuleInclude(DirectiveLoc, Mod); 15478 } 15479 15480 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15481 // Determine whether we're in the #include buffer for a module. The #includes 15482 // in that buffer do not qualify as module imports; they're just an 15483 // implementation detail of us building the module. 15484 // 15485 // FIXME: Should we even get ActOnModuleInclude calls for those? 15486 bool IsInModuleIncludes = 15487 TUKind == TU_Module && 15488 getSourceManager().isWrittenInMainFile(DirectiveLoc); 15489 15490 bool ShouldAddImport = !IsInModuleIncludes; 15491 15492 // If this module import was due to an inclusion directive, create an 15493 // implicit import declaration to capture it in the AST. 15494 if (ShouldAddImport) { 15495 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15496 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15497 DirectiveLoc, Mod, 15498 DirectiveLoc); 15499 if (!ModuleScopes.empty()) 15500 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 15501 TU->addDecl(ImportD); 15502 Consumer.HandleImplicitImportDecl(ImportD); 15503 } 15504 15505 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 15506 VisibleModules.setVisible(Mod, DirectiveLoc); 15507 } 15508 15509 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 15510 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 15511 15512 ModuleScopes.push_back({}); 15513 ModuleScopes.back().Module = Mod; 15514 if (getLangOpts().ModulesLocalVisibility) 15515 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 15516 15517 VisibleModules.setVisible(Mod, DirectiveLoc); 15518 } 15519 15520 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) { 15521 checkModuleImportContext(*this, Mod, EofLoc, CurContext); 15522 15523 if (getLangOpts().ModulesLocalVisibility) { 15524 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 15525 // Leaving a module hides namespace names, so our visible namespace cache 15526 // is now out of date. 15527 VisibleNamespaceCache.clear(); 15528 } 15529 15530 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 15531 "left the wrong module scope"); 15532 ModuleScopes.pop_back(); 15533 15534 // We got to the end of processing a #include of a local module. Create an 15535 // ImportDecl as we would for an imported module. 15536 FileID File = getSourceManager().getFileID(EofLoc); 15537 assert(File != getSourceManager().getMainFileID() && 15538 "end of submodule in main source file"); 15539 SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File); 15540 BuildModuleInclude(DirectiveLoc, Mod); 15541 } 15542 15543 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 15544 Module *Mod) { 15545 // Bail if we're not allowed to implicitly import a module here. 15546 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 15547 return; 15548 15549 // Create the implicit import declaration. 15550 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15551 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15552 Loc, Mod, Loc); 15553 TU->addDecl(ImportD); 15554 Consumer.HandleImplicitImportDecl(ImportD); 15555 15556 // Make the module visible. 15557 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 15558 VisibleModules.setVisible(Mod, Loc); 15559 } 15560 15561 /// We have parsed the start of an export declaration, including the '{' 15562 /// (if present). 15563 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 15564 SourceLocation LBraceLoc) { 15565 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 15566 15567 // C++ Modules TS draft: 15568 // An export-declaration [...] shall not contain more than one 15569 // export keyword. 15570 // 15571 // The intent here is that an export-declaration cannot appear within another 15572 // export-declaration. 15573 if (D->isExported()) 15574 Diag(ExportLoc, diag::err_export_within_export); 15575 15576 CurContext->addDecl(D); 15577 PushDeclContext(S, D); 15578 return D; 15579 } 15580 15581 /// Complete the definition of an export declaration. 15582 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 15583 auto *ED = cast<ExportDecl>(D); 15584 if (RBraceLoc.isValid()) 15585 ED->setRBraceLoc(RBraceLoc); 15586 15587 // FIXME: Diagnose export of internal-linkage declaration (including 15588 // anonymous namespace). 15589 15590 PopDeclContext(); 15591 return D; 15592 } 15593 15594 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 15595 IdentifierInfo* AliasName, 15596 SourceLocation PragmaLoc, 15597 SourceLocation NameLoc, 15598 SourceLocation AliasNameLoc) { 15599 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 15600 LookupOrdinaryName); 15601 AsmLabelAttr *Attr = 15602 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 15603 15604 // If a declaration that: 15605 // 1) declares a function or a variable 15606 // 2) has external linkage 15607 // already exists, add a label attribute to it. 15608 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15609 if (isDeclExternC(PrevDecl)) 15610 PrevDecl->addAttr(Attr); 15611 else 15612 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 15613 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 15614 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 15615 } else 15616 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 15617 } 15618 15619 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 15620 SourceLocation PragmaLoc, 15621 SourceLocation NameLoc) { 15622 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 15623 15624 if (PrevDecl) { 15625 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 15626 } else { 15627 (void)WeakUndeclaredIdentifiers.insert( 15628 std::pair<IdentifierInfo*,WeakInfo> 15629 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 15630 } 15631 } 15632 15633 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 15634 IdentifierInfo* AliasName, 15635 SourceLocation PragmaLoc, 15636 SourceLocation NameLoc, 15637 SourceLocation AliasNameLoc) { 15638 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 15639 LookupOrdinaryName); 15640 WeakInfo W = WeakInfo(Name, NameLoc); 15641 15642 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15643 if (!PrevDecl->hasAttr<AliasAttr>()) 15644 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 15645 DeclApplyPragmaWeak(TUScope, ND, W); 15646 } else { 15647 (void)WeakUndeclaredIdentifiers.insert( 15648 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 15649 } 15650 } 15651 15652 Decl *Sema::getObjCDeclContext() const { 15653 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 15654 } 15655