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 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw__Float16: 136 case tok::kw___float128: 137 case tok::kw_wchar_t: 138 case tok::kw_bool: 139 case tok::kw___underlying_type: 140 case tok::kw___auto_type: 141 return true; 142 143 case tok::annot_typename: 144 case tok::kw_char16_t: 145 case tok::kw_char32_t: 146 case tok::kw_typeof: 147 case tok::annot_decltype: 148 case tok::kw_decltype: 149 return getLangOpts().CPlusPlus; 150 151 case tok::kw_char8_t: 152 return getLangOpts().Char8; 153 154 default: 155 break; 156 } 157 158 return false; 159 } 160 161 namespace { 162 enum class UnqualifiedTypeNameLookupResult { 163 NotFound, 164 FoundNonType, 165 FoundType 166 }; 167 } // end anonymous namespace 168 169 /// Tries to perform unqualified lookup of the type decls in bases for 170 /// dependent class. 171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 172 /// type decl, \a FoundType if only type decls are found. 173 static UnqualifiedTypeNameLookupResult 174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 175 SourceLocation NameLoc, 176 const CXXRecordDecl *RD) { 177 if (!RD->hasDefinition()) 178 return UnqualifiedTypeNameLookupResult::NotFound; 179 // Look for type decls in base classes. 180 UnqualifiedTypeNameLookupResult FoundTypeDecl = 181 UnqualifiedTypeNameLookupResult::NotFound; 182 for (const auto &Base : RD->bases()) { 183 const CXXRecordDecl *BaseRD = nullptr; 184 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 185 BaseRD = BaseTT->getAsCXXRecordDecl(); 186 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 187 // Look for type decls in dependent base classes that have known primary 188 // templates. 189 if (!TST || !TST->isDependentType()) 190 continue; 191 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 192 if (!TD) 193 continue; 194 if (auto *BasePrimaryTemplate = 195 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 196 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 197 BaseRD = BasePrimaryTemplate; 198 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 199 if (const ClassTemplatePartialSpecializationDecl *PS = 200 CTD->findPartialSpecialization(Base.getType())) 201 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 202 BaseRD = PS; 203 } 204 } 205 } 206 if (BaseRD) { 207 for (NamedDecl *ND : BaseRD->lookup(&II)) { 208 if (!isa<TypeDecl>(ND)) 209 return UnqualifiedTypeNameLookupResult::FoundNonType; 210 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 211 } 212 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 213 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 214 case UnqualifiedTypeNameLookupResult::FoundNonType: 215 return UnqualifiedTypeNameLookupResult::FoundNonType; 216 case UnqualifiedTypeNameLookupResult::FoundType: 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 break; 219 case UnqualifiedTypeNameLookupResult::NotFound: 220 break; 221 } 222 } 223 } 224 } 225 226 return FoundTypeDecl; 227 } 228 229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 230 const IdentifierInfo &II, 231 SourceLocation NameLoc) { 232 // Lookup in the parent class template context, if any. 233 const CXXRecordDecl *RD = nullptr; 234 UnqualifiedTypeNameLookupResult FoundTypeDecl = 235 UnqualifiedTypeNameLookupResult::NotFound; 236 for (DeclContext *DC = S.CurContext; 237 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 238 DC = DC->getParent()) { 239 // Look for type decls in dependent base classes that have known primary 240 // templates. 241 RD = dyn_cast<CXXRecordDecl>(DC); 242 if (RD && RD->getDescribedClassTemplate()) 243 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 244 } 245 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 246 return nullptr; 247 248 // We found some types in dependent base classes. Recover as if the user 249 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 250 // lookup during template instantiation. 251 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 252 253 ASTContext &Context = S.Context; 254 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 255 cast<Type>(Context.getRecordType(RD))); 256 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 257 258 CXXScopeSpec SS; 259 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 260 261 TypeLocBuilder Builder; 262 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 263 DepTL.setNameLoc(NameLoc); 264 DepTL.setElaboratedKeywordLoc(SourceLocation()); 265 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 266 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 267 } 268 269 /// If the identifier refers to a type name within this scope, 270 /// return the declaration of that type. 271 /// 272 /// This routine performs ordinary name lookup of the identifier II 273 /// within the given scope, with optional C++ scope specifier SS, to 274 /// determine whether the name refers to a type. If so, returns an 275 /// opaque pointer (actually a QualType) corresponding to that 276 /// type. Otherwise, returns NULL. 277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 278 Scope *S, CXXScopeSpec *SS, 279 bool isClassName, bool HasTrailingDot, 280 ParsedType ObjectTypePtr, 281 bool IsCtorOrDtorName, 282 bool WantNontrivialTypeSourceInfo, 283 bool IsClassTemplateDeductionContext, 284 IdentifierInfo **CorrectedII) { 285 // FIXME: Consider allowing this outside C++1z mode as an extension. 286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 287 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 288 !isClassName && !HasTrailingDot; 289 290 // Determine where we will perform name lookup. 291 DeclContext *LookupCtx = nullptr; 292 if (ObjectTypePtr) { 293 QualType ObjectType = ObjectTypePtr.get(); 294 if (ObjectType->isRecordType()) 295 LookupCtx = computeDeclContext(ObjectType); 296 } else if (SS && SS->isNotEmpty()) { 297 LookupCtx = computeDeclContext(*SS, false); 298 299 if (!LookupCtx) { 300 if (isDependentScopeSpecifier(*SS)) { 301 // C++ [temp.res]p3: 302 // A qualified-id that refers to a type and in which the 303 // nested-name-specifier depends on a template-parameter (14.6.2) 304 // shall be prefixed by the keyword typename to indicate that the 305 // qualified-id denotes a type, forming an 306 // elaborated-type-specifier (7.1.5.3). 307 // 308 // We therefore do not perform any name lookup if the result would 309 // refer to a member of an unknown specialization. 310 if (!isClassName && !IsCtorOrDtorName) 311 return nullptr; 312 313 // We know from the grammar that this name refers to a type, 314 // so build a dependent node to describe the type. 315 if (WantNontrivialTypeSourceInfo) 316 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 317 318 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 319 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 320 II, NameLoc); 321 return ParsedType::make(T); 322 } 323 324 return nullptr; 325 } 326 327 if (!LookupCtx->isDependentContext() && 328 RequireCompleteDeclContext(*SS, LookupCtx)) 329 return nullptr; 330 } 331 332 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 333 // lookup for class-names. 334 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 335 LookupOrdinaryName; 336 LookupResult Result(*this, &II, NameLoc, Kind); 337 if (LookupCtx) { 338 // Perform "qualified" name lookup into the declaration context we 339 // computed, which is either the type of the base of a member access 340 // expression or the declaration context associated with a prior 341 // nested-name-specifier. 342 LookupQualifiedName(Result, LookupCtx); 343 344 if (ObjectTypePtr && Result.empty()) { 345 // C++ [basic.lookup.classref]p3: 346 // If the unqualified-id is ~type-name, the type-name is looked up 347 // in the context of the entire postfix-expression. If the type T of 348 // the object expression is of a class type C, the type-name is also 349 // looked up in the scope of class C. At least one of the lookups shall 350 // find a name that refers to (possibly cv-qualified) T. 351 LookupName(Result, S); 352 } 353 } else { 354 // Perform unqualified name lookup. 355 LookupName(Result, S); 356 357 // For unqualified lookup in a class template in MSVC mode, look into 358 // dependent base classes where the primary class template is known. 359 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 360 if (ParsedType TypeInBase = 361 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 362 return TypeInBase; 363 } 364 } 365 366 NamedDecl *IIDecl = nullptr; 367 switch (Result.getResultKind()) { 368 case LookupResult::NotFound: 369 case LookupResult::NotFoundInCurrentInstantiation: 370 if (CorrectedII) { 371 TypoCorrection Correction = 372 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 373 llvm::make_unique<TypeNameValidatorCCC>( 374 true, isClassName, AllowDeducedTemplate), 375 CTK_ErrorRecovery); 376 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 377 TemplateTy Template; 378 bool MemberOfUnknownSpecialization; 379 UnqualifiedId TemplateName; 380 TemplateName.setIdentifier(NewII, NameLoc); 381 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 382 CXXScopeSpec NewSS, *NewSSPtr = SS; 383 if (SS && NNS) { 384 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 385 NewSSPtr = &NewSS; 386 } 387 if (Correction && (NNS || NewII != &II) && 388 // Ignore a correction to a template type as the to-be-corrected 389 // identifier is not a template (typo correction for template names 390 // is handled elsewhere). 391 !(getLangOpts().CPlusPlus && NewSSPtr && 392 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 393 Template, MemberOfUnknownSpecialization))) { 394 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 395 isClassName, HasTrailingDot, ObjectTypePtr, 396 IsCtorOrDtorName, 397 WantNontrivialTypeSourceInfo, 398 IsClassTemplateDeductionContext); 399 if (Ty) { 400 diagnoseTypo(Correction, 401 PDiag(diag::err_unknown_type_or_class_name_suggest) 402 << Result.getLookupName() << isClassName); 403 if (SS && NNS) 404 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 405 *CorrectedII = NewII; 406 return Ty; 407 } 408 } 409 } 410 // If typo correction failed or was not performed, fall through 411 LLVM_FALLTHROUGH; 412 case LookupResult::FoundOverloaded: 413 case LookupResult::FoundUnresolvedValue: 414 Result.suppressDiagnostics(); 415 return nullptr; 416 417 case LookupResult::Ambiguous: 418 // Recover from type-hiding ambiguities by hiding the type. We'll 419 // do the lookup again when looking for an object, and we can 420 // diagnose the error then. If we don't do this, then the error 421 // about hiding the type will be immediately followed by an error 422 // that only makes sense if the identifier was treated like a type. 423 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 424 Result.suppressDiagnostics(); 425 return nullptr; 426 } 427 428 // Look to see if we have a type anywhere in the list of results. 429 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 430 Res != ResEnd; ++Res) { 431 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 432 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 433 if (!IIDecl || 434 (*Res)->getLocation().getRawEncoding() < 435 IIDecl->getLocation().getRawEncoding()) 436 IIDecl = *Res; 437 } 438 } 439 440 if (!IIDecl) { 441 // None of the entities we found is a type, so there is no way 442 // to even assume that the result is a type. In this case, don't 443 // complain about the ambiguity. The parser will either try to 444 // perform this lookup again (e.g., as an object name), which 445 // will produce the ambiguity, or will complain that it expected 446 // a type name. 447 Result.suppressDiagnostics(); 448 return nullptr; 449 } 450 451 // We found a type within the ambiguous lookup; diagnose the 452 // ambiguity and then return that type. This might be the right 453 // answer, or it might not be, but it suppresses any attempt to 454 // perform the name lookup again. 455 break; 456 457 case LookupResult::Found: 458 IIDecl = Result.getFoundDecl(); 459 break; 460 } 461 462 assert(IIDecl && "Didn't find decl"); 463 464 QualType T; 465 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 466 // C++ [class.qual]p2: A lookup that would find the injected-class-name 467 // instead names the constructors of the class, except when naming a class. 468 // This is ill-formed when we're not actually forming a ctor or dtor name. 469 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 470 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 471 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 472 FoundRD->isInjectedClassName() && 473 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 474 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 475 << &II << /*Type*/1; 476 477 DiagnoseUseOfDecl(IIDecl, NameLoc); 478 479 T = Context.getTypeDeclType(TD); 480 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 481 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 482 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 483 if (!HasTrailingDot) 484 T = Context.getObjCInterfaceType(IDecl); 485 } else if (AllowDeducedTemplate) { 486 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 487 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 488 QualType(), false); 489 } 490 491 if (T.isNull()) { 492 // If it's not plausibly a type, suppress diagnostics. 493 Result.suppressDiagnostics(); 494 return nullptr; 495 } 496 497 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 498 // constructor or destructor name (in such a case, the scope specifier 499 // will be attached to the enclosing Expr or Decl node). 500 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 501 !isa<ObjCInterfaceDecl>(IIDecl)) { 502 if (WantNontrivialTypeSourceInfo) { 503 // Construct a type with type-source information. 504 TypeLocBuilder Builder; 505 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 506 507 T = getElaboratedType(ETK_None, *SS, T); 508 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 509 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 510 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 511 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 512 } else { 513 T = getElaboratedType(ETK_None, *SS, T); 514 } 515 } 516 517 return ParsedType::make(T); 518 } 519 520 // Builds a fake NNS for the given decl context. 521 static NestedNameSpecifier * 522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 523 for (;; DC = DC->getLookupParent()) { 524 DC = DC->getPrimaryContext(); 525 auto *ND = dyn_cast<NamespaceDecl>(DC); 526 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 527 return NestedNameSpecifier::Create(Context, nullptr, ND); 528 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 529 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 530 RD->getTypeForDecl()); 531 else if (isa<TranslationUnitDecl>(DC)) 532 return NestedNameSpecifier::GlobalSpecifier(Context); 533 } 534 llvm_unreachable("something isn't in TU scope?"); 535 } 536 537 /// Find the parent class with dependent bases of the innermost enclosing method 538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 539 /// up allowing unqualified dependent type names at class-level, which MSVC 540 /// correctly rejects. 541 static const CXXRecordDecl * 542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 543 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 544 DC = DC->getPrimaryContext(); 545 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 546 if (MD->getParent()->hasAnyDependentBases()) 547 return MD->getParent(); 548 } 549 return nullptr; 550 } 551 552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 553 SourceLocation NameLoc, 554 bool IsTemplateTypeArg) { 555 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 556 557 NestedNameSpecifier *NNS = nullptr; 558 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 559 // If we weren't able to parse a default template argument, delay lookup 560 // until instantiation time by making a non-dependent DependentTypeName. We 561 // pretend we saw a NestedNameSpecifier referring to the current scope, and 562 // lookup is retried. 563 // FIXME: This hurts our diagnostic quality, since we get errors like "no 564 // type named 'Foo' in 'current_namespace'" when the user didn't write any 565 // name specifiers. 566 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 567 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 568 } else if (const CXXRecordDecl *RD = 569 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 570 // Build a DependentNameType that will perform lookup into RD at 571 // instantiation time. 572 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 573 RD->getTypeForDecl()); 574 575 // Diagnose that this identifier was undeclared, and retry the lookup during 576 // template instantiation. 577 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 578 << RD; 579 } else { 580 // This is not a situation that we should recover from. 581 return ParsedType(); 582 } 583 584 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 585 586 // Build type location information. We synthesized the qualifier, so we have 587 // to build a fake NestedNameSpecifierLoc. 588 NestedNameSpecifierLocBuilder NNSLocBuilder; 589 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 590 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 591 592 TypeLocBuilder Builder; 593 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 594 DepTL.setNameLoc(NameLoc); 595 DepTL.setElaboratedKeywordLoc(SourceLocation()); 596 DepTL.setQualifierLoc(QualifierLoc); 597 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 598 } 599 600 /// isTagName() - This method is called *for error recovery purposes only* 601 /// to determine if the specified name is a valid tag name ("struct foo"). If 602 /// so, this returns the TST for the tag corresponding to it (TST_enum, 603 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 604 /// cases in C where the user forgot to specify the tag. 605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 606 // Do a tag name lookup in this scope. 607 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 608 LookupName(R, S, false); 609 R.suppressDiagnostics(); 610 if (R.getResultKind() == LookupResult::Found) 611 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 612 switch (TD->getTagKind()) { 613 case TTK_Struct: return DeclSpec::TST_struct; 614 case TTK_Interface: return DeclSpec::TST_interface; 615 case TTK_Union: return DeclSpec::TST_union; 616 case TTK_Class: return DeclSpec::TST_class; 617 case TTK_Enum: return DeclSpec::TST_enum; 618 } 619 } 620 621 return DeclSpec::TST_unspecified; 622 } 623 624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 626 /// then downgrade the missing typename error to a warning. 627 /// This is needed for MSVC compatibility; Example: 628 /// @code 629 /// template<class T> class A { 630 /// public: 631 /// typedef int TYPE; 632 /// }; 633 /// template<class T> class B : public A<T> { 634 /// public: 635 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 636 /// }; 637 /// @endcode 638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 639 if (CurContext->isRecord()) { 640 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 641 return true; 642 643 const Type *Ty = SS->getScopeRep()->getAsType(); 644 645 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 646 for (const auto &Base : RD->bases()) 647 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 648 return true; 649 return S->isFunctionPrototypeScope(); 650 } 651 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 652 } 653 654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 655 SourceLocation IILoc, 656 Scope *S, 657 CXXScopeSpec *SS, 658 ParsedType &SuggestedType, 659 bool IsTemplateName) { 660 // Don't report typename errors for editor placeholders. 661 if (II->isEditorPlaceholder()) 662 return; 663 // We don't have anything to suggest (yet). 664 SuggestedType = nullptr; 665 666 // There may have been a typo in the name of the type. Look up typo 667 // results, in case we have something that we can suggest. 668 if (TypoCorrection Corrected = 669 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 670 llvm::make_unique<TypeNameValidatorCCC>( 671 false, false, IsTemplateName, !IsTemplateName), 672 CTK_ErrorRecovery)) { 673 // FIXME: Support error recovery for the template-name case. 674 bool CanRecover = !IsTemplateName; 675 if (Corrected.isKeyword()) { 676 // We corrected to a keyword. 677 diagnoseTypo(Corrected, 678 PDiag(IsTemplateName ? diag::err_no_template_suggest 679 : diag::err_unknown_typename_suggest) 680 << II); 681 II = Corrected.getCorrectionAsIdentifierInfo(); 682 } else { 683 // We found a similarly-named type or interface; suggest that. 684 if (!SS || !SS->isSet()) { 685 diagnoseTypo(Corrected, 686 PDiag(IsTemplateName ? diag::err_no_template_suggest 687 : diag::err_unknown_typename_suggest) 688 << II, CanRecover); 689 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 690 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 691 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 692 II->getName().equals(CorrectedStr); 693 diagnoseTypo(Corrected, 694 PDiag(IsTemplateName 695 ? diag::err_no_member_template_suggest 696 : diag::err_unknown_nested_typename_suggest) 697 << II << DC << DroppedSpecifier << SS->getRange(), 698 CanRecover); 699 } else { 700 llvm_unreachable("could not have corrected a typo here"); 701 } 702 703 if (!CanRecover) 704 return; 705 706 CXXScopeSpec tmpSS; 707 if (Corrected.getCorrectionSpecifier()) 708 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 709 SourceRange(IILoc)); 710 // FIXME: Support class template argument deduction here. 711 SuggestedType = 712 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 713 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 714 /*IsCtorOrDtorName=*/false, 715 /*NonTrivialTypeSourceInfo=*/true); 716 } 717 return; 718 } 719 720 if (getLangOpts().CPlusPlus && !IsTemplateName) { 721 // See if II is a class template that the user forgot to pass arguments to. 722 UnqualifiedId Name; 723 Name.setIdentifier(II, IILoc); 724 CXXScopeSpec EmptySS; 725 TemplateTy TemplateResult; 726 bool MemberOfUnknownSpecialization; 727 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 728 Name, nullptr, true, TemplateResult, 729 MemberOfUnknownSpecialization) == TNK_Type_template) { 730 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 731 return; 732 } 733 } 734 735 // FIXME: Should we move the logic that tries to recover from a missing tag 736 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 737 738 if (!SS || (!SS->isSet() && !SS->isInvalid())) 739 Diag(IILoc, IsTemplateName ? diag::err_no_template 740 : diag::err_unknown_typename) 741 << II; 742 else if (DeclContext *DC = computeDeclContext(*SS, false)) 743 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 744 : diag::err_typename_nested_not_found) 745 << II << DC << SS->getRange(); 746 else if (isDependentScopeSpecifier(*SS)) { 747 unsigned DiagID = diag::err_typename_missing; 748 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 749 DiagID = diag::ext_typename_missing; 750 751 Diag(SS->getRange().getBegin(), DiagID) 752 << SS->getScopeRep() << II->getName() 753 << SourceRange(SS->getRange().getBegin(), IILoc) 754 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 755 SuggestedType = ActOnTypenameType(S, SourceLocation(), 756 *SS, *II, IILoc).get(); 757 } else { 758 assert(SS && SS->isInvalid() && 759 "Invalid scope specifier has already been diagnosed"); 760 } 761 } 762 763 /// Determine whether the given result set contains either a type name 764 /// or 765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 766 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 767 NextToken.is(tok::less); 768 769 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 770 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 771 return true; 772 773 if (CheckTemplate && isa<TemplateDecl>(*I)) 774 return true; 775 } 776 777 return false; 778 } 779 780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 781 Scope *S, CXXScopeSpec &SS, 782 IdentifierInfo *&Name, 783 SourceLocation NameLoc) { 784 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 785 SemaRef.LookupParsedName(R, S, &SS); 786 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 787 StringRef FixItTagName; 788 switch (Tag->getTagKind()) { 789 case TTK_Class: 790 FixItTagName = "class "; 791 break; 792 793 case TTK_Enum: 794 FixItTagName = "enum "; 795 break; 796 797 case TTK_Struct: 798 FixItTagName = "struct "; 799 break; 800 801 case TTK_Interface: 802 FixItTagName = "__interface "; 803 break; 804 805 case TTK_Union: 806 FixItTagName = "union "; 807 break; 808 } 809 810 StringRef TagName = FixItTagName.drop_back(); 811 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 812 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 813 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 814 815 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 816 I != IEnd; ++I) 817 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 818 << Name << TagName; 819 820 // Replace lookup results with just the tag decl. 821 Result.clear(Sema::LookupTagName); 822 SemaRef.LookupParsedName(Result, S, &SS); 823 return true; 824 } 825 826 return false; 827 } 828 829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 831 QualType T, SourceLocation NameLoc) { 832 ASTContext &Context = S.Context; 833 834 TypeLocBuilder Builder; 835 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 836 837 T = S.getElaboratedType(ETK_None, SS, T); 838 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 839 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 840 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 841 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 842 } 843 844 Sema::NameClassification 845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 846 SourceLocation NameLoc, const Token &NextToken, 847 bool IsAddressOfOperand, 848 std::unique_ptr<CorrectionCandidateCallback> CCC) { 849 DeclarationNameInfo NameInfo(Name, NameLoc); 850 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 851 852 if (NextToken.is(tok::coloncolon)) { 853 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 854 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 855 } else if (getLangOpts().CPlusPlus && SS.isSet() && 856 isCurrentClassName(*Name, S, &SS)) { 857 // Per [class.qual]p2, this names the constructors of SS, not the 858 // injected-class-name. We don't have a classification for that. 859 // There's not much point caching this result, since the parser 860 // will reject it later. 861 return NameClassification::Unknown(); 862 } 863 864 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 865 LookupParsedName(Result, S, &SS, !CurMethod); 866 867 // For unqualified lookup in a class template in MSVC mode, look into 868 // dependent base classes where the primary class template is known. 869 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 870 if (ParsedType TypeInBase = 871 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 872 return TypeInBase; 873 } 874 875 // Perform lookup for Objective-C instance variables (including automatically 876 // synthesized instance variables), if we're in an Objective-C method. 877 // FIXME: This lookup really, really needs to be folded in to the normal 878 // unqualified lookup mechanism. 879 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 880 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 881 if (E.get() || E.isInvalid()) 882 return E; 883 } 884 885 bool SecondTry = false; 886 bool IsFilteredTemplateName = false; 887 888 Corrected: 889 switch (Result.getResultKind()) { 890 case LookupResult::NotFound: 891 // If an unqualified-id is followed by a '(', then we have a function 892 // call. 893 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 894 // In C++, this is an ADL-only call. 895 // FIXME: Reference? 896 if (getLangOpts().CPlusPlus) 897 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 898 899 // C90 6.3.2.2: 900 // If the expression that precedes the parenthesized argument list in a 901 // function call consists solely of an identifier, and if no 902 // declaration is visible for this identifier, the identifier is 903 // implicitly declared exactly as if, in the innermost block containing 904 // the function call, the declaration 905 // 906 // extern int identifier (); 907 // 908 // appeared. 909 // 910 // We also allow this in C99 as an extension. 911 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 912 Result.addDecl(D); 913 Result.resolveKind(); 914 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 915 } 916 } 917 918 // In C, we first see whether there is a tag type by the same name, in 919 // which case it's likely that the user just forgot to write "enum", 920 // "struct", or "union". 921 if (!getLangOpts().CPlusPlus && !SecondTry && 922 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 923 break; 924 } 925 926 // Perform typo correction to determine if there is another name that is 927 // close to this name. 928 if (!SecondTry && CCC) { 929 SecondTry = true; 930 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 931 Result.getLookupKind(), S, 932 &SS, std::move(CCC), 933 CTK_ErrorRecovery)) { 934 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 935 unsigned QualifiedDiag = diag::err_no_member_suggest; 936 937 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 938 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 939 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 940 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 941 UnqualifiedDiag = diag::err_no_template_suggest; 942 QualifiedDiag = diag::err_no_member_template_suggest; 943 } else if (UnderlyingFirstDecl && 944 (isa<TypeDecl>(UnderlyingFirstDecl) || 945 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 946 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 947 UnqualifiedDiag = diag::err_unknown_typename_suggest; 948 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 949 } 950 951 if (SS.isEmpty()) { 952 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 953 } else {// FIXME: is this even reachable? Test it. 954 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 955 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 956 Name->getName().equals(CorrectedStr); 957 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 958 << Name << computeDeclContext(SS, false) 959 << DroppedSpecifier << SS.getRange()); 960 } 961 962 // Update the name, so that the caller has the new name. 963 Name = Corrected.getCorrectionAsIdentifierInfo(); 964 965 // Typo correction corrected to a keyword. 966 if (Corrected.isKeyword()) 967 return Name; 968 969 // Also update the LookupResult... 970 // FIXME: This should probably go away at some point 971 Result.clear(); 972 Result.setLookupName(Corrected.getCorrection()); 973 if (FirstDecl) 974 Result.addDecl(FirstDecl); 975 976 // If we found an Objective-C instance variable, let 977 // LookupInObjCMethod build the appropriate expression to 978 // reference the ivar. 979 // FIXME: This is a gross hack. 980 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 981 Result.clear(); 982 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 983 return E; 984 } 985 986 goto Corrected; 987 } 988 } 989 990 // We failed to correct; just fall through and let the parser deal with it. 991 Result.suppressDiagnostics(); 992 return NameClassification::Unknown(); 993 994 case LookupResult::NotFoundInCurrentInstantiation: { 995 // We performed name lookup into the current instantiation, and there were 996 // dependent bases, so we treat this result the same way as any other 997 // dependent nested-name-specifier. 998 999 // C++ [temp.res]p2: 1000 // A name used in a template declaration or definition and that is 1001 // dependent on a template-parameter is assumed not to name a type 1002 // unless the applicable name lookup finds a type name or the name is 1003 // qualified by the keyword typename. 1004 // 1005 // FIXME: If the next token is '<', we might want to ask the parser to 1006 // perform some heroics to see if we actually have a 1007 // template-argument-list, which would indicate a missing 'template' 1008 // keyword here. 1009 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1010 NameInfo, IsAddressOfOperand, 1011 /*TemplateArgs=*/nullptr); 1012 } 1013 1014 case LookupResult::Found: 1015 case LookupResult::FoundOverloaded: 1016 case LookupResult::FoundUnresolvedValue: 1017 break; 1018 1019 case LookupResult::Ambiguous: 1020 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1021 hasAnyAcceptableTemplateNames(Result)) { 1022 // C++ [temp.local]p3: 1023 // A lookup that finds an injected-class-name (10.2) can result in an 1024 // ambiguity in certain cases (for example, if it is found in more than 1025 // one base class). If all of the injected-class-names that are found 1026 // refer to specializations of the same class template, and if the name 1027 // is followed by a template-argument-list, the reference refers to the 1028 // class template itself and not a specialization thereof, and is not 1029 // ambiguous. 1030 // 1031 // This filtering can make an ambiguous result into an unambiguous one, 1032 // so try again after filtering out template names. 1033 FilterAcceptableTemplateNames(Result); 1034 if (!Result.isAmbiguous()) { 1035 IsFilteredTemplateName = true; 1036 break; 1037 } 1038 } 1039 1040 // Diagnose the ambiguity and return an error. 1041 return NameClassification::Error(); 1042 } 1043 1044 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1045 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1046 // C++ [temp.names]p3: 1047 // After name lookup (3.4) finds that a name is a template-name or that 1048 // an operator-function-id or a literal- operator-id refers to a set of 1049 // overloaded functions any member of which is a function template if 1050 // this is followed by a <, the < is always taken as the delimiter of a 1051 // template-argument-list and never as the less-than operator. 1052 if (!IsFilteredTemplateName) 1053 FilterAcceptableTemplateNames(Result); 1054 1055 if (!Result.empty()) { 1056 bool IsFunctionTemplate; 1057 bool IsVarTemplate; 1058 TemplateName Template; 1059 if (Result.end() - Result.begin() > 1) { 1060 IsFunctionTemplate = true; 1061 Template = Context.getOverloadedTemplateName(Result.begin(), 1062 Result.end()); 1063 } else { 1064 TemplateDecl *TD 1065 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1066 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1067 IsVarTemplate = isa<VarTemplateDecl>(TD); 1068 1069 if (SS.isSet() && !SS.isInvalid()) 1070 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1071 /*TemplateKeyword=*/false, 1072 TD); 1073 else 1074 Template = TemplateName(TD); 1075 } 1076 1077 if (IsFunctionTemplate) { 1078 // Function templates always go through overload resolution, at which 1079 // point we'll perform the various checks (e.g., accessibility) we need 1080 // to based on which function we selected. 1081 Result.suppressDiagnostics(); 1082 1083 return NameClassification::FunctionTemplate(Template); 1084 } 1085 1086 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1087 : NameClassification::TypeTemplate(Template); 1088 } 1089 } 1090 1091 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1092 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1093 DiagnoseUseOfDecl(Type, NameLoc); 1094 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1095 QualType T = Context.getTypeDeclType(Type); 1096 if (SS.isNotEmpty()) 1097 return buildNestedType(*this, SS, T, NameLoc); 1098 return ParsedType::make(T); 1099 } 1100 1101 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1102 if (!Class) { 1103 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1104 if (ObjCCompatibleAliasDecl *Alias = 1105 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1106 Class = Alias->getClassInterface(); 1107 } 1108 1109 if (Class) { 1110 DiagnoseUseOfDecl(Class, NameLoc); 1111 1112 if (NextToken.is(tok::period)) { 1113 // Interface. <something> is parsed as a property reference expression. 1114 // Just return "unknown" as a fall-through for now. 1115 Result.suppressDiagnostics(); 1116 return NameClassification::Unknown(); 1117 } 1118 1119 QualType T = Context.getObjCInterfaceType(Class); 1120 return ParsedType::make(T); 1121 } 1122 1123 // We can have a type template here if we're classifying a template argument. 1124 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1125 !isa<VarTemplateDecl>(FirstDecl)) 1126 return NameClassification::TypeTemplate( 1127 TemplateName(cast<TemplateDecl>(FirstDecl))); 1128 1129 // Check for a tag type hidden by a non-type decl in a few cases where it 1130 // seems likely a type is wanted instead of the non-type that was found. 1131 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1132 if ((NextToken.is(tok::identifier) || 1133 (NextIsOp && 1134 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1135 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1136 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1137 DiagnoseUseOfDecl(Type, NameLoc); 1138 QualType T = Context.getTypeDeclType(Type); 1139 if (SS.isNotEmpty()) 1140 return buildNestedType(*this, SS, T, NameLoc); 1141 return ParsedType::make(T); 1142 } 1143 1144 if (FirstDecl->isCXXClassMember()) 1145 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1146 nullptr, S); 1147 1148 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1149 return BuildDeclarationNameExpr(SS, Result, ADL); 1150 } 1151 1152 Sema::TemplateNameKindForDiagnostics 1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1154 auto *TD = Name.getAsTemplateDecl(); 1155 if (!TD) 1156 return TemplateNameKindForDiagnostics::DependentTemplate; 1157 if (isa<ClassTemplateDecl>(TD)) 1158 return TemplateNameKindForDiagnostics::ClassTemplate; 1159 if (isa<FunctionTemplateDecl>(TD)) 1160 return TemplateNameKindForDiagnostics::FunctionTemplate; 1161 if (isa<VarTemplateDecl>(TD)) 1162 return TemplateNameKindForDiagnostics::VarTemplate; 1163 if (isa<TypeAliasTemplateDecl>(TD)) 1164 return TemplateNameKindForDiagnostics::AliasTemplate; 1165 if (isa<TemplateTemplateParmDecl>(TD)) 1166 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1167 return TemplateNameKindForDiagnostics::DependentTemplate; 1168 } 1169 1170 // Determines the context to return to after temporarily entering a 1171 // context. This depends in an unnecessarily complicated way on the 1172 // exact ordering of callbacks from the parser. 1173 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1174 1175 // Functions defined inline within classes aren't parsed until we've 1176 // finished parsing the top-level class, so the top-level class is 1177 // the context we'll need to return to. 1178 // A Lambda call operator whose parent is a class must not be treated 1179 // as an inline member function. A Lambda can be used legally 1180 // either as an in-class member initializer or a default argument. These 1181 // are parsed once the class has been marked complete and so the containing 1182 // context would be the nested class (when the lambda is defined in one); 1183 // If the class is not complete, then the lambda is being used in an 1184 // ill-formed fashion (such as to specify the width of a bit-field, or 1185 // in an array-bound) - in which case we still want to return the 1186 // lexically containing DC (which could be a nested class). 1187 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1188 DC = DC->getLexicalParent(); 1189 1190 // A function not defined within a class will always return to its 1191 // lexical context. 1192 if (!isa<CXXRecordDecl>(DC)) 1193 return DC; 1194 1195 // A C++ inline method/friend is parsed *after* the topmost class 1196 // it was declared in is fully parsed ("complete"); the topmost 1197 // class is the context we need to return to. 1198 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1199 DC = RD; 1200 1201 // Return the declaration context of the topmost class the inline method is 1202 // declared in. 1203 return DC; 1204 } 1205 1206 return DC->getLexicalParent(); 1207 } 1208 1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1210 assert(getContainingDC(DC) == CurContext && 1211 "The next DeclContext should be lexically contained in the current one."); 1212 CurContext = DC; 1213 S->setEntity(DC); 1214 } 1215 1216 void Sema::PopDeclContext() { 1217 assert(CurContext && "DeclContext imbalance!"); 1218 1219 CurContext = getContainingDC(CurContext); 1220 assert(CurContext && "Popped translation unit!"); 1221 } 1222 1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1224 Decl *D) { 1225 // Unlike PushDeclContext, the context to which we return is not necessarily 1226 // the containing DC of TD, because the new context will be some pre-existing 1227 // TagDecl definition instead of a fresh one. 1228 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1229 CurContext = cast<TagDecl>(D)->getDefinition(); 1230 assert(CurContext && "skipping definition of undefined tag"); 1231 // Start lookups from the parent of the current context; we don't want to look 1232 // into the pre-existing complete definition. 1233 S->setEntity(CurContext->getLookupParent()); 1234 return Result; 1235 } 1236 1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1238 CurContext = static_cast<decltype(CurContext)>(Context); 1239 } 1240 1241 /// EnterDeclaratorContext - Used when we must lookup names in the context 1242 /// of a declarator's nested name specifier. 1243 /// 1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1245 // C++0x [basic.lookup.unqual]p13: 1246 // A name used in the definition of a static data member of class 1247 // X (after the qualified-id of the static member) is looked up as 1248 // if the name was used in a member function of X. 1249 // C++0x [basic.lookup.unqual]p14: 1250 // If a variable member of a namespace is defined outside of the 1251 // scope of its namespace then any name used in the definition of 1252 // the variable member (after the declarator-id) is looked up as 1253 // if the definition of the variable member occurred in its 1254 // namespace. 1255 // Both of these imply that we should push a scope whose context 1256 // is the semantic context of the declaration. We can't use 1257 // PushDeclContext here because that context is not necessarily 1258 // lexically contained in the current context. Fortunately, 1259 // the containing scope should have the appropriate information. 1260 1261 assert(!S->getEntity() && "scope already has entity"); 1262 1263 #ifndef NDEBUG 1264 Scope *Ancestor = S->getParent(); 1265 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1266 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1267 #endif 1268 1269 CurContext = DC; 1270 S->setEntity(DC); 1271 } 1272 1273 void Sema::ExitDeclaratorContext(Scope *S) { 1274 assert(S->getEntity() == CurContext && "Context imbalance!"); 1275 1276 // Switch back to the lexical context. The safety of this is 1277 // enforced by an assert in EnterDeclaratorContext. 1278 Scope *Ancestor = S->getParent(); 1279 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1280 CurContext = Ancestor->getEntity(); 1281 1282 // We don't need to do anything with the scope, which is going to 1283 // disappear. 1284 } 1285 1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1287 // We assume that the caller has already called 1288 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1289 FunctionDecl *FD = D->getAsFunction(); 1290 if (!FD) 1291 return; 1292 1293 // Same implementation as PushDeclContext, but enters the context 1294 // from the lexical parent, rather than the top-level class. 1295 assert(CurContext == FD->getLexicalParent() && 1296 "The next DeclContext should be lexically contained in the current one."); 1297 CurContext = FD; 1298 S->setEntity(CurContext); 1299 1300 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1301 ParmVarDecl *Param = FD->getParamDecl(P); 1302 // If the parameter has an identifier, then add it to the scope 1303 if (Param->getIdentifier()) { 1304 S->AddDecl(Param); 1305 IdResolver.AddDecl(Param); 1306 } 1307 } 1308 } 1309 1310 void Sema::ActOnExitFunctionContext() { 1311 // Same implementation as PopDeclContext, but returns to the lexical parent, 1312 // rather than the top-level class. 1313 assert(CurContext && "DeclContext imbalance!"); 1314 CurContext = CurContext->getLexicalParent(); 1315 assert(CurContext && "Popped translation unit!"); 1316 } 1317 1318 /// Determine whether we allow overloading of the function 1319 /// PrevDecl with another declaration. 1320 /// 1321 /// This routine determines whether overloading is possible, not 1322 /// whether some new function is actually an overload. It will return 1323 /// true in C++ (where we can always provide overloads) or, as an 1324 /// extension, in C when the previous function is already an 1325 /// overloaded function declaration or has the "overloadable" 1326 /// attribute. 1327 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1328 ASTContext &Context, 1329 const FunctionDecl *New) { 1330 if (Context.getLangOpts().CPlusPlus) 1331 return true; 1332 1333 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1334 return true; 1335 1336 return Previous.getResultKind() == LookupResult::Found && 1337 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1338 New->hasAttr<OverloadableAttr>()); 1339 } 1340 1341 /// Add this decl to the scope shadowed decl chains. 1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1343 // Move up the scope chain until we find the nearest enclosing 1344 // non-transparent context. The declaration will be introduced into this 1345 // scope. 1346 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1347 S = S->getParent(); 1348 1349 // Add scoped declarations into their context, so that they can be 1350 // found later. Declarations without a context won't be inserted 1351 // into any context. 1352 if (AddToContext) 1353 CurContext->addDecl(D); 1354 1355 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1356 // are function-local declarations. 1357 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1358 !D->getDeclContext()->getRedeclContext()->Equals( 1359 D->getLexicalDeclContext()->getRedeclContext()) && 1360 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1361 return; 1362 1363 // Template instantiations should also not be pushed into scope. 1364 if (isa<FunctionDecl>(D) && 1365 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1366 return; 1367 1368 // If this replaces anything in the current scope, 1369 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1370 IEnd = IdResolver.end(); 1371 for (; I != IEnd; ++I) { 1372 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1373 S->RemoveDecl(*I); 1374 IdResolver.RemoveDecl(*I); 1375 1376 // Should only need to replace one decl. 1377 break; 1378 } 1379 } 1380 1381 S->AddDecl(D); 1382 1383 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1384 // Implicitly-generated labels may end up getting generated in an order that 1385 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1386 // the label at the appropriate place in the identifier chain. 1387 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1388 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1389 if (IDC == CurContext) { 1390 if (!S->isDeclScope(*I)) 1391 continue; 1392 } else if (IDC->Encloses(CurContext)) 1393 break; 1394 } 1395 1396 IdResolver.InsertDeclAfter(I, D); 1397 } else { 1398 IdResolver.AddDecl(D); 1399 } 1400 } 1401 1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1403 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1404 TUScope->AddDecl(D); 1405 } 1406 1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1408 bool AllowInlineNamespace) { 1409 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1410 } 1411 1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1413 DeclContext *TargetDC = DC->getPrimaryContext(); 1414 do { 1415 if (DeclContext *ScopeDC = S->getEntity()) 1416 if (ScopeDC->getPrimaryContext() == TargetDC) 1417 return S; 1418 } while ((S = S->getParent())); 1419 1420 return nullptr; 1421 } 1422 1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1424 DeclContext*, 1425 ASTContext&); 1426 1427 /// Filters out lookup results that don't fall within the given scope 1428 /// as determined by isDeclInScope. 1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1430 bool ConsiderLinkage, 1431 bool AllowInlineNamespace) { 1432 LookupResult::Filter F = R.makeFilter(); 1433 while (F.hasNext()) { 1434 NamedDecl *D = F.next(); 1435 1436 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1437 continue; 1438 1439 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1440 continue; 1441 1442 F.erase(); 1443 } 1444 1445 F.done(); 1446 } 1447 1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1449 /// have compatible owning modules. 1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1451 // FIXME: The Modules TS is not clear about how friend declarations are 1452 // to be treated. It's not meaningful to have different owning modules for 1453 // linkage in redeclarations of the same entity, so for now allow the 1454 // redeclaration and change the owning modules to match. 1455 if (New->getFriendObjectKind() && 1456 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1457 New->setLocalOwningModule(Old->getOwningModule()); 1458 makeMergedDefinitionVisible(New); 1459 return false; 1460 } 1461 1462 Module *NewM = New->getOwningModule(); 1463 Module *OldM = Old->getOwningModule(); 1464 if (NewM == OldM) 1465 return false; 1466 1467 // FIXME: Check proclaimed-ownership-declarations here too. 1468 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit; 1469 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit; 1470 if (NewIsModuleInterface || OldIsModuleInterface) { 1471 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1472 // if a declaration of D [...] appears in the purview of a module, all 1473 // other such declarations shall appear in the purview of the same module 1474 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1475 << New 1476 << NewIsModuleInterface 1477 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1478 << OldIsModuleInterface 1479 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1480 Diag(Old->getLocation(), diag::note_previous_declaration); 1481 New->setInvalidDecl(); 1482 return true; 1483 } 1484 1485 return false; 1486 } 1487 1488 static bool isUsingDecl(NamedDecl *D) { 1489 return isa<UsingShadowDecl>(D) || 1490 isa<UnresolvedUsingTypenameDecl>(D) || 1491 isa<UnresolvedUsingValueDecl>(D); 1492 } 1493 1494 /// Removes using shadow declarations from the lookup results. 1495 static void RemoveUsingDecls(LookupResult &R) { 1496 LookupResult::Filter F = R.makeFilter(); 1497 while (F.hasNext()) 1498 if (isUsingDecl(F.next())) 1499 F.erase(); 1500 1501 F.done(); 1502 } 1503 1504 /// Check for this common pattern: 1505 /// @code 1506 /// class S { 1507 /// S(const S&); // DO NOT IMPLEMENT 1508 /// void operator=(const S&); // DO NOT IMPLEMENT 1509 /// }; 1510 /// @endcode 1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1512 // FIXME: Should check for private access too but access is set after we get 1513 // the decl here. 1514 if (D->doesThisDeclarationHaveABody()) 1515 return false; 1516 1517 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1518 return CD->isCopyConstructor(); 1519 return D->isCopyAssignmentOperator(); 1520 } 1521 1522 // We need this to handle 1523 // 1524 // typedef struct { 1525 // void *foo() { return 0; } 1526 // } A; 1527 // 1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1529 // for example. If 'A', foo will have external linkage. If we have '*A', 1530 // foo will have no linkage. Since we can't know until we get to the end 1531 // of the typedef, this function finds out if D might have non-external linkage. 1532 // Callers should verify at the end of the TU if it D has external linkage or 1533 // not. 1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1535 const DeclContext *DC = D->getDeclContext(); 1536 while (!DC->isTranslationUnit()) { 1537 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1538 if (!RD->hasNameForLinkage()) 1539 return true; 1540 } 1541 DC = DC->getParent(); 1542 } 1543 1544 return !D->isExternallyVisible(); 1545 } 1546 1547 // FIXME: This needs to be refactored; some other isInMainFile users want 1548 // these semantics. 1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1550 if (S.TUKind != TU_Complete) 1551 return false; 1552 return S.SourceMgr.isInMainFile(Loc); 1553 } 1554 1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1556 assert(D); 1557 1558 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1559 return false; 1560 1561 // Ignore all entities declared within templates, and out-of-line definitions 1562 // of members of class templates. 1563 if (D->getDeclContext()->isDependentContext() || 1564 D->getLexicalDeclContext()->isDependentContext()) 1565 return false; 1566 1567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1568 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1569 return false; 1570 // A non-out-of-line declaration of a member specialization was implicitly 1571 // instantiated; it's the out-of-line declaration that we're interested in. 1572 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1573 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1574 return false; 1575 1576 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1577 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1578 return false; 1579 } else { 1580 // 'static inline' functions are defined in headers; don't warn. 1581 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1582 return false; 1583 } 1584 1585 if (FD->doesThisDeclarationHaveABody() && 1586 Context.DeclMustBeEmitted(FD)) 1587 return false; 1588 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1589 // Constants and utility variables are defined in headers with internal 1590 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1591 // like "inline".) 1592 if (!isMainFileLoc(*this, VD->getLocation())) 1593 return false; 1594 1595 if (Context.DeclMustBeEmitted(VD)) 1596 return false; 1597 1598 if (VD->isStaticDataMember() && 1599 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1600 return false; 1601 if (VD->isStaticDataMember() && 1602 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1603 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1604 return false; 1605 1606 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1607 return false; 1608 } else { 1609 return false; 1610 } 1611 1612 // Only warn for unused decls internal to the translation unit. 1613 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1614 // for inline functions defined in the main source file, for instance. 1615 return mightHaveNonExternalLinkage(D); 1616 } 1617 1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1619 if (!D) 1620 return; 1621 1622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1623 const FunctionDecl *First = FD->getFirstDecl(); 1624 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1625 return; // First should already be in the vector. 1626 } 1627 1628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1629 const VarDecl *First = VD->getFirstDecl(); 1630 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1631 return; // First should already be in the vector. 1632 } 1633 1634 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1635 UnusedFileScopedDecls.push_back(D); 1636 } 1637 1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1639 if (D->isInvalidDecl()) 1640 return false; 1641 1642 bool Referenced = false; 1643 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1644 // For a decomposition declaration, warn if none of the bindings are 1645 // referenced, instead of if the variable itself is referenced (which 1646 // it is, by the bindings' expressions). 1647 for (auto *BD : DD->bindings()) { 1648 if (BD->isReferenced()) { 1649 Referenced = true; 1650 break; 1651 } 1652 } 1653 } else if (!D->getDeclName()) { 1654 return false; 1655 } else if (D->isReferenced() || D->isUsed()) { 1656 Referenced = true; 1657 } 1658 1659 if (Referenced || D->hasAttr<UnusedAttr>() || 1660 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1661 return false; 1662 1663 if (isa<LabelDecl>(D)) 1664 return true; 1665 1666 // Except for labels, we only care about unused decls that are local to 1667 // functions. 1668 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1669 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1670 // For dependent types, the diagnostic is deferred. 1671 WithinFunction = 1672 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1673 if (!WithinFunction) 1674 return false; 1675 1676 if (isa<TypedefNameDecl>(D)) 1677 return true; 1678 1679 // White-list anything that isn't a local variable. 1680 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1681 return false; 1682 1683 // Types of valid local variables should be complete, so this should succeed. 1684 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1685 1686 // White-list anything with an __attribute__((unused)) type. 1687 const auto *Ty = VD->getType().getTypePtr(); 1688 1689 // Only look at the outermost level of typedef. 1690 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1691 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1692 return false; 1693 } 1694 1695 // If we failed to complete the type for some reason, or if the type is 1696 // dependent, don't diagnose the variable. 1697 if (Ty->isIncompleteType() || Ty->isDependentType()) 1698 return false; 1699 1700 // Look at the element type to ensure that the warning behaviour is 1701 // consistent for both scalars and arrays. 1702 Ty = Ty->getBaseElementTypeUnsafe(); 1703 1704 if (const TagType *TT = Ty->getAs<TagType>()) { 1705 const TagDecl *Tag = TT->getDecl(); 1706 if (Tag->hasAttr<UnusedAttr>()) 1707 return false; 1708 1709 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1710 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1711 return false; 1712 1713 if (const Expr *Init = VD->getInit()) { 1714 if (const ExprWithCleanups *Cleanups = 1715 dyn_cast<ExprWithCleanups>(Init)) 1716 Init = Cleanups->getSubExpr(); 1717 const CXXConstructExpr *Construct = 1718 dyn_cast<CXXConstructExpr>(Init); 1719 if (Construct && !Construct->isElidable()) { 1720 CXXConstructorDecl *CD = Construct->getConstructor(); 1721 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1722 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1723 return false; 1724 } 1725 } 1726 } 1727 } 1728 1729 // TODO: __attribute__((unused)) templates? 1730 } 1731 1732 return true; 1733 } 1734 1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1736 FixItHint &Hint) { 1737 if (isa<LabelDecl>(D)) { 1738 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1739 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1740 if (AfterColon.isInvalid()) 1741 return; 1742 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1743 getCharRange(D->getLocStart(), AfterColon)); 1744 } 1745 } 1746 1747 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1748 if (D->getTypeForDecl()->isDependentType()) 1749 return; 1750 1751 for (auto *TmpD : D->decls()) { 1752 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1753 DiagnoseUnusedDecl(T); 1754 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1755 DiagnoseUnusedNestedTypedefs(R); 1756 } 1757 } 1758 1759 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1760 /// unless they are marked attr(unused). 1761 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1762 if (!ShouldDiagnoseUnusedDecl(D)) 1763 return; 1764 1765 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1766 // typedefs can be referenced later on, so the diagnostics are emitted 1767 // at end-of-translation-unit. 1768 UnusedLocalTypedefNameCandidates.insert(TD); 1769 return; 1770 } 1771 1772 FixItHint Hint; 1773 GenerateFixForUnusedDecl(D, Context, Hint); 1774 1775 unsigned DiagID; 1776 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1777 DiagID = diag::warn_unused_exception_param; 1778 else if (isa<LabelDecl>(D)) 1779 DiagID = diag::warn_unused_label; 1780 else 1781 DiagID = diag::warn_unused_variable; 1782 1783 Diag(D->getLocation(), DiagID) << D << Hint; 1784 } 1785 1786 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1787 // Verify that we have no forward references left. If so, there was a goto 1788 // or address of a label taken, but no definition of it. Label fwd 1789 // definitions are indicated with a null substmt which is also not a resolved 1790 // MS inline assembly label name. 1791 bool Diagnose = false; 1792 if (L->isMSAsmLabel()) 1793 Diagnose = !L->isResolvedMSAsmLabel(); 1794 else 1795 Diagnose = L->getStmt() == nullptr; 1796 if (Diagnose) 1797 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1798 } 1799 1800 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1801 S->mergeNRVOIntoParent(); 1802 1803 if (S->decl_empty()) return; 1804 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1805 "Scope shouldn't contain decls!"); 1806 1807 for (auto *TmpD : S->decls()) { 1808 assert(TmpD && "This decl didn't get pushed??"); 1809 1810 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1811 NamedDecl *D = cast<NamedDecl>(TmpD); 1812 1813 // Diagnose unused variables in this scope. 1814 if (!S->hasUnrecoverableErrorOccurred()) { 1815 DiagnoseUnusedDecl(D); 1816 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1817 DiagnoseUnusedNestedTypedefs(RD); 1818 } 1819 1820 if (!D->getDeclName()) continue; 1821 1822 // If this was a forward reference to a label, verify it was defined. 1823 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1824 CheckPoppedLabel(LD, *this); 1825 1826 // Remove this name from our lexical scope, and warn on it if we haven't 1827 // already. 1828 IdResolver.RemoveDecl(D); 1829 auto ShadowI = ShadowingDecls.find(D); 1830 if (ShadowI != ShadowingDecls.end()) { 1831 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1832 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1833 << D << FD << FD->getParent(); 1834 Diag(FD->getLocation(), diag::note_previous_declaration); 1835 } 1836 ShadowingDecls.erase(ShadowI); 1837 } 1838 } 1839 } 1840 1841 /// Look for an Objective-C class in the translation unit. 1842 /// 1843 /// \param Id The name of the Objective-C class we're looking for. If 1844 /// typo-correction fixes this name, the Id will be updated 1845 /// to the fixed name. 1846 /// 1847 /// \param IdLoc The location of the name in the translation unit. 1848 /// 1849 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1850 /// if there is no class with the given name. 1851 /// 1852 /// \returns The declaration of the named Objective-C class, or NULL if the 1853 /// class could not be found. 1854 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1855 SourceLocation IdLoc, 1856 bool DoTypoCorrection) { 1857 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1858 // creation from this context. 1859 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1860 1861 if (!IDecl && DoTypoCorrection) { 1862 // Perform typo correction at the given location, but only if we 1863 // find an Objective-C class name. 1864 if (TypoCorrection C = CorrectTypo( 1865 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1866 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1867 CTK_ErrorRecovery)) { 1868 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1869 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1870 Id = IDecl->getIdentifier(); 1871 } 1872 } 1873 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1874 // This routine must always return a class definition, if any. 1875 if (Def && Def->getDefinition()) 1876 Def = Def->getDefinition(); 1877 return Def; 1878 } 1879 1880 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1881 /// from S, where a non-field would be declared. This routine copes 1882 /// with the difference between C and C++ scoping rules in structs and 1883 /// unions. For example, the following code is well-formed in C but 1884 /// ill-formed in C++: 1885 /// @code 1886 /// struct S6 { 1887 /// enum { BAR } e; 1888 /// }; 1889 /// 1890 /// void test_S6() { 1891 /// struct S6 a; 1892 /// a.e = BAR; 1893 /// } 1894 /// @endcode 1895 /// For the declaration of BAR, this routine will return a different 1896 /// scope. The scope S will be the scope of the unnamed enumeration 1897 /// within S6. In C++, this routine will return the scope associated 1898 /// with S6, because the enumeration's scope is a transparent 1899 /// context but structures can contain non-field names. In C, this 1900 /// routine will return the translation unit scope, since the 1901 /// enumeration's scope is a transparent context and structures cannot 1902 /// contain non-field names. 1903 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1904 while (((S->getFlags() & Scope::DeclScope) == 0) || 1905 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1906 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1907 S = S->getParent(); 1908 return S; 1909 } 1910 1911 /// Looks up the declaration of "struct objc_super" and 1912 /// saves it for later use in building builtin declaration of 1913 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1914 /// pre-existing declaration exists no action takes place. 1915 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1916 IdentifierInfo *II) { 1917 if (!II->isStr("objc_msgSendSuper")) 1918 return; 1919 ASTContext &Context = ThisSema.Context; 1920 1921 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1922 SourceLocation(), Sema::LookupTagName); 1923 ThisSema.LookupName(Result, S); 1924 if (Result.getResultKind() == LookupResult::Found) 1925 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1926 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1927 } 1928 1929 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1930 switch (Error) { 1931 case ASTContext::GE_None: 1932 return ""; 1933 case ASTContext::GE_Missing_stdio: 1934 return "stdio.h"; 1935 case ASTContext::GE_Missing_setjmp: 1936 return "setjmp.h"; 1937 case ASTContext::GE_Missing_ucontext: 1938 return "ucontext.h"; 1939 } 1940 llvm_unreachable("unhandled error kind"); 1941 } 1942 1943 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1944 /// file scope. lazily create a decl for it. ForRedeclaration is true 1945 /// if we're creating this built-in in anticipation of redeclaring the 1946 /// built-in. 1947 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1948 Scope *S, bool ForRedeclaration, 1949 SourceLocation Loc) { 1950 LookupPredefedObjCSuperType(*this, S, II); 1951 1952 ASTContext::GetBuiltinTypeError Error; 1953 QualType R = Context.GetBuiltinType(ID, Error); 1954 if (Error) { 1955 if (ForRedeclaration) 1956 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1957 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1958 return nullptr; 1959 } 1960 1961 if (!ForRedeclaration && 1962 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1963 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1964 Diag(Loc, diag::ext_implicit_lib_function_decl) 1965 << Context.BuiltinInfo.getName(ID) << R; 1966 if (Context.BuiltinInfo.getHeaderName(ID) && 1967 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1968 Diag(Loc, diag::note_include_header_or_declare) 1969 << Context.BuiltinInfo.getHeaderName(ID) 1970 << Context.BuiltinInfo.getName(ID); 1971 } 1972 1973 if (R.isNull()) 1974 return nullptr; 1975 1976 DeclContext *Parent = Context.getTranslationUnitDecl(); 1977 if (getLangOpts().CPlusPlus) { 1978 LinkageSpecDecl *CLinkageDecl = 1979 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1980 LinkageSpecDecl::lang_c, false); 1981 CLinkageDecl->setImplicit(); 1982 Parent->addDecl(CLinkageDecl); 1983 Parent = CLinkageDecl; 1984 } 1985 1986 FunctionDecl *New = FunctionDecl::Create(Context, 1987 Parent, 1988 Loc, Loc, II, R, /*TInfo=*/nullptr, 1989 SC_Extern, 1990 false, 1991 R->isFunctionProtoType()); 1992 New->setImplicit(); 1993 1994 // Create Decl objects for each parameter, adding them to the 1995 // FunctionDecl. 1996 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1997 SmallVector<ParmVarDecl*, 16> Params; 1998 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1999 ParmVarDecl *parm = 2000 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2001 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2002 SC_None, nullptr); 2003 parm->setScopeInfo(0, i); 2004 Params.push_back(parm); 2005 } 2006 New->setParams(Params); 2007 } 2008 2009 AddKnownFunctionAttributes(New); 2010 RegisterLocallyScopedExternCDecl(New, S); 2011 2012 // TUScope is the translation-unit scope to insert this function into. 2013 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2014 // relate Scopes to DeclContexts, and probably eliminate CurContext 2015 // entirely, but we're not there yet. 2016 DeclContext *SavedContext = CurContext; 2017 CurContext = Parent; 2018 PushOnScopeChains(New, TUScope); 2019 CurContext = SavedContext; 2020 return New; 2021 } 2022 2023 /// Typedef declarations don't have linkage, but they still denote the same 2024 /// entity if their types are the same. 2025 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2026 /// isSameEntity. 2027 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2028 TypedefNameDecl *Decl, 2029 LookupResult &Previous) { 2030 // This is only interesting when modules are enabled. 2031 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2032 return; 2033 2034 // Empty sets are uninteresting. 2035 if (Previous.empty()) 2036 return; 2037 2038 LookupResult::Filter Filter = Previous.makeFilter(); 2039 while (Filter.hasNext()) { 2040 NamedDecl *Old = Filter.next(); 2041 2042 // Non-hidden declarations are never ignored. 2043 if (S.isVisible(Old)) 2044 continue; 2045 2046 // Declarations of the same entity are not ignored, even if they have 2047 // different linkages. 2048 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2049 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2050 Decl->getUnderlyingType())) 2051 continue; 2052 2053 // If both declarations give a tag declaration a typedef name for linkage 2054 // purposes, then they declare the same entity. 2055 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2056 Decl->getAnonDeclWithTypedefName()) 2057 continue; 2058 } 2059 2060 Filter.erase(); 2061 } 2062 2063 Filter.done(); 2064 } 2065 2066 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2067 QualType OldType; 2068 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2069 OldType = OldTypedef->getUnderlyingType(); 2070 else 2071 OldType = Context.getTypeDeclType(Old); 2072 QualType NewType = New->getUnderlyingType(); 2073 2074 if (NewType->isVariablyModifiedType()) { 2075 // Must not redefine a typedef with a variably-modified type. 2076 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2077 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2078 << Kind << NewType; 2079 if (Old->getLocation().isValid()) 2080 notePreviousDefinition(Old, New->getLocation()); 2081 New->setInvalidDecl(); 2082 return true; 2083 } 2084 2085 if (OldType != NewType && 2086 !OldType->isDependentType() && 2087 !NewType->isDependentType() && 2088 !Context.hasSameType(OldType, NewType)) { 2089 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2090 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2091 << Kind << NewType << OldType; 2092 if (Old->getLocation().isValid()) 2093 notePreviousDefinition(Old, New->getLocation()); 2094 New->setInvalidDecl(); 2095 return true; 2096 } 2097 return false; 2098 } 2099 2100 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2101 /// same name and scope as a previous declaration 'Old'. Figure out 2102 /// how to resolve this situation, merging decls or emitting 2103 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2104 /// 2105 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2106 LookupResult &OldDecls) { 2107 // If the new decl is known invalid already, don't bother doing any 2108 // merging checks. 2109 if (New->isInvalidDecl()) return; 2110 2111 // Allow multiple definitions for ObjC built-in typedefs. 2112 // FIXME: Verify the underlying types are equivalent! 2113 if (getLangOpts().ObjC1) { 2114 const IdentifierInfo *TypeID = New->getIdentifier(); 2115 switch (TypeID->getLength()) { 2116 default: break; 2117 case 2: 2118 { 2119 if (!TypeID->isStr("id")) 2120 break; 2121 QualType T = New->getUnderlyingType(); 2122 if (!T->isPointerType()) 2123 break; 2124 if (!T->isVoidPointerType()) { 2125 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2126 if (!PT->isStructureType()) 2127 break; 2128 } 2129 Context.setObjCIdRedefinitionType(T); 2130 // Install the built-in type for 'id', ignoring the current definition. 2131 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2132 return; 2133 } 2134 case 5: 2135 if (!TypeID->isStr("Class")) 2136 break; 2137 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2138 // Install the built-in type for 'Class', ignoring the current definition. 2139 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2140 return; 2141 case 3: 2142 if (!TypeID->isStr("SEL")) 2143 break; 2144 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2145 // Install the built-in type for 'SEL', ignoring the current definition. 2146 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2147 return; 2148 } 2149 // Fall through - the typedef name was not a builtin type. 2150 } 2151 2152 // Verify the old decl was also a type. 2153 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2154 if (!Old) { 2155 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2156 << New->getDeclName(); 2157 2158 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2159 if (OldD->getLocation().isValid()) 2160 notePreviousDefinition(OldD, New->getLocation()); 2161 2162 return New->setInvalidDecl(); 2163 } 2164 2165 // If the old declaration is invalid, just give up here. 2166 if (Old->isInvalidDecl()) 2167 return New->setInvalidDecl(); 2168 2169 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2170 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2171 auto *NewTag = New->getAnonDeclWithTypedefName(); 2172 NamedDecl *Hidden = nullptr; 2173 if (OldTag && NewTag && 2174 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2175 !hasVisibleDefinition(OldTag, &Hidden)) { 2176 // There is a definition of this tag, but it is not visible. Use it 2177 // instead of our tag. 2178 New->setTypeForDecl(OldTD->getTypeForDecl()); 2179 if (OldTD->isModed()) 2180 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2181 OldTD->getUnderlyingType()); 2182 else 2183 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2184 2185 // Make the old tag definition visible. 2186 makeMergedDefinitionVisible(Hidden); 2187 2188 // If this was an unscoped enumeration, yank all of its enumerators 2189 // out of the scope. 2190 if (isa<EnumDecl>(NewTag)) { 2191 Scope *EnumScope = getNonFieldDeclScope(S); 2192 for (auto *D : NewTag->decls()) { 2193 auto *ED = cast<EnumConstantDecl>(D); 2194 assert(EnumScope->isDeclScope(ED)); 2195 EnumScope->RemoveDecl(ED); 2196 IdResolver.RemoveDecl(ED); 2197 ED->getLexicalDeclContext()->removeDecl(ED); 2198 } 2199 } 2200 } 2201 } 2202 2203 // If the typedef types are not identical, reject them in all languages and 2204 // with any extensions enabled. 2205 if (isIncompatibleTypedef(Old, New)) 2206 return; 2207 2208 // The types match. Link up the redeclaration chain and merge attributes if 2209 // the old declaration was a typedef. 2210 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2211 New->setPreviousDecl(Typedef); 2212 mergeDeclAttributes(New, Old); 2213 } 2214 2215 if (getLangOpts().MicrosoftExt) 2216 return; 2217 2218 if (getLangOpts().CPlusPlus) { 2219 // C++ [dcl.typedef]p2: 2220 // In a given non-class scope, a typedef specifier can be used to 2221 // redefine the name of any type declared in that scope to refer 2222 // to the type to which it already refers. 2223 if (!isa<CXXRecordDecl>(CurContext)) 2224 return; 2225 2226 // C++0x [dcl.typedef]p4: 2227 // In a given class scope, a typedef specifier can be used to redefine 2228 // any class-name declared in that scope that is not also a typedef-name 2229 // to refer to the type to which it already refers. 2230 // 2231 // This wording came in via DR424, which was a correction to the 2232 // wording in DR56, which accidentally banned code like: 2233 // 2234 // struct S { 2235 // typedef struct A { } A; 2236 // }; 2237 // 2238 // in the C++03 standard. We implement the C++0x semantics, which 2239 // allow the above but disallow 2240 // 2241 // struct S { 2242 // typedef int I; 2243 // typedef int I; 2244 // }; 2245 // 2246 // since that was the intent of DR56. 2247 if (!isa<TypedefNameDecl>(Old)) 2248 return; 2249 2250 Diag(New->getLocation(), diag::err_redefinition) 2251 << New->getDeclName(); 2252 notePreviousDefinition(Old, New->getLocation()); 2253 return New->setInvalidDecl(); 2254 } 2255 2256 // Modules always permit redefinition of typedefs, as does C11. 2257 if (getLangOpts().Modules || getLangOpts().C11) 2258 return; 2259 2260 // If we have a redefinition of a typedef in C, emit a warning. This warning 2261 // is normally mapped to an error, but can be controlled with 2262 // -Wtypedef-redefinition. If either the original or the redefinition is 2263 // in a system header, don't emit this for compatibility with GCC. 2264 if (getDiagnostics().getSuppressSystemWarnings() && 2265 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2266 (Old->isImplicit() || 2267 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2268 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2269 return; 2270 2271 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2272 << New->getDeclName(); 2273 notePreviousDefinition(Old, New->getLocation()); 2274 } 2275 2276 /// DeclhasAttr - returns true if decl Declaration already has the target 2277 /// attribute. 2278 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2279 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2280 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2281 for (const auto *i : D->attrs()) 2282 if (i->getKind() == A->getKind()) { 2283 if (Ann) { 2284 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2285 return true; 2286 continue; 2287 } 2288 // FIXME: Don't hardcode this check 2289 if (OA && isa<OwnershipAttr>(i)) 2290 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2291 return true; 2292 } 2293 2294 return false; 2295 } 2296 2297 static bool isAttributeTargetADefinition(Decl *D) { 2298 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2299 return VD->isThisDeclarationADefinition(); 2300 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2301 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2302 return true; 2303 } 2304 2305 /// Merge alignment attributes from \p Old to \p New, taking into account the 2306 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2307 /// 2308 /// \return \c true if any attributes were added to \p New. 2309 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2310 // Look for alignas attributes on Old, and pick out whichever attribute 2311 // specifies the strictest alignment requirement. 2312 AlignedAttr *OldAlignasAttr = nullptr; 2313 AlignedAttr *OldStrictestAlignAttr = nullptr; 2314 unsigned OldAlign = 0; 2315 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2316 // FIXME: We have no way of representing inherited dependent alignments 2317 // in a case like: 2318 // template<int A, int B> struct alignas(A) X; 2319 // template<int A, int B> struct alignas(B) X {}; 2320 // For now, we just ignore any alignas attributes which are not on the 2321 // definition in such a case. 2322 if (I->isAlignmentDependent()) 2323 return false; 2324 2325 if (I->isAlignas()) 2326 OldAlignasAttr = I; 2327 2328 unsigned Align = I->getAlignment(S.Context); 2329 if (Align > OldAlign) { 2330 OldAlign = Align; 2331 OldStrictestAlignAttr = I; 2332 } 2333 } 2334 2335 // Look for alignas attributes on New. 2336 AlignedAttr *NewAlignasAttr = nullptr; 2337 unsigned NewAlign = 0; 2338 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2339 if (I->isAlignmentDependent()) 2340 return false; 2341 2342 if (I->isAlignas()) 2343 NewAlignasAttr = I; 2344 2345 unsigned Align = I->getAlignment(S.Context); 2346 if (Align > NewAlign) 2347 NewAlign = Align; 2348 } 2349 2350 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2351 // Both declarations have 'alignas' attributes. We require them to match. 2352 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2353 // fall short. (If two declarations both have alignas, they must both match 2354 // every definition, and so must match each other if there is a definition.) 2355 2356 // If either declaration only contains 'alignas(0)' specifiers, then it 2357 // specifies the natural alignment for the type. 2358 if (OldAlign == 0 || NewAlign == 0) { 2359 QualType Ty; 2360 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2361 Ty = VD->getType(); 2362 else 2363 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2364 2365 if (OldAlign == 0) 2366 OldAlign = S.Context.getTypeAlign(Ty); 2367 if (NewAlign == 0) 2368 NewAlign = S.Context.getTypeAlign(Ty); 2369 } 2370 2371 if (OldAlign != NewAlign) { 2372 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2373 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2374 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2375 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2376 } 2377 } 2378 2379 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2380 // C++11 [dcl.align]p6: 2381 // if any declaration of an entity has an alignment-specifier, 2382 // every defining declaration of that entity shall specify an 2383 // equivalent alignment. 2384 // C11 6.7.5/7: 2385 // If the definition of an object does not have an alignment 2386 // specifier, any other declaration of that object shall also 2387 // have no alignment specifier. 2388 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2389 << OldAlignasAttr; 2390 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2391 << OldAlignasAttr; 2392 } 2393 2394 bool AnyAdded = false; 2395 2396 // Ensure we have an attribute representing the strictest alignment. 2397 if (OldAlign > NewAlign) { 2398 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2399 Clone->setInherited(true); 2400 New->addAttr(Clone); 2401 AnyAdded = true; 2402 } 2403 2404 // Ensure we have an alignas attribute if the old declaration had one. 2405 if (OldAlignasAttr && !NewAlignasAttr && 2406 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2407 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2408 Clone->setInherited(true); 2409 New->addAttr(Clone); 2410 AnyAdded = true; 2411 } 2412 2413 return AnyAdded; 2414 } 2415 2416 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2417 const InheritableAttr *Attr, 2418 Sema::AvailabilityMergeKind AMK) { 2419 // This function copies an attribute Attr from a previous declaration to the 2420 // new declaration D if the new declaration doesn't itself have that attribute 2421 // yet or if that attribute allows duplicates. 2422 // If you're adding a new attribute that requires logic different from 2423 // "use explicit attribute on decl if present, else use attribute from 2424 // previous decl", for example if the attribute needs to be consistent 2425 // between redeclarations, you need to call a custom merge function here. 2426 InheritableAttr *NewAttr = nullptr; 2427 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2428 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2429 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2430 AA->isImplicit(), AA->getIntroduced(), 2431 AA->getDeprecated(), 2432 AA->getObsoleted(), AA->getUnavailable(), 2433 AA->getMessage(), AA->getStrict(), 2434 AA->getReplacement(), AMK, 2435 AttrSpellingListIndex); 2436 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2437 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2438 AttrSpellingListIndex); 2439 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2440 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2441 AttrSpellingListIndex); 2442 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2443 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2444 AttrSpellingListIndex); 2445 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2446 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2447 AttrSpellingListIndex); 2448 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2449 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2450 FA->getFormatIdx(), FA->getFirstArg(), 2451 AttrSpellingListIndex); 2452 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2453 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2454 AttrSpellingListIndex); 2455 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2456 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2457 AttrSpellingListIndex, 2458 IA->getSemanticSpelling()); 2459 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2460 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2461 &S.Context.Idents.get(AA->getSpelling()), 2462 AttrSpellingListIndex); 2463 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2464 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2465 isa<CUDAGlobalAttr>(Attr))) { 2466 // CUDA target attributes are part of function signature for 2467 // overloading purposes and must not be merged. 2468 return false; 2469 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2470 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2471 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2472 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2473 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2474 NewAttr = S.mergeInternalLinkageAttr( 2475 D, InternalLinkageA->getRange(), 2476 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2477 AttrSpellingListIndex); 2478 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2479 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2480 &S.Context.Idents.get(CommonA->getSpelling()), 2481 AttrSpellingListIndex); 2482 else if (isa<AlignedAttr>(Attr)) 2483 // AlignedAttrs are handled separately, because we need to handle all 2484 // such attributes on a declaration at the same time. 2485 NewAttr = nullptr; 2486 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2487 (AMK == Sema::AMK_Override || 2488 AMK == Sema::AMK_ProtocolImplementation)) 2489 NewAttr = nullptr; 2490 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2491 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2492 UA->getGuid()); 2493 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2494 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2495 2496 if (NewAttr) { 2497 NewAttr->setInherited(true); 2498 D->addAttr(NewAttr); 2499 if (isa<MSInheritanceAttr>(NewAttr)) 2500 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2501 return true; 2502 } 2503 2504 return false; 2505 } 2506 2507 static const NamedDecl *getDefinition(const Decl *D) { 2508 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2509 return TD->getDefinition(); 2510 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2511 const VarDecl *Def = VD->getDefinition(); 2512 if (Def) 2513 return Def; 2514 return VD->getActingDefinition(); 2515 } 2516 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2517 return FD->getDefinition(); 2518 return nullptr; 2519 } 2520 2521 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2522 for (const auto *Attribute : D->attrs()) 2523 if (Attribute->getKind() == Kind) 2524 return true; 2525 return false; 2526 } 2527 2528 /// checkNewAttributesAfterDef - If we already have a definition, check that 2529 /// there are no new attributes in this declaration. 2530 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2531 if (!New->hasAttrs()) 2532 return; 2533 2534 const NamedDecl *Def = getDefinition(Old); 2535 if (!Def || Def == New) 2536 return; 2537 2538 AttrVec &NewAttributes = New->getAttrs(); 2539 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2540 const Attr *NewAttribute = NewAttributes[I]; 2541 2542 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2543 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2544 Sema::SkipBodyInfo SkipBody; 2545 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2546 2547 // If we're skipping this definition, drop the "alias" attribute. 2548 if (SkipBody.ShouldSkip) { 2549 NewAttributes.erase(NewAttributes.begin() + I); 2550 --E; 2551 continue; 2552 } 2553 } else { 2554 VarDecl *VD = cast<VarDecl>(New); 2555 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2556 VarDecl::TentativeDefinition 2557 ? diag::err_alias_after_tentative 2558 : diag::err_redefinition; 2559 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2560 if (Diag == diag::err_redefinition) 2561 S.notePreviousDefinition(Def, VD->getLocation()); 2562 else 2563 S.Diag(Def->getLocation(), diag::note_previous_definition); 2564 VD->setInvalidDecl(); 2565 } 2566 ++I; 2567 continue; 2568 } 2569 2570 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2571 // Tentative definitions are only interesting for the alias check above. 2572 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2573 ++I; 2574 continue; 2575 } 2576 } 2577 2578 if (hasAttribute(Def, NewAttribute->getKind())) { 2579 ++I; 2580 continue; // regular attr merging will take care of validating this. 2581 } 2582 2583 if (isa<C11NoReturnAttr>(NewAttribute)) { 2584 // C's _Noreturn is allowed to be added to a function after it is defined. 2585 ++I; 2586 continue; 2587 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2588 if (AA->isAlignas()) { 2589 // C++11 [dcl.align]p6: 2590 // if any declaration of an entity has an alignment-specifier, 2591 // every defining declaration of that entity shall specify an 2592 // equivalent alignment. 2593 // C11 6.7.5/7: 2594 // If the definition of an object does not have an alignment 2595 // specifier, any other declaration of that object shall also 2596 // have no alignment specifier. 2597 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2598 << AA; 2599 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2600 << AA; 2601 NewAttributes.erase(NewAttributes.begin() + I); 2602 --E; 2603 continue; 2604 } 2605 } 2606 2607 S.Diag(NewAttribute->getLocation(), 2608 diag::warn_attribute_precede_definition); 2609 S.Diag(Def->getLocation(), diag::note_previous_definition); 2610 NewAttributes.erase(NewAttributes.begin() + I); 2611 --E; 2612 } 2613 } 2614 2615 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2616 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2617 AvailabilityMergeKind AMK) { 2618 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2619 UsedAttr *NewAttr = OldAttr->clone(Context); 2620 NewAttr->setInherited(true); 2621 New->addAttr(NewAttr); 2622 } 2623 2624 if (!Old->hasAttrs() && !New->hasAttrs()) 2625 return; 2626 2627 // Attributes declared post-definition are currently ignored. 2628 checkNewAttributesAfterDef(*this, New, Old); 2629 2630 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2631 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2632 if (OldA->getLabel() != NewA->getLabel()) { 2633 // This redeclaration changes __asm__ label. 2634 Diag(New->getLocation(), diag::err_different_asm_label); 2635 Diag(OldA->getLocation(), diag::note_previous_declaration); 2636 } 2637 } else if (Old->isUsed()) { 2638 // This redeclaration adds an __asm__ label to a declaration that has 2639 // already been ODR-used. 2640 Diag(New->getLocation(), diag::err_late_asm_label_name) 2641 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2642 } 2643 } 2644 2645 // Re-declaration cannot add abi_tag's. 2646 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2647 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2648 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2649 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2650 NewTag) == OldAbiTagAttr->tags_end()) { 2651 Diag(NewAbiTagAttr->getLocation(), 2652 diag::err_new_abi_tag_on_redeclaration) 2653 << NewTag; 2654 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2655 } 2656 } 2657 } else { 2658 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2659 Diag(Old->getLocation(), diag::note_previous_declaration); 2660 } 2661 } 2662 2663 // This redeclaration adds a section attribute. 2664 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2665 if (auto *VD = dyn_cast<VarDecl>(New)) { 2666 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2667 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2668 Diag(Old->getLocation(), diag::note_previous_declaration); 2669 } 2670 } else if (isa<CXXMethodDecl>(New)) { 2671 const auto *NewSA = New->getAttr<SectionAttr>(); 2672 if (!NewSA->isImplicit()) { 2673 Diag(New->getLocation(), diag::warn_mismatched_section); 2674 Diag(Old->getLocation(), diag::note_previous_declaration); 2675 } 2676 } 2677 } 2678 if (!Old->hasAttrs()) 2679 return; 2680 2681 bool foundAny = New->hasAttrs(); 2682 2683 // Ensure that any moving of objects within the allocated map is done before 2684 // we process them. 2685 if (!foundAny) New->setAttrs(AttrVec()); 2686 2687 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2688 // Ignore deprecated/unavailable/availability attributes if requested. 2689 AvailabilityMergeKind LocalAMK = AMK_None; 2690 if (isa<DeprecatedAttr>(I) || 2691 isa<UnavailableAttr>(I) || 2692 isa<AvailabilityAttr>(I)) { 2693 switch (AMK) { 2694 case AMK_None: 2695 continue; 2696 2697 case AMK_Redeclaration: 2698 case AMK_Override: 2699 case AMK_ProtocolImplementation: 2700 LocalAMK = AMK; 2701 break; 2702 } 2703 } 2704 2705 // Already handled. 2706 if (isa<UsedAttr>(I)) 2707 continue; 2708 2709 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2710 foundAny = true; 2711 } 2712 2713 if (mergeAlignedAttrs(*this, New, Old)) 2714 foundAny = true; 2715 2716 if (!foundAny) New->dropAttrs(); 2717 } 2718 2719 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2720 /// to the new one. 2721 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2722 const ParmVarDecl *oldDecl, 2723 Sema &S) { 2724 // C++11 [dcl.attr.depend]p2: 2725 // The first declaration of a function shall specify the 2726 // carries_dependency attribute for its declarator-id if any declaration 2727 // of the function specifies the carries_dependency attribute. 2728 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2729 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2730 S.Diag(CDA->getLocation(), 2731 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2732 // Find the first declaration of the parameter. 2733 // FIXME: Should we build redeclaration chains for function parameters? 2734 const FunctionDecl *FirstFD = 2735 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2736 const ParmVarDecl *FirstVD = 2737 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2738 S.Diag(FirstVD->getLocation(), 2739 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2740 } 2741 2742 if (!oldDecl->hasAttrs()) 2743 return; 2744 2745 bool foundAny = newDecl->hasAttrs(); 2746 2747 // Ensure that any moving of objects within the allocated map is 2748 // done before we process them. 2749 if (!foundAny) newDecl->setAttrs(AttrVec()); 2750 2751 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2752 if (!DeclHasAttr(newDecl, I)) { 2753 InheritableAttr *newAttr = 2754 cast<InheritableParamAttr>(I->clone(S.Context)); 2755 newAttr->setInherited(true); 2756 newDecl->addAttr(newAttr); 2757 foundAny = true; 2758 } 2759 } 2760 2761 if (!foundAny) newDecl->dropAttrs(); 2762 } 2763 2764 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2765 const ParmVarDecl *OldParam, 2766 Sema &S) { 2767 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2768 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2769 if (*Oldnullability != *Newnullability) { 2770 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2771 << DiagNullabilityKind( 2772 *Newnullability, 2773 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2774 != 0)) 2775 << DiagNullabilityKind( 2776 *Oldnullability, 2777 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2778 != 0)); 2779 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2780 } 2781 } else { 2782 QualType NewT = NewParam->getType(); 2783 NewT = S.Context.getAttributedType( 2784 AttributedType::getNullabilityAttrKind(*Oldnullability), 2785 NewT, NewT); 2786 NewParam->setType(NewT); 2787 } 2788 } 2789 } 2790 2791 namespace { 2792 2793 /// Used in MergeFunctionDecl to keep track of function parameters in 2794 /// C. 2795 struct GNUCompatibleParamWarning { 2796 ParmVarDecl *OldParm; 2797 ParmVarDecl *NewParm; 2798 QualType PromotedType; 2799 }; 2800 2801 } // end anonymous namespace 2802 2803 /// getSpecialMember - get the special member enum for a method. 2804 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2805 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2806 if (Ctor->isDefaultConstructor()) 2807 return Sema::CXXDefaultConstructor; 2808 2809 if (Ctor->isCopyConstructor()) 2810 return Sema::CXXCopyConstructor; 2811 2812 if (Ctor->isMoveConstructor()) 2813 return Sema::CXXMoveConstructor; 2814 } else if (isa<CXXDestructorDecl>(MD)) { 2815 return Sema::CXXDestructor; 2816 } else if (MD->isCopyAssignmentOperator()) { 2817 return Sema::CXXCopyAssignment; 2818 } else if (MD->isMoveAssignmentOperator()) { 2819 return Sema::CXXMoveAssignment; 2820 } 2821 2822 return Sema::CXXInvalid; 2823 } 2824 2825 // Determine whether the previous declaration was a definition, implicit 2826 // declaration, or a declaration. 2827 template <typename T> 2828 static std::pair<diag::kind, SourceLocation> 2829 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2830 diag::kind PrevDiag; 2831 SourceLocation OldLocation = Old->getLocation(); 2832 if (Old->isThisDeclarationADefinition()) 2833 PrevDiag = diag::note_previous_definition; 2834 else if (Old->isImplicit()) { 2835 PrevDiag = diag::note_previous_implicit_declaration; 2836 if (OldLocation.isInvalid()) 2837 OldLocation = New->getLocation(); 2838 } else 2839 PrevDiag = diag::note_previous_declaration; 2840 return std::make_pair(PrevDiag, OldLocation); 2841 } 2842 2843 /// canRedefineFunction - checks if a function can be redefined. Currently, 2844 /// only extern inline functions can be redefined, and even then only in 2845 /// GNU89 mode. 2846 static bool canRedefineFunction(const FunctionDecl *FD, 2847 const LangOptions& LangOpts) { 2848 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2849 !LangOpts.CPlusPlus && 2850 FD->isInlineSpecified() && 2851 FD->getStorageClass() == SC_Extern); 2852 } 2853 2854 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2855 const AttributedType *AT = T->getAs<AttributedType>(); 2856 while (AT && !AT->isCallingConv()) 2857 AT = AT->getModifiedType()->getAs<AttributedType>(); 2858 return AT; 2859 } 2860 2861 template <typename T> 2862 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2863 const DeclContext *DC = Old->getDeclContext(); 2864 if (DC->isRecord()) 2865 return false; 2866 2867 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2868 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2869 return true; 2870 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2871 return true; 2872 return false; 2873 } 2874 2875 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2876 static bool isExternC(VarTemplateDecl *) { return false; } 2877 2878 /// Check whether a redeclaration of an entity introduced by a 2879 /// using-declaration is valid, given that we know it's not an overload 2880 /// (nor a hidden tag declaration). 2881 template<typename ExpectedDecl> 2882 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2883 ExpectedDecl *New) { 2884 // C++11 [basic.scope.declarative]p4: 2885 // Given a set of declarations in a single declarative region, each of 2886 // which specifies the same unqualified name, 2887 // -- they shall all refer to the same entity, or all refer to functions 2888 // and function templates; or 2889 // -- exactly one declaration shall declare a class name or enumeration 2890 // name that is not a typedef name and the other declarations shall all 2891 // refer to the same variable or enumerator, or all refer to functions 2892 // and function templates; in this case the class name or enumeration 2893 // name is hidden (3.3.10). 2894 2895 // C++11 [namespace.udecl]p14: 2896 // If a function declaration in namespace scope or block scope has the 2897 // same name and the same parameter-type-list as a function introduced 2898 // by a using-declaration, and the declarations do not declare the same 2899 // function, the program is ill-formed. 2900 2901 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2902 if (Old && 2903 !Old->getDeclContext()->getRedeclContext()->Equals( 2904 New->getDeclContext()->getRedeclContext()) && 2905 !(isExternC(Old) && isExternC(New))) 2906 Old = nullptr; 2907 2908 if (!Old) { 2909 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2910 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2911 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2912 return true; 2913 } 2914 return false; 2915 } 2916 2917 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2918 const FunctionDecl *B) { 2919 assert(A->getNumParams() == B->getNumParams()); 2920 2921 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2922 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2923 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2924 if (AttrA == AttrB) 2925 return true; 2926 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2927 }; 2928 2929 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2930 } 2931 2932 /// If necessary, adjust the semantic declaration context for a qualified 2933 /// declaration to name the correct inline namespace within the qualifier. 2934 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2935 DeclaratorDecl *OldD) { 2936 // The only case where we need to update the DeclContext is when 2937 // redeclaration lookup for a qualified name finds a declaration 2938 // in an inline namespace within the context named by the qualifier: 2939 // 2940 // inline namespace N { int f(); } 2941 // int ::f(); // Sema DC needs adjusting from :: to N::. 2942 // 2943 // For unqualified declarations, the semantic context *can* change 2944 // along the redeclaration chain (for local extern declarations, 2945 // extern "C" declarations, and friend declarations in particular). 2946 if (!NewD->getQualifier()) 2947 return; 2948 2949 // NewD is probably already in the right context. 2950 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2951 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2952 if (NamedDC->Equals(SemaDC)) 2953 return; 2954 2955 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2956 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2957 "unexpected context for redeclaration"); 2958 2959 auto *LexDC = NewD->getLexicalDeclContext(); 2960 auto FixSemaDC = [=](NamedDecl *D) { 2961 if (!D) 2962 return; 2963 D->setDeclContext(SemaDC); 2964 D->setLexicalDeclContext(LexDC); 2965 }; 2966 2967 FixSemaDC(NewD); 2968 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 2969 FixSemaDC(FD->getDescribedFunctionTemplate()); 2970 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 2971 FixSemaDC(VD->getDescribedVarTemplate()); 2972 } 2973 2974 /// MergeFunctionDecl - We just parsed a function 'New' from 2975 /// declarator D which has the same name and scope as a previous 2976 /// declaration 'Old'. Figure out how to resolve this situation, 2977 /// merging decls or emitting diagnostics as appropriate. 2978 /// 2979 /// In C++, New and Old must be declarations that are not 2980 /// overloaded. Use IsOverload to determine whether New and Old are 2981 /// overloaded, and to select the Old declaration that New should be 2982 /// merged with. 2983 /// 2984 /// Returns true if there was an error, false otherwise. 2985 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2986 Scope *S, bool MergeTypeWithOld) { 2987 // Verify the old decl was also a function. 2988 FunctionDecl *Old = OldD->getAsFunction(); 2989 if (!Old) { 2990 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2991 if (New->getFriendObjectKind()) { 2992 Diag(New->getLocation(), diag::err_using_decl_friend); 2993 Diag(Shadow->getTargetDecl()->getLocation(), 2994 diag::note_using_decl_target); 2995 Diag(Shadow->getUsingDecl()->getLocation(), 2996 diag::note_using_decl) << 0; 2997 return true; 2998 } 2999 3000 // Check whether the two declarations might declare the same function. 3001 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3002 return true; 3003 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3004 } else { 3005 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3006 << New->getDeclName(); 3007 notePreviousDefinition(OldD, New->getLocation()); 3008 return true; 3009 } 3010 } 3011 3012 // If the old declaration is invalid, just give up here. 3013 if (Old->isInvalidDecl()) 3014 return true; 3015 3016 // Disallow redeclaration of some builtins. 3017 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3018 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3019 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3020 << Old << Old->getType(); 3021 return true; 3022 } 3023 3024 diag::kind PrevDiag; 3025 SourceLocation OldLocation; 3026 std::tie(PrevDiag, OldLocation) = 3027 getNoteDiagForInvalidRedeclaration(Old, New); 3028 3029 // Don't complain about this if we're in GNU89 mode and the old function 3030 // is an extern inline function. 3031 // Don't complain about specializations. They are not supposed to have 3032 // storage classes. 3033 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3034 New->getStorageClass() == SC_Static && 3035 Old->hasExternalFormalLinkage() && 3036 !New->getTemplateSpecializationInfo() && 3037 !canRedefineFunction(Old, getLangOpts())) { 3038 if (getLangOpts().MicrosoftExt) { 3039 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3040 Diag(OldLocation, PrevDiag); 3041 } else { 3042 Diag(New->getLocation(), diag::err_static_non_static) << New; 3043 Diag(OldLocation, PrevDiag); 3044 return true; 3045 } 3046 } 3047 3048 if (New->hasAttr<InternalLinkageAttr>() && 3049 !Old->hasAttr<InternalLinkageAttr>()) { 3050 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3051 << New->getDeclName(); 3052 notePreviousDefinition(Old, New->getLocation()); 3053 New->dropAttr<InternalLinkageAttr>(); 3054 } 3055 3056 if (CheckRedeclarationModuleOwnership(New, Old)) 3057 return true; 3058 3059 if (!getLangOpts().CPlusPlus) { 3060 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3061 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3062 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3063 << New << OldOvl; 3064 3065 // Try our best to find a decl that actually has the overloadable 3066 // attribute for the note. In most cases (e.g. programs with only one 3067 // broken declaration/definition), this won't matter. 3068 // 3069 // FIXME: We could do this if we juggled some extra state in 3070 // OverloadableAttr, rather than just removing it. 3071 const Decl *DiagOld = Old; 3072 if (OldOvl) { 3073 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3074 const auto *A = D->getAttr<OverloadableAttr>(); 3075 return A && !A->isImplicit(); 3076 }); 3077 // If we've implicitly added *all* of the overloadable attrs to this 3078 // chain, emitting a "previous redecl" note is pointless. 3079 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3080 } 3081 3082 if (DiagOld) 3083 Diag(DiagOld->getLocation(), 3084 diag::note_attribute_overloadable_prev_overload) 3085 << OldOvl; 3086 3087 if (OldOvl) 3088 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3089 else 3090 New->dropAttr<OverloadableAttr>(); 3091 } 3092 } 3093 3094 // If a function is first declared with a calling convention, but is later 3095 // declared or defined without one, all following decls assume the calling 3096 // convention of the first. 3097 // 3098 // It's OK if a function is first declared without a calling convention, 3099 // but is later declared or defined with the default calling convention. 3100 // 3101 // To test if either decl has an explicit calling convention, we look for 3102 // AttributedType sugar nodes on the type as written. If they are missing or 3103 // were canonicalized away, we assume the calling convention was implicit. 3104 // 3105 // Note also that we DO NOT return at this point, because we still have 3106 // other tests to run. 3107 QualType OldQType = Context.getCanonicalType(Old->getType()); 3108 QualType NewQType = Context.getCanonicalType(New->getType()); 3109 const FunctionType *OldType = cast<FunctionType>(OldQType); 3110 const FunctionType *NewType = cast<FunctionType>(NewQType); 3111 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3112 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3113 bool RequiresAdjustment = false; 3114 3115 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3116 FunctionDecl *First = Old->getFirstDecl(); 3117 const FunctionType *FT = 3118 First->getType().getCanonicalType()->castAs<FunctionType>(); 3119 FunctionType::ExtInfo FI = FT->getExtInfo(); 3120 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3121 if (!NewCCExplicit) { 3122 // Inherit the CC from the previous declaration if it was specified 3123 // there but not here. 3124 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3125 RequiresAdjustment = true; 3126 } else { 3127 // Calling conventions aren't compatible, so complain. 3128 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3129 Diag(New->getLocation(), diag::err_cconv_change) 3130 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3131 << !FirstCCExplicit 3132 << (!FirstCCExplicit ? "" : 3133 FunctionType::getNameForCallConv(FI.getCC())); 3134 3135 // Put the note on the first decl, since it is the one that matters. 3136 Diag(First->getLocation(), diag::note_previous_declaration); 3137 return true; 3138 } 3139 } 3140 3141 // FIXME: diagnose the other way around? 3142 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3143 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3144 RequiresAdjustment = true; 3145 } 3146 3147 // Merge regparm attribute. 3148 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3149 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3150 if (NewTypeInfo.getHasRegParm()) { 3151 Diag(New->getLocation(), diag::err_regparm_mismatch) 3152 << NewType->getRegParmType() 3153 << OldType->getRegParmType(); 3154 Diag(OldLocation, diag::note_previous_declaration); 3155 return true; 3156 } 3157 3158 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3159 RequiresAdjustment = true; 3160 } 3161 3162 // Merge ns_returns_retained attribute. 3163 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3164 if (NewTypeInfo.getProducesResult()) { 3165 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3166 << "'ns_returns_retained'"; 3167 Diag(OldLocation, diag::note_previous_declaration); 3168 return true; 3169 } 3170 3171 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3172 RequiresAdjustment = true; 3173 } 3174 3175 if (OldTypeInfo.getNoCallerSavedRegs() != 3176 NewTypeInfo.getNoCallerSavedRegs()) { 3177 if (NewTypeInfo.getNoCallerSavedRegs()) { 3178 AnyX86NoCallerSavedRegistersAttr *Attr = 3179 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3180 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3181 Diag(OldLocation, diag::note_previous_declaration); 3182 return true; 3183 } 3184 3185 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3186 RequiresAdjustment = true; 3187 } 3188 3189 if (RequiresAdjustment) { 3190 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3191 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3192 New->setType(QualType(AdjustedType, 0)); 3193 NewQType = Context.getCanonicalType(New->getType()); 3194 NewType = cast<FunctionType>(NewQType); 3195 } 3196 3197 // If this redeclaration makes the function inline, we may need to add it to 3198 // UndefinedButUsed. 3199 if (!Old->isInlined() && New->isInlined() && 3200 !New->hasAttr<GNUInlineAttr>() && 3201 !getLangOpts().GNUInline && 3202 Old->isUsed(false) && 3203 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3204 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3205 SourceLocation())); 3206 3207 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3208 // about it. 3209 if (New->hasAttr<GNUInlineAttr>() && 3210 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3211 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3212 } 3213 3214 // If pass_object_size params don't match up perfectly, this isn't a valid 3215 // redeclaration. 3216 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3217 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3218 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3219 << New->getDeclName(); 3220 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3221 return true; 3222 } 3223 3224 if (getLangOpts().CPlusPlus) { 3225 // C++1z [over.load]p2 3226 // Certain function declarations cannot be overloaded: 3227 // -- Function declarations that differ only in the return type, 3228 // the exception specification, or both cannot be overloaded. 3229 3230 // Check the exception specifications match. This may recompute the type of 3231 // both Old and New if it resolved exception specifications, so grab the 3232 // types again after this. Because this updates the type, we do this before 3233 // any of the other checks below, which may update the "de facto" NewQType 3234 // but do not necessarily update the type of New. 3235 if (CheckEquivalentExceptionSpec(Old, New)) 3236 return true; 3237 OldQType = Context.getCanonicalType(Old->getType()); 3238 NewQType = Context.getCanonicalType(New->getType()); 3239 3240 // Go back to the type source info to compare the declared return types, 3241 // per C++1y [dcl.type.auto]p13: 3242 // Redeclarations or specializations of a function or function template 3243 // with a declared return type that uses a placeholder type shall also 3244 // use that placeholder, not a deduced type. 3245 QualType OldDeclaredReturnType = 3246 (Old->getTypeSourceInfo() 3247 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3248 : OldType)->getReturnType(); 3249 QualType NewDeclaredReturnType = 3250 (New->getTypeSourceInfo() 3251 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3252 : NewType)->getReturnType(); 3253 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3254 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3255 New->isLocalExternDecl())) { 3256 QualType ResQT; 3257 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3258 OldDeclaredReturnType->isObjCObjectPointerType()) 3259 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3260 if (ResQT.isNull()) { 3261 if (New->isCXXClassMember() && New->isOutOfLine()) 3262 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3263 << New << New->getReturnTypeSourceRange(); 3264 else 3265 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3266 << New->getReturnTypeSourceRange(); 3267 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3268 << Old->getReturnTypeSourceRange(); 3269 return true; 3270 } 3271 else 3272 NewQType = ResQT; 3273 } 3274 3275 QualType OldReturnType = OldType->getReturnType(); 3276 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3277 if (OldReturnType != NewReturnType) { 3278 // If this function has a deduced return type and has already been 3279 // defined, copy the deduced value from the old declaration. 3280 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3281 if (OldAT && OldAT->isDeduced()) { 3282 New->setType( 3283 SubstAutoType(New->getType(), 3284 OldAT->isDependentType() ? Context.DependentTy 3285 : OldAT->getDeducedType())); 3286 NewQType = Context.getCanonicalType( 3287 SubstAutoType(NewQType, 3288 OldAT->isDependentType() ? Context.DependentTy 3289 : OldAT->getDeducedType())); 3290 } 3291 } 3292 3293 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3294 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3295 if (OldMethod && NewMethod) { 3296 // Preserve triviality. 3297 NewMethod->setTrivial(OldMethod->isTrivial()); 3298 3299 // MSVC allows explicit template specialization at class scope: 3300 // 2 CXXMethodDecls referring to the same function will be injected. 3301 // We don't want a redeclaration error. 3302 bool IsClassScopeExplicitSpecialization = 3303 OldMethod->isFunctionTemplateSpecialization() && 3304 NewMethod->isFunctionTemplateSpecialization(); 3305 bool isFriend = NewMethod->getFriendObjectKind(); 3306 3307 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3308 !IsClassScopeExplicitSpecialization) { 3309 // -- Member function declarations with the same name and the 3310 // same parameter types cannot be overloaded if any of them 3311 // is a static member function declaration. 3312 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3313 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3314 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3315 return true; 3316 } 3317 3318 // C++ [class.mem]p1: 3319 // [...] A member shall not be declared twice in the 3320 // member-specification, except that a nested class or member 3321 // class template can be declared and then later defined. 3322 if (!inTemplateInstantiation()) { 3323 unsigned NewDiag; 3324 if (isa<CXXConstructorDecl>(OldMethod)) 3325 NewDiag = diag::err_constructor_redeclared; 3326 else if (isa<CXXDestructorDecl>(NewMethod)) 3327 NewDiag = diag::err_destructor_redeclared; 3328 else if (isa<CXXConversionDecl>(NewMethod)) 3329 NewDiag = diag::err_conv_function_redeclared; 3330 else 3331 NewDiag = diag::err_member_redeclared; 3332 3333 Diag(New->getLocation(), NewDiag); 3334 } else { 3335 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3336 << New << New->getType(); 3337 } 3338 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3339 return true; 3340 3341 // Complain if this is an explicit declaration of a special 3342 // member that was initially declared implicitly. 3343 // 3344 // As an exception, it's okay to befriend such methods in order 3345 // to permit the implicit constructor/destructor/operator calls. 3346 } else if (OldMethod->isImplicit()) { 3347 if (isFriend) { 3348 NewMethod->setImplicit(); 3349 } else { 3350 Diag(NewMethod->getLocation(), 3351 diag::err_definition_of_implicitly_declared_member) 3352 << New << getSpecialMember(OldMethod); 3353 return true; 3354 } 3355 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3356 Diag(NewMethod->getLocation(), 3357 diag::err_definition_of_explicitly_defaulted_member) 3358 << getSpecialMember(OldMethod); 3359 return true; 3360 } 3361 } 3362 3363 // C++11 [dcl.attr.noreturn]p1: 3364 // The first declaration of a function shall specify the noreturn 3365 // attribute if any declaration of that function specifies the noreturn 3366 // attribute. 3367 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3368 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3369 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3370 Diag(Old->getFirstDecl()->getLocation(), 3371 diag::note_noreturn_missing_first_decl); 3372 } 3373 3374 // C++11 [dcl.attr.depend]p2: 3375 // The first declaration of a function shall specify the 3376 // carries_dependency attribute for its declarator-id if any declaration 3377 // of the function specifies the carries_dependency attribute. 3378 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3379 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3380 Diag(CDA->getLocation(), 3381 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3382 Diag(Old->getFirstDecl()->getLocation(), 3383 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3384 } 3385 3386 // (C++98 8.3.5p3): 3387 // All declarations for a function shall agree exactly in both the 3388 // return type and the parameter-type-list. 3389 // We also want to respect all the extended bits except noreturn. 3390 3391 // noreturn should now match unless the old type info didn't have it. 3392 QualType OldQTypeForComparison = OldQType; 3393 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3394 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3395 const FunctionType *OldTypeForComparison 3396 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3397 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3398 assert(OldQTypeForComparison.isCanonical()); 3399 } 3400 3401 if (haveIncompatibleLanguageLinkages(Old, New)) { 3402 // As a special case, retain the language linkage from previous 3403 // declarations of a friend function as an extension. 3404 // 3405 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3406 // and is useful because there's otherwise no way to specify language 3407 // linkage within class scope. 3408 // 3409 // Check cautiously as the friend object kind isn't yet complete. 3410 if (New->getFriendObjectKind() != Decl::FOK_None) { 3411 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3412 Diag(OldLocation, PrevDiag); 3413 } else { 3414 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3415 Diag(OldLocation, PrevDiag); 3416 return true; 3417 } 3418 } 3419 3420 if (OldQTypeForComparison == NewQType) 3421 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3422 3423 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3424 New->isLocalExternDecl()) { 3425 // It's OK if we couldn't merge types for a local function declaraton 3426 // if either the old or new type is dependent. We'll merge the types 3427 // when we instantiate the function. 3428 return false; 3429 } 3430 3431 // Fall through for conflicting redeclarations and redefinitions. 3432 } 3433 3434 // C: Function types need to be compatible, not identical. This handles 3435 // duplicate function decls like "void f(int); void f(enum X);" properly. 3436 if (!getLangOpts().CPlusPlus && 3437 Context.typesAreCompatible(OldQType, NewQType)) { 3438 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3439 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3440 const FunctionProtoType *OldProto = nullptr; 3441 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3442 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3443 // The old declaration provided a function prototype, but the 3444 // new declaration does not. Merge in the prototype. 3445 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3446 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3447 NewQType = 3448 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3449 OldProto->getExtProtoInfo()); 3450 New->setType(NewQType); 3451 New->setHasInheritedPrototype(); 3452 3453 // Synthesize parameters with the same types. 3454 SmallVector<ParmVarDecl*, 16> Params; 3455 for (const auto &ParamType : OldProto->param_types()) { 3456 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3457 SourceLocation(), nullptr, 3458 ParamType, /*TInfo=*/nullptr, 3459 SC_None, nullptr); 3460 Param->setScopeInfo(0, Params.size()); 3461 Param->setImplicit(); 3462 Params.push_back(Param); 3463 } 3464 3465 New->setParams(Params); 3466 } 3467 3468 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3469 } 3470 3471 // GNU C permits a K&R definition to follow a prototype declaration 3472 // if the declared types of the parameters in the K&R definition 3473 // match the types in the prototype declaration, even when the 3474 // promoted types of the parameters from the K&R definition differ 3475 // from the types in the prototype. GCC then keeps the types from 3476 // the prototype. 3477 // 3478 // If a variadic prototype is followed by a non-variadic K&R definition, 3479 // the K&R definition becomes variadic. This is sort of an edge case, but 3480 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3481 // C99 6.9.1p8. 3482 if (!getLangOpts().CPlusPlus && 3483 Old->hasPrototype() && !New->hasPrototype() && 3484 New->getType()->getAs<FunctionProtoType>() && 3485 Old->getNumParams() == New->getNumParams()) { 3486 SmallVector<QualType, 16> ArgTypes; 3487 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3488 const FunctionProtoType *OldProto 3489 = Old->getType()->getAs<FunctionProtoType>(); 3490 const FunctionProtoType *NewProto 3491 = New->getType()->getAs<FunctionProtoType>(); 3492 3493 // Determine whether this is the GNU C extension. 3494 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3495 NewProto->getReturnType()); 3496 bool LooseCompatible = !MergedReturn.isNull(); 3497 for (unsigned Idx = 0, End = Old->getNumParams(); 3498 LooseCompatible && Idx != End; ++Idx) { 3499 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3500 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3501 if (Context.typesAreCompatible(OldParm->getType(), 3502 NewProto->getParamType(Idx))) { 3503 ArgTypes.push_back(NewParm->getType()); 3504 } else if (Context.typesAreCompatible(OldParm->getType(), 3505 NewParm->getType(), 3506 /*CompareUnqualified=*/true)) { 3507 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3508 NewProto->getParamType(Idx) }; 3509 Warnings.push_back(Warn); 3510 ArgTypes.push_back(NewParm->getType()); 3511 } else 3512 LooseCompatible = false; 3513 } 3514 3515 if (LooseCompatible) { 3516 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3517 Diag(Warnings[Warn].NewParm->getLocation(), 3518 diag::ext_param_promoted_not_compatible_with_prototype) 3519 << Warnings[Warn].PromotedType 3520 << Warnings[Warn].OldParm->getType(); 3521 if (Warnings[Warn].OldParm->getLocation().isValid()) 3522 Diag(Warnings[Warn].OldParm->getLocation(), 3523 diag::note_previous_declaration); 3524 } 3525 3526 if (MergeTypeWithOld) 3527 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3528 OldProto->getExtProtoInfo())); 3529 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3530 } 3531 3532 // Fall through to diagnose conflicting types. 3533 } 3534 3535 // A function that has already been declared has been redeclared or 3536 // defined with a different type; show an appropriate diagnostic. 3537 3538 // If the previous declaration was an implicitly-generated builtin 3539 // declaration, then at the very least we should use a specialized note. 3540 unsigned BuiltinID; 3541 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3542 // If it's actually a library-defined builtin function like 'malloc' 3543 // or 'printf', just warn about the incompatible redeclaration. 3544 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3545 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3546 Diag(OldLocation, diag::note_previous_builtin_declaration) 3547 << Old << Old->getType(); 3548 3549 // If this is a global redeclaration, just forget hereafter 3550 // about the "builtin-ness" of the function. 3551 // 3552 // Doing this for local extern declarations is problematic. If 3553 // the builtin declaration remains visible, a second invalid 3554 // local declaration will produce a hard error; if it doesn't 3555 // remain visible, a single bogus local redeclaration (which is 3556 // actually only a warning) could break all the downstream code. 3557 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3558 New->getIdentifier()->revertBuiltin(); 3559 3560 return false; 3561 } 3562 3563 PrevDiag = diag::note_previous_builtin_declaration; 3564 } 3565 3566 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3567 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3568 return true; 3569 } 3570 3571 /// Completes the merge of two function declarations that are 3572 /// known to be compatible. 3573 /// 3574 /// This routine handles the merging of attributes and other 3575 /// properties of function declarations from the old declaration to 3576 /// the new declaration, once we know that New is in fact a 3577 /// redeclaration of Old. 3578 /// 3579 /// \returns false 3580 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3581 Scope *S, bool MergeTypeWithOld) { 3582 // Merge the attributes 3583 mergeDeclAttributes(New, Old); 3584 3585 // Merge "pure" flag. 3586 if (Old->isPure()) 3587 New->setPure(); 3588 3589 // Merge "used" flag. 3590 if (Old->getMostRecentDecl()->isUsed(false)) 3591 New->setIsUsed(); 3592 3593 // Merge attributes from the parameters. These can mismatch with K&R 3594 // declarations. 3595 if (New->getNumParams() == Old->getNumParams()) 3596 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3597 ParmVarDecl *NewParam = New->getParamDecl(i); 3598 ParmVarDecl *OldParam = Old->getParamDecl(i); 3599 mergeParamDeclAttributes(NewParam, OldParam, *this); 3600 mergeParamDeclTypes(NewParam, OldParam, *this); 3601 } 3602 3603 if (getLangOpts().CPlusPlus) 3604 return MergeCXXFunctionDecl(New, Old, S); 3605 3606 // Merge the function types so the we get the composite types for the return 3607 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3608 // was visible. 3609 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3610 if (!Merged.isNull() && MergeTypeWithOld) 3611 New->setType(Merged); 3612 3613 return false; 3614 } 3615 3616 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3617 ObjCMethodDecl *oldMethod) { 3618 // Merge the attributes, including deprecated/unavailable 3619 AvailabilityMergeKind MergeKind = 3620 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3621 ? AMK_ProtocolImplementation 3622 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3623 : AMK_Override; 3624 3625 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3626 3627 // Merge attributes from the parameters. 3628 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3629 oe = oldMethod->param_end(); 3630 for (ObjCMethodDecl::param_iterator 3631 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3632 ni != ne && oi != oe; ++ni, ++oi) 3633 mergeParamDeclAttributes(*ni, *oi, *this); 3634 3635 CheckObjCMethodOverride(newMethod, oldMethod); 3636 } 3637 3638 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3639 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3640 3641 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3642 ? diag::err_redefinition_different_type 3643 : diag::err_redeclaration_different_type) 3644 << New->getDeclName() << New->getType() << Old->getType(); 3645 3646 diag::kind PrevDiag; 3647 SourceLocation OldLocation; 3648 std::tie(PrevDiag, OldLocation) 3649 = getNoteDiagForInvalidRedeclaration(Old, New); 3650 S.Diag(OldLocation, PrevDiag); 3651 New->setInvalidDecl(); 3652 } 3653 3654 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3655 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3656 /// emitting diagnostics as appropriate. 3657 /// 3658 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3659 /// to here in AddInitializerToDecl. We can't check them before the initializer 3660 /// is attached. 3661 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3662 bool MergeTypeWithOld) { 3663 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3664 return; 3665 3666 QualType MergedT; 3667 if (getLangOpts().CPlusPlus) { 3668 if (New->getType()->isUndeducedType()) { 3669 // We don't know what the new type is until the initializer is attached. 3670 return; 3671 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3672 // These could still be something that needs exception specs checked. 3673 return MergeVarDeclExceptionSpecs(New, Old); 3674 } 3675 // C++ [basic.link]p10: 3676 // [...] the types specified by all declarations referring to a given 3677 // object or function shall be identical, except that declarations for an 3678 // array object can specify array types that differ by the presence or 3679 // absence of a major array bound (8.3.4). 3680 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3681 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3682 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3683 3684 // We are merging a variable declaration New into Old. If it has an array 3685 // bound, and that bound differs from Old's bound, we should diagnose the 3686 // mismatch. 3687 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3688 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3689 PrevVD = PrevVD->getPreviousDecl()) { 3690 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3691 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3692 continue; 3693 3694 if (!Context.hasSameType(NewArray, PrevVDTy)) 3695 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3696 } 3697 } 3698 3699 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3700 if (Context.hasSameType(OldArray->getElementType(), 3701 NewArray->getElementType())) 3702 MergedT = New->getType(); 3703 } 3704 // FIXME: Check visibility. New is hidden but has a complete type. If New 3705 // has no array bound, it should not inherit one from Old, if Old is not 3706 // visible. 3707 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3708 if (Context.hasSameType(OldArray->getElementType(), 3709 NewArray->getElementType())) 3710 MergedT = Old->getType(); 3711 } 3712 } 3713 else if (New->getType()->isObjCObjectPointerType() && 3714 Old->getType()->isObjCObjectPointerType()) { 3715 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3716 Old->getType()); 3717 } 3718 } else { 3719 // C 6.2.7p2: 3720 // All declarations that refer to the same object or function shall have 3721 // compatible type. 3722 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3723 } 3724 if (MergedT.isNull()) { 3725 // It's OK if we couldn't merge types if either type is dependent, for a 3726 // block-scope variable. In other cases (static data members of class 3727 // templates, variable templates, ...), we require the types to be 3728 // equivalent. 3729 // FIXME: The C++ standard doesn't say anything about this. 3730 if ((New->getType()->isDependentType() || 3731 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3732 // If the old type was dependent, we can't merge with it, so the new type 3733 // becomes dependent for now. We'll reproduce the original type when we 3734 // instantiate the TypeSourceInfo for the variable. 3735 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3736 New->setType(Context.DependentTy); 3737 return; 3738 } 3739 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3740 } 3741 3742 // Don't actually update the type on the new declaration if the old 3743 // declaration was an extern declaration in a different scope. 3744 if (MergeTypeWithOld) 3745 New->setType(MergedT); 3746 } 3747 3748 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3749 LookupResult &Previous) { 3750 // C11 6.2.7p4: 3751 // For an identifier with internal or external linkage declared 3752 // in a scope in which a prior declaration of that identifier is 3753 // visible, if the prior declaration specifies internal or 3754 // external linkage, the type of the identifier at the later 3755 // declaration becomes the composite type. 3756 // 3757 // If the variable isn't visible, we do not merge with its type. 3758 if (Previous.isShadowed()) 3759 return false; 3760 3761 if (S.getLangOpts().CPlusPlus) { 3762 // C++11 [dcl.array]p3: 3763 // If there is a preceding declaration of the entity in the same 3764 // scope in which the bound was specified, an omitted array bound 3765 // is taken to be the same as in that earlier declaration. 3766 return NewVD->isPreviousDeclInSameBlockScope() || 3767 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3768 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3769 } else { 3770 // If the old declaration was function-local, don't merge with its 3771 // type unless we're in the same function. 3772 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3773 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3774 } 3775 } 3776 3777 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3778 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3779 /// situation, merging decls or emitting diagnostics as appropriate. 3780 /// 3781 /// Tentative definition rules (C99 6.9.2p2) are checked by 3782 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3783 /// definitions here, since the initializer hasn't been attached. 3784 /// 3785 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3786 // If the new decl is already invalid, don't do any other checking. 3787 if (New->isInvalidDecl()) 3788 return; 3789 3790 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3791 return; 3792 3793 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3794 3795 // Verify the old decl was also a variable or variable template. 3796 VarDecl *Old = nullptr; 3797 VarTemplateDecl *OldTemplate = nullptr; 3798 if (Previous.isSingleResult()) { 3799 if (NewTemplate) { 3800 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3801 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3802 3803 if (auto *Shadow = 3804 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3805 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3806 return New->setInvalidDecl(); 3807 } else { 3808 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3809 3810 if (auto *Shadow = 3811 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3812 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3813 return New->setInvalidDecl(); 3814 } 3815 } 3816 if (!Old) { 3817 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3818 << New->getDeclName(); 3819 notePreviousDefinition(Previous.getRepresentativeDecl(), 3820 New->getLocation()); 3821 return New->setInvalidDecl(); 3822 } 3823 3824 // Ensure the template parameters are compatible. 3825 if (NewTemplate && 3826 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3827 OldTemplate->getTemplateParameters(), 3828 /*Complain=*/true, TPL_TemplateMatch)) 3829 return New->setInvalidDecl(); 3830 3831 // C++ [class.mem]p1: 3832 // A member shall not be declared twice in the member-specification [...] 3833 // 3834 // Here, we need only consider static data members. 3835 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3836 Diag(New->getLocation(), diag::err_duplicate_member) 3837 << New->getIdentifier(); 3838 Diag(Old->getLocation(), diag::note_previous_declaration); 3839 New->setInvalidDecl(); 3840 } 3841 3842 mergeDeclAttributes(New, Old); 3843 // Warn if an already-declared variable is made a weak_import in a subsequent 3844 // declaration 3845 if (New->hasAttr<WeakImportAttr>() && 3846 Old->getStorageClass() == SC_None && 3847 !Old->hasAttr<WeakImportAttr>()) { 3848 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3849 notePreviousDefinition(Old, New->getLocation()); 3850 // Remove weak_import attribute on new declaration. 3851 New->dropAttr<WeakImportAttr>(); 3852 } 3853 3854 if (New->hasAttr<InternalLinkageAttr>() && 3855 !Old->hasAttr<InternalLinkageAttr>()) { 3856 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3857 << New->getDeclName(); 3858 notePreviousDefinition(Old, New->getLocation()); 3859 New->dropAttr<InternalLinkageAttr>(); 3860 } 3861 3862 // Merge the types. 3863 VarDecl *MostRecent = Old->getMostRecentDecl(); 3864 if (MostRecent != Old) { 3865 MergeVarDeclTypes(New, MostRecent, 3866 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3867 if (New->isInvalidDecl()) 3868 return; 3869 } 3870 3871 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3872 if (New->isInvalidDecl()) 3873 return; 3874 3875 diag::kind PrevDiag; 3876 SourceLocation OldLocation; 3877 std::tie(PrevDiag, OldLocation) = 3878 getNoteDiagForInvalidRedeclaration(Old, New); 3879 3880 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3881 if (New->getStorageClass() == SC_Static && 3882 !New->isStaticDataMember() && 3883 Old->hasExternalFormalLinkage()) { 3884 if (getLangOpts().MicrosoftExt) { 3885 Diag(New->getLocation(), diag::ext_static_non_static) 3886 << New->getDeclName(); 3887 Diag(OldLocation, PrevDiag); 3888 } else { 3889 Diag(New->getLocation(), diag::err_static_non_static) 3890 << New->getDeclName(); 3891 Diag(OldLocation, PrevDiag); 3892 return New->setInvalidDecl(); 3893 } 3894 } 3895 // C99 6.2.2p4: 3896 // For an identifier declared with the storage-class specifier 3897 // extern in a scope in which a prior declaration of that 3898 // identifier is visible,23) if the prior declaration specifies 3899 // internal or external linkage, the linkage of the identifier at 3900 // the later declaration is the same as the linkage specified at 3901 // the prior declaration. If no prior declaration is visible, or 3902 // if the prior declaration specifies no linkage, then the 3903 // identifier has external linkage. 3904 if (New->hasExternalStorage() && Old->hasLinkage()) 3905 /* Okay */; 3906 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3907 !New->isStaticDataMember() && 3908 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3909 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3910 Diag(OldLocation, PrevDiag); 3911 return New->setInvalidDecl(); 3912 } 3913 3914 // Check if extern is followed by non-extern and vice-versa. 3915 if (New->hasExternalStorage() && 3916 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3917 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3918 Diag(OldLocation, PrevDiag); 3919 return New->setInvalidDecl(); 3920 } 3921 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3922 !New->hasExternalStorage()) { 3923 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3924 Diag(OldLocation, PrevDiag); 3925 return New->setInvalidDecl(); 3926 } 3927 3928 if (CheckRedeclarationModuleOwnership(New, Old)) 3929 return; 3930 3931 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3932 3933 // FIXME: The test for external storage here seems wrong? We still 3934 // need to check for mismatches. 3935 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3936 // Don't complain about out-of-line definitions of static members. 3937 !(Old->getLexicalDeclContext()->isRecord() && 3938 !New->getLexicalDeclContext()->isRecord())) { 3939 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3940 Diag(OldLocation, PrevDiag); 3941 return New->setInvalidDecl(); 3942 } 3943 3944 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3945 if (VarDecl *Def = Old->getDefinition()) { 3946 // C++1z [dcl.fcn.spec]p4: 3947 // If the definition of a variable appears in a translation unit before 3948 // its first declaration as inline, the program is ill-formed. 3949 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3950 Diag(Def->getLocation(), diag::note_previous_definition); 3951 } 3952 } 3953 3954 // If this redeclaration makes the variable inline, we may need to add it to 3955 // UndefinedButUsed. 3956 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3957 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3958 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3959 SourceLocation())); 3960 3961 if (New->getTLSKind() != Old->getTLSKind()) { 3962 if (!Old->getTLSKind()) { 3963 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3964 Diag(OldLocation, PrevDiag); 3965 } else if (!New->getTLSKind()) { 3966 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3967 Diag(OldLocation, PrevDiag); 3968 } else { 3969 // Do not allow redeclaration to change the variable between requiring 3970 // static and dynamic initialization. 3971 // FIXME: GCC allows this, but uses the TLS keyword on the first 3972 // declaration to determine the kind. Do we need to be compatible here? 3973 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3974 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3975 Diag(OldLocation, PrevDiag); 3976 } 3977 } 3978 3979 // C++ doesn't have tentative definitions, so go right ahead and check here. 3980 if (getLangOpts().CPlusPlus && 3981 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3982 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3983 Old->getCanonicalDecl()->isConstexpr()) { 3984 // This definition won't be a definition any more once it's been merged. 3985 Diag(New->getLocation(), 3986 diag::warn_deprecated_redundant_constexpr_static_def); 3987 } else if (VarDecl *Def = Old->getDefinition()) { 3988 if (checkVarDeclRedefinition(Def, New)) 3989 return; 3990 } 3991 } 3992 3993 if (haveIncompatibleLanguageLinkages(Old, New)) { 3994 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3995 Diag(OldLocation, PrevDiag); 3996 New->setInvalidDecl(); 3997 return; 3998 } 3999 4000 // Merge "used" flag. 4001 if (Old->getMostRecentDecl()->isUsed(false)) 4002 New->setIsUsed(); 4003 4004 // Keep a chain of previous declarations. 4005 New->setPreviousDecl(Old); 4006 if (NewTemplate) 4007 NewTemplate->setPreviousDecl(OldTemplate); 4008 adjustDeclContextForDeclaratorDecl(New, Old); 4009 4010 // Inherit access appropriately. 4011 New->setAccess(Old->getAccess()); 4012 if (NewTemplate) 4013 NewTemplate->setAccess(New->getAccess()); 4014 4015 if (Old->isInline()) 4016 New->setImplicitlyInline(); 4017 } 4018 4019 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4020 SourceManager &SrcMgr = getSourceManager(); 4021 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4022 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4023 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4024 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4025 auto &HSI = PP.getHeaderSearchInfo(); 4026 StringRef HdrFilename = 4027 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4028 4029 auto noteFromModuleOrInclude = [&](Module *Mod, 4030 SourceLocation IncLoc) -> bool { 4031 // Redefinition errors with modules are common with non modular mapped 4032 // headers, example: a non-modular header H in module A that also gets 4033 // included directly in a TU. Pointing twice to the same header/definition 4034 // is confusing, try to get better diagnostics when modules is on. 4035 if (IncLoc.isValid()) { 4036 if (Mod) { 4037 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4038 << HdrFilename.str() << Mod->getFullModuleName(); 4039 if (!Mod->DefinitionLoc.isInvalid()) 4040 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4041 << Mod->getFullModuleName(); 4042 } else { 4043 Diag(IncLoc, diag::note_redefinition_include_same_file) 4044 << HdrFilename.str(); 4045 } 4046 return true; 4047 } 4048 4049 return false; 4050 }; 4051 4052 // Is it the same file and same offset? Provide more information on why 4053 // this leads to a redefinition error. 4054 bool EmittedDiag = false; 4055 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4056 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4057 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4058 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4059 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4060 4061 // If the header has no guards, emit a note suggesting one. 4062 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4063 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4064 4065 if (EmittedDiag) 4066 return; 4067 } 4068 4069 // Redefinition coming from different files or couldn't do better above. 4070 if (Old->getLocation().isValid()) 4071 Diag(Old->getLocation(), diag::note_previous_definition); 4072 } 4073 4074 /// We've just determined that \p Old and \p New both appear to be definitions 4075 /// of the same variable. Either diagnose or fix the problem. 4076 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4077 if (!hasVisibleDefinition(Old) && 4078 (New->getFormalLinkage() == InternalLinkage || 4079 New->isInline() || 4080 New->getDescribedVarTemplate() || 4081 New->getNumTemplateParameterLists() || 4082 New->getDeclContext()->isDependentContext())) { 4083 // The previous definition is hidden, and multiple definitions are 4084 // permitted (in separate TUs). Demote this to a declaration. 4085 New->demoteThisDefinitionToDeclaration(); 4086 4087 // Make the canonical definition visible. 4088 if (auto *OldTD = Old->getDescribedVarTemplate()) 4089 makeMergedDefinitionVisible(OldTD); 4090 makeMergedDefinitionVisible(Old); 4091 return false; 4092 } else { 4093 Diag(New->getLocation(), diag::err_redefinition) << New; 4094 notePreviousDefinition(Old, New->getLocation()); 4095 New->setInvalidDecl(); 4096 return true; 4097 } 4098 } 4099 4100 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4101 /// no declarator (e.g. "struct foo;") is parsed. 4102 Decl * 4103 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4104 RecordDecl *&AnonRecord) { 4105 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4106 AnonRecord); 4107 } 4108 4109 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4110 // disambiguate entities defined in different scopes. 4111 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4112 // compatibility. 4113 // We will pick our mangling number depending on which version of MSVC is being 4114 // targeted. 4115 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4116 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4117 ? S->getMSCurManglingNumber() 4118 : S->getMSLastManglingNumber(); 4119 } 4120 4121 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4122 if (!Context.getLangOpts().CPlusPlus) 4123 return; 4124 4125 if (isa<CXXRecordDecl>(Tag->getParent())) { 4126 // If this tag is the direct child of a class, number it if 4127 // it is anonymous. 4128 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4129 return; 4130 MangleNumberingContext &MCtx = 4131 Context.getManglingNumberContext(Tag->getParent()); 4132 Context.setManglingNumber( 4133 Tag, MCtx.getManglingNumber( 4134 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4135 return; 4136 } 4137 4138 // If this tag isn't a direct child of a class, number it if it is local. 4139 Decl *ManglingContextDecl; 4140 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4141 Tag->getDeclContext(), ManglingContextDecl)) { 4142 Context.setManglingNumber( 4143 Tag, MCtx->getManglingNumber( 4144 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4145 } 4146 } 4147 4148 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4149 TypedefNameDecl *NewTD) { 4150 if (TagFromDeclSpec->isInvalidDecl()) 4151 return; 4152 4153 // Do nothing if the tag already has a name for linkage purposes. 4154 if (TagFromDeclSpec->hasNameForLinkage()) 4155 return; 4156 4157 // A well-formed anonymous tag must always be a TUK_Definition. 4158 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4159 4160 // The type must match the tag exactly; no qualifiers allowed. 4161 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4162 Context.getTagDeclType(TagFromDeclSpec))) { 4163 if (getLangOpts().CPlusPlus) 4164 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4165 return; 4166 } 4167 4168 // If we've already computed linkage for the anonymous tag, then 4169 // adding a typedef name for the anonymous decl can change that 4170 // linkage, which might be a serious problem. Diagnose this as 4171 // unsupported and ignore the typedef name. TODO: we should 4172 // pursue this as a language defect and establish a formal rule 4173 // for how to handle it. 4174 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4175 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4176 4177 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4178 tagLoc = getLocForEndOfToken(tagLoc); 4179 4180 llvm::SmallString<40> textToInsert; 4181 textToInsert += ' '; 4182 textToInsert += NewTD->getIdentifier()->getName(); 4183 Diag(tagLoc, diag::note_typedef_changes_linkage) 4184 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4185 return; 4186 } 4187 4188 // Otherwise, set this is the anon-decl typedef for the tag. 4189 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4190 } 4191 4192 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4193 switch (T) { 4194 case DeclSpec::TST_class: 4195 return 0; 4196 case DeclSpec::TST_struct: 4197 return 1; 4198 case DeclSpec::TST_interface: 4199 return 2; 4200 case DeclSpec::TST_union: 4201 return 3; 4202 case DeclSpec::TST_enum: 4203 return 4; 4204 default: 4205 llvm_unreachable("unexpected type specifier"); 4206 } 4207 } 4208 4209 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4210 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4211 /// parameters to cope with template friend declarations. 4212 Decl * 4213 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4214 MultiTemplateParamsArg TemplateParams, 4215 bool IsExplicitInstantiation, 4216 RecordDecl *&AnonRecord) { 4217 Decl *TagD = nullptr; 4218 TagDecl *Tag = nullptr; 4219 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4220 DS.getTypeSpecType() == DeclSpec::TST_struct || 4221 DS.getTypeSpecType() == DeclSpec::TST_interface || 4222 DS.getTypeSpecType() == DeclSpec::TST_union || 4223 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4224 TagD = DS.getRepAsDecl(); 4225 4226 if (!TagD) // We probably had an error 4227 return nullptr; 4228 4229 // Note that the above type specs guarantee that the 4230 // type rep is a Decl, whereas in many of the others 4231 // it's a Type. 4232 if (isa<TagDecl>(TagD)) 4233 Tag = cast<TagDecl>(TagD); 4234 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4235 Tag = CTD->getTemplatedDecl(); 4236 } 4237 4238 if (Tag) { 4239 handleTagNumbering(Tag, S); 4240 Tag->setFreeStanding(); 4241 if (Tag->isInvalidDecl()) 4242 return Tag; 4243 } 4244 4245 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4246 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4247 // or incomplete types shall not be restrict-qualified." 4248 if (TypeQuals & DeclSpec::TQ_restrict) 4249 Diag(DS.getRestrictSpecLoc(), 4250 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4251 << DS.getSourceRange(); 4252 } 4253 4254 if (DS.isInlineSpecified()) 4255 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4256 << getLangOpts().CPlusPlus17; 4257 4258 if (DS.isConstexprSpecified()) { 4259 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4260 // and definitions of functions and variables. 4261 if (Tag) 4262 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4263 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4264 else 4265 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4266 // Don't emit warnings after this error. 4267 return TagD; 4268 } 4269 4270 DiagnoseFunctionSpecifiers(DS); 4271 4272 if (DS.isFriendSpecified()) { 4273 // If we're dealing with a decl but not a TagDecl, assume that 4274 // whatever routines created it handled the friendship aspect. 4275 if (TagD && !Tag) 4276 return nullptr; 4277 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4278 } 4279 4280 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4281 bool IsExplicitSpecialization = 4282 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4283 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4284 !IsExplicitInstantiation && !IsExplicitSpecialization && 4285 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4286 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4287 // nested-name-specifier unless it is an explicit instantiation 4288 // or an explicit specialization. 4289 // 4290 // FIXME: We allow class template partial specializations here too, per the 4291 // obvious intent of DR1819. 4292 // 4293 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4294 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4295 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4296 return nullptr; 4297 } 4298 4299 // Track whether this decl-specifier declares anything. 4300 bool DeclaresAnything = true; 4301 4302 // Handle anonymous struct definitions. 4303 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4304 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4305 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4306 if (getLangOpts().CPlusPlus || 4307 Record->getDeclContext()->isRecord()) { 4308 // If CurContext is a DeclContext that can contain statements, 4309 // RecursiveASTVisitor won't visit the decls that 4310 // BuildAnonymousStructOrUnion() will put into CurContext. 4311 // Also store them here so that they can be part of the 4312 // DeclStmt that gets created in this case. 4313 // FIXME: Also return the IndirectFieldDecls created by 4314 // BuildAnonymousStructOr union, for the same reason? 4315 if (CurContext->isFunctionOrMethod()) 4316 AnonRecord = Record; 4317 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4318 Context.getPrintingPolicy()); 4319 } 4320 4321 DeclaresAnything = false; 4322 } 4323 } 4324 4325 // C11 6.7.2.1p2: 4326 // A struct-declaration that does not declare an anonymous structure or 4327 // anonymous union shall contain a struct-declarator-list. 4328 // 4329 // This rule also existed in C89 and C99; the grammar for struct-declaration 4330 // did not permit a struct-declaration without a struct-declarator-list. 4331 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4332 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4333 // Check for Microsoft C extension: anonymous struct/union member. 4334 // Handle 2 kinds of anonymous struct/union: 4335 // struct STRUCT; 4336 // union UNION; 4337 // and 4338 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4339 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4340 if ((Tag && Tag->getDeclName()) || 4341 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4342 RecordDecl *Record = nullptr; 4343 if (Tag) 4344 Record = dyn_cast<RecordDecl>(Tag); 4345 else if (const RecordType *RT = 4346 DS.getRepAsType().get()->getAsStructureType()) 4347 Record = RT->getDecl(); 4348 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4349 Record = UT->getDecl(); 4350 4351 if (Record && getLangOpts().MicrosoftExt) { 4352 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4353 << Record->isUnion() << DS.getSourceRange(); 4354 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4355 } 4356 4357 DeclaresAnything = false; 4358 } 4359 } 4360 4361 // Skip all the checks below if we have a type error. 4362 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4363 (TagD && TagD->isInvalidDecl())) 4364 return TagD; 4365 4366 if (getLangOpts().CPlusPlus && 4367 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4368 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4369 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4370 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4371 DeclaresAnything = false; 4372 4373 if (!DS.isMissingDeclaratorOk()) { 4374 // Customize diagnostic for a typedef missing a name. 4375 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4376 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4377 << DS.getSourceRange(); 4378 else 4379 DeclaresAnything = false; 4380 } 4381 4382 if (DS.isModulePrivateSpecified() && 4383 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4384 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4385 << Tag->getTagKind() 4386 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4387 4388 ActOnDocumentableDecl(TagD); 4389 4390 // C 6.7/2: 4391 // A declaration [...] shall declare at least a declarator [...], a tag, 4392 // or the members of an enumeration. 4393 // C++ [dcl.dcl]p3: 4394 // [If there are no declarators], and except for the declaration of an 4395 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4396 // names into the program, or shall redeclare a name introduced by a 4397 // previous declaration. 4398 if (!DeclaresAnything) { 4399 // In C, we allow this as a (popular) extension / bug. Don't bother 4400 // producing further diagnostics for redundant qualifiers after this. 4401 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4402 return TagD; 4403 } 4404 4405 // C++ [dcl.stc]p1: 4406 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4407 // init-declarator-list of the declaration shall not be empty. 4408 // C++ [dcl.fct.spec]p1: 4409 // If a cv-qualifier appears in a decl-specifier-seq, the 4410 // init-declarator-list of the declaration shall not be empty. 4411 // 4412 // Spurious qualifiers here appear to be valid in C. 4413 unsigned DiagID = diag::warn_standalone_specifier; 4414 if (getLangOpts().CPlusPlus) 4415 DiagID = diag::ext_standalone_specifier; 4416 4417 // Note that a linkage-specification sets a storage class, but 4418 // 'extern "C" struct foo;' is actually valid and not theoretically 4419 // useless. 4420 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4421 if (SCS == DeclSpec::SCS_mutable) 4422 // Since mutable is not a viable storage class specifier in C, there is 4423 // no reason to treat it as an extension. Instead, diagnose as an error. 4424 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4425 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4426 Diag(DS.getStorageClassSpecLoc(), DiagID) 4427 << DeclSpec::getSpecifierName(SCS); 4428 } 4429 4430 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4431 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4432 << DeclSpec::getSpecifierName(TSCS); 4433 if (DS.getTypeQualifiers()) { 4434 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4435 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4436 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4437 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4438 // Restrict is covered above. 4439 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4440 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4441 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4442 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4443 } 4444 4445 // Warn about ignored type attributes, for example: 4446 // __attribute__((aligned)) struct A; 4447 // Attributes should be placed after tag to apply to type declaration. 4448 if (!DS.getAttributes().empty()) { 4449 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4450 if (TypeSpecType == DeclSpec::TST_class || 4451 TypeSpecType == DeclSpec::TST_struct || 4452 TypeSpecType == DeclSpec::TST_interface || 4453 TypeSpecType == DeclSpec::TST_union || 4454 TypeSpecType == DeclSpec::TST_enum) { 4455 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4456 attrs = attrs->getNext()) 4457 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4458 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4459 } 4460 } 4461 4462 return TagD; 4463 } 4464 4465 /// We are trying to inject an anonymous member into the given scope; 4466 /// check if there's an existing declaration that can't be overloaded. 4467 /// 4468 /// \return true if this is a forbidden redeclaration 4469 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4470 Scope *S, 4471 DeclContext *Owner, 4472 DeclarationName Name, 4473 SourceLocation NameLoc, 4474 bool IsUnion) { 4475 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4476 Sema::ForVisibleRedeclaration); 4477 if (!SemaRef.LookupName(R, S)) return false; 4478 4479 // Pick a representative declaration. 4480 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4481 assert(PrevDecl && "Expected a non-null Decl"); 4482 4483 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4484 return false; 4485 4486 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4487 << IsUnion << Name; 4488 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4489 4490 return true; 4491 } 4492 4493 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4494 /// anonymous struct or union AnonRecord into the owning context Owner 4495 /// and scope S. This routine will be invoked just after we realize 4496 /// that an unnamed union or struct is actually an anonymous union or 4497 /// struct, e.g., 4498 /// 4499 /// @code 4500 /// union { 4501 /// int i; 4502 /// float f; 4503 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4504 /// // f into the surrounding scope.x 4505 /// @endcode 4506 /// 4507 /// This routine is recursive, injecting the names of nested anonymous 4508 /// structs/unions into the owning context and scope as well. 4509 static bool 4510 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4511 RecordDecl *AnonRecord, AccessSpecifier AS, 4512 SmallVectorImpl<NamedDecl *> &Chaining) { 4513 bool Invalid = false; 4514 4515 // Look every FieldDecl and IndirectFieldDecl with a name. 4516 for (auto *D : AnonRecord->decls()) { 4517 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4518 cast<NamedDecl>(D)->getDeclName()) { 4519 ValueDecl *VD = cast<ValueDecl>(D); 4520 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4521 VD->getLocation(), 4522 AnonRecord->isUnion())) { 4523 // C++ [class.union]p2: 4524 // The names of the members of an anonymous union shall be 4525 // distinct from the names of any other entity in the 4526 // scope in which the anonymous union is declared. 4527 Invalid = true; 4528 } else { 4529 // C++ [class.union]p2: 4530 // For the purpose of name lookup, after the anonymous union 4531 // definition, the members of the anonymous union are 4532 // considered to have been defined in the scope in which the 4533 // anonymous union is declared. 4534 unsigned OldChainingSize = Chaining.size(); 4535 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4536 Chaining.append(IF->chain_begin(), IF->chain_end()); 4537 else 4538 Chaining.push_back(VD); 4539 4540 assert(Chaining.size() >= 2); 4541 NamedDecl **NamedChain = 4542 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4543 for (unsigned i = 0; i < Chaining.size(); i++) 4544 NamedChain[i] = Chaining[i]; 4545 4546 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4547 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4548 VD->getType(), {NamedChain, Chaining.size()}); 4549 4550 for (const auto *Attr : VD->attrs()) 4551 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4552 4553 IndirectField->setAccess(AS); 4554 IndirectField->setImplicit(); 4555 SemaRef.PushOnScopeChains(IndirectField, S); 4556 4557 // That includes picking up the appropriate access specifier. 4558 if (AS != AS_none) IndirectField->setAccess(AS); 4559 4560 Chaining.resize(OldChainingSize); 4561 } 4562 } 4563 } 4564 4565 return Invalid; 4566 } 4567 4568 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4569 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4570 /// illegal input values are mapped to SC_None. 4571 static StorageClass 4572 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4573 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4574 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4575 "Parser allowed 'typedef' as storage class VarDecl."); 4576 switch (StorageClassSpec) { 4577 case DeclSpec::SCS_unspecified: return SC_None; 4578 case DeclSpec::SCS_extern: 4579 if (DS.isExternInLinkageSpec()) 4580 return SC_None; 4581 return SC_Extern; 4582 case DeclSpec::SCS_static: return SC_Static; 4583 case DeclSpec::SCS_auto: return SC_Auto; 4584 case DeclSpec::SCS_register: return SC_Register; 4585 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4586 // Illegal SCSs map to None: error reporting is up to the caller. 4587 case DeclSpec::SCS_mutable: // Fall through. 4588 case DeclSpec::SCS_typedef: return SC_None; 4589 } 4590 llvm_unreachable("unknown storage class specifier"); 4591 } 4592 4593 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4594 assert(Record->hasInClassInitializer()); 4595 4596 for (const auto *I : Record->decls()) { 4597 const auto *FD = dyn_cast<FieldDecl>(I); 4598 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4599 FD = IFD->getAnonField(); 4600 if (FD && FD->hasInClassInitializer()) 4601 return FD->getLocation(); 4602 } 4603 4604 llvm_unreachable("couldn't find in-class initializer"); 4605 } 4606 4607 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4608 SourceLocation DefaultInitLoc) { 4609 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4610 return; 4611 4612 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4613 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4614 } 4615 4616 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4617 CXXRecordDecl *AnonUnion) { 4618 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4619 return; 4620 4621 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4622 } 4623 4624 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4625 /// anonymous structure or union. Anonymous unions are a C++ feature 4626 /// (C++ [class.union]) and a C11 feature; anonymous structures 4627 /// are a C11 feature and GNU C++ extension. 4628 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4629 AccessSpecifier AS, 4630 RecordDecl *Record, 4631 const PrintingPolicy &Policy) { 4632 DeclContext *Owner = Record->getDeclContext(); 4633 4634 // Diagnose whether this anonymous struct/union is an extension. 4635 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4636 Diag(Record->getLocation(), diag::ext_anonymous_union); 4637 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4638 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4639 else if (!Record->isUnion() && !getLangOpts().C11) 4640 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4641 4642 // C and C++ require different kinds of checks for anonymous 4643 // structs/unions. 4644 bool Invalid = false; 4645 if (getLangOpts().CPlusPlus) { 4646 const char *PrevSpec = nullptr; 4647 unsigned DiagID; 4648 if (Record->isUnion()) { 4649 // C++ [class.union]p6: 4650 // Anonymous unions declared in a named namespace or in the 4651 // global namespace shall be declared static. 4652 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4653 (isa<TranslationUnitDecl>(Owner) || 4654 (isa<NamespaceDecl>(Owner) && 4655 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4656 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4657 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4658 4659 // Recover by adding 'static'. 4660 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4661 PrevSpec, DiagID, Policy); 4662 } 4663 // C++ [class.union]p6: 4664 // A storage class is not allowed in a declaration of an 4665 // anonymous union in a class scope. 4666 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4667 isa<RecordDecl>(Owner)) { 4668 Diag(DS.getStorageClassSpecLoc(), 4669 diag::err_anonymous_union_with_storage_spec) 4670 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4671 4672 // Recover by removing the storage specifier. 4673 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4674 SourceLocation(), 4675 PrevSpec, DiagID, Context.getPrintingPolicy()); 4676 } 4677 } 4678 4679 // Ignore const/volatile/restrict qualifiers. 4680 if (DS.getTypeQualifiers()) { 4681 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4682 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4683 << Record->isUnion() << "const" 4684 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4685 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4686 Diag(DS.getVolatileSpecLoc(), 4687 diag::ext_anonymous_struct_union_qualified) 4688 << Record->isUnion() << "volatile" 4689 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4690 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4691 Diag(DS.getRestrictSpecLoc(), 4692 diag::ext_anonymous_struct_union_qualified) 4693 << Record->isUnion() << "restrict" 4694 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4695 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4696 Diag(DS.getAtomicSpecLoc(), 4697 diag::ext_anonymous_struct_union_qualified) 4698 << Record->isUnion() << "_Atomic" 4699 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4700 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4701 Diag(DS.getUnalignedSpecLoc(), 4702 diag::ext_anonymous_struct_union_qualified) 4703 << Record->isUnion() << "__unaligned" 4704 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4705 4706 DS.ClearTypeQualifiers(); 4707 } 4708 4709 // C++ [class.union]p2: 4710 // The member-specification of an anonymous union shall only 4711 // define non-static data members. [Note: nested types and 4712 // functions cannot be declared within an anonymous union. ] 4713 for (auto *Mem : Record->decls()) { 4714 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4715 // C++ [class.union]p3: 4716 // An anonymous union shall not have private or protected 4717 // members (clause 11). 4718 assert(FD->getAccess() != AS_none); 4719 if (FD->getAccess() != AS_public) { 4720 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4721 << Record->isUnion() << (FD->getAccess() == AS_protected); 4722 Invalid = true; 4723 } 4724 4725 // C++ [class.union]p1 4726 // An object of a class with a non-trivial constructor, a non-trivial 4727 // copy constructor, a non-trivial destructor, or a non-trivial copy 4728 // assignment operator cannot be a member of a union, nor can an 4729 // array of such objects. 4730 if (CheckNontrivialField(FD)) 4731 Invalid = true; 4732 } else if (Mem->isImplicit()) { 4733 // Any implicit members are fine. 4734 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4735 // This is a type that showed up in an 4736 // elaborated-type-specifier inside the anonymous struct or 4737 // union, but which actually declares a type outside of the 4738 // anonymous struct or union. It's okay. 4739 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4740 if (!MemRecord->isAnonymousStructOrUnion() && 4741 MemRecord->getDeclName()) { 4742 // Visual C++ allows type definition in anonymous struct or union. 4743 if (getLangOpts().MicrosoftExt) 4744 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4745 << Record->isUnion(); 4746 else { 4747 // This is a nested type declaration. 4748 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4749 << Record->isUnion(); 4750 Invalid = true; 4751 } 4752 } else { 4753 // This is an anonymous type definition within another anonymous type. 4754 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4755 // not part of standard C++. 4756 Diag(MemRecord->getLocation(), 4757 diag::ext_anonymous_record_with_anonymous_type) 4758 << Record->isUnion(); 4759 } 4760 } else if (isa<AccessSpecDecl>(Mem)) { 4761 // Any access specifier is fine. 4762 } else if (isa<StaticAssertDecl>(Mem)) { 4763 // In C++1z, static_assert declarations are also fine. 4764 } else { 4765 // We have something that isn't a non-static data 4766 // member. Complain about it. 4767 unsigned DK = diag::err_anonymous_record_bad_member; 4768 if (isa<TypeDecl>(Mem)) 4769 DK = diag::err_anonymous_record_with_type; 4770 else if (isa<FunctionDecl>(Mem)) 4771 DK = diag::err_anonymous_record_with_function; 4772 else if (isa<VarDecl>(Mem)) 4773 DK = diag::err_anonymous_record_with_static; 4774 4775 // Visual C++ allows type definition in anonymous struct or union. 4776 if (getLangOpts().MicrosoftExt && 4777 DK == diag::err_anonymous_record_with_type) 4778 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4779 << Record->isUnion(); 4780 else { 4781 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4782 Invalid = true; 4783 } 4784 } 4785 } 4786 4787 // C++11 [class.union]p8 (DR1460): 4788 // At most one variant member of a union may have a 4789 // brace-or-equal-initializer. 4790 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4791 Owner->isRecord()) 4792 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4793 cast<CXXRecordDecl>(Record)); 4794 } 4795 4796 if (!Record->isUnion() && !Owner->isRecord()) { 4797 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4798 << getLangOpts().CPlusPlus; 4799 Invalid = true; 4800 } 4801 4802 // Mock up a declarator. 4803 Declarator Dc(DS, DeclaratorContext::MemberContext); 4804 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4805 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4806 4807 // Create a declaration for this anonymous struct/union. 4808 NamedDecl *Anon = nullptr; 4809 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4810 Anon = FieldDecl::Create(Context, OwningClass, 4811 DS.getLocStart(), 4812 Record->getLocation(), 4813 /*IdentifierInfo=*/nullptr, 4814 Context.getTypeDeclType(Record), 4815 TInfo, 4816 /*BitWidth=*/nullptr, /*Mutable=*/false, 4817 /*InitStyle=*/ICIS_NoInit); 4818 Anon->setAccess(AS); 4819 if (getLangOpts().CPlusPlus) 4820 FieldCollector->Add(cast<FieldDecl>(Anon)); 4821 } else { 4822 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4823 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4824 if (SCSpec == DeclSpec::SCS_mutable) { 4825 // mutable can only appear on non-static class members, so it's always 4826 // an error here 4827 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4828 Invalid = true; 4829 SC = SC_None; 4830 } 4831 4832 Anon = VarDecl::Create(Context, Owner, 4833 DS.getLocStart(), 4834 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4835 Context.getTypeDeclType(Record), 4836 TInfo, SC); 4837 4838 // Default-initialize the implicit variable. This initialization will be 4839 // trivial in almost all cases, except if a union member has an in-class 4840 // initializer: 4841 // union { int n = 0; }; 4842 ActOnUninitializedDecl(Anon); 4843 } 4844 Anon->setImplicit(); 4845 4846 // Mark this as an anonymous struct/union type. 4847 Record->setAnonymousStructOrUnion(true); 4848 4849 // Add the anonymous struct/union object to the current 4850 // context. We'll be referencing this object when we refer to one of 4851 // its members. 4852 Owner->addDecl(Anon); 4853 4854 // Inject the members of the anonymous struct/union into the owning 4855 // context and into the identifier resolver chain for name lookup 4856 // purposes. 4857 SmallVector<NamedDecl*, 2> Chain; 4858 Chain.push_back(Anon); 4859 4860 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4861 Invalid = true; 4862 4863 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4864 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4865 Decl *ManglingContextDecl; 4866 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4867 NewVD->getDeclContext(), ManglingContextDecl)) { 4868 Context.setManglingNumber( 4869 NewVD, MCtx->getManglingNumber( 4870 NewVD, getMSManglingNumber(getLangOpts(), S))); 4871 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4872 } 4873 } 4874 } 4875 4876 if (Invalid) 4877 Anon->setInvalidDecl(); 4878 4879 return Anon; 4880 } 4881 4882 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4883 /// Microsoft C anonymous structure. 4884 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4885 /// Example: 4886 /// 4887 /// struct A { int a; }; 4888 /// struct B { struct A; int b; }; 4889 /// 4890 /// void foo() { 4891 /// B var; 4892 /// var.a = 3; 4893 /// } 4894 /// 4895 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4896 RecordDecl *Record) { 4897 assert(Record && "expected a record!"); 4898 4899 // Mock up a declarator. 4900 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4901 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4902 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4903 4904 auto *ParentDecl = cast<RecordDecl>(CurContext); 4905 QualType RecTy = Context.getTypeDeclType(Record); 4906 4907 // Create a declaration for this anonymous struct. 4908 NamedDecl *Anon = FieldDecl::Create(Context, 4909 ParentDecl, 4910 DS.getLocStart(), 4911 DS.getLocStart(), 4912 /*IdentifierInfo=*/nullptr, 4913 RecTy, 4914 TInfo, 4915 /*BitWidth=*/nullptr, /*Mutable=*/false, 4916 /*InitStyle=*/ICIS_NoInit); 4917 Anon->setImplicit(); 4918 4919 // Add the anonymous struct object to the current context. 4920 CurContext->addDecl(Anon); 4921 4922 // Inject the members of the anonymous struct into the current 4923 // context and into the identifier resolver chain for name lookup 4924 // purposes. 4925 SmallVector<NamedDecl*, 2> Chain; 4926 Chain.push_back(Anon); 4927 4928 RecordDecl *RecordDef = Record->getDefinition(); 4929 if (RequireCompleteType(Anon->getLocation(), RecTy, 4930 diag::err_field_incomplete) || 4931 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4932 AS_none, Chain)) { 4933 Anon->setInvalidDecl(); 4934 ParentDecl->setInvalidDecl(); 4935 } 4936 4937 return Anon; 4938 } 4939 4940 /// GetNameForDeclarator - Determine the full declaration name for the 4941 /// given Declarator. 4942 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4943 return GetNameFromUnqualifiedId(D.getName()); 4944 } 4945 4946 /// Retrieves the declaration name from a parsed unqualified-id. 4947 DeclarationNameInfo 4948 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4949 DeclarationNameInfo NameInfo; 4950 NameInfo.setLoc(Name.StartLocation); 4951 4952 switch (Name.getKind()) { 4953 4954 case UnqualifiedIdKind::IK_ImplicitSelfParam: 4955 case UnqualifiedIdKind::IK_Identifier: 4956 NameInfo.setName(Name.Identifier); 4957 NameInfo.setLoc(Name.StartLocation); 4958 return NameInfo; 4959 4960 case UnqualifiedIdKind::IK_DeductionGuideName: { 4961 // C++ [temp.deduct.guide]p3: 4962 // The simple-template-id shall name a class template specialization. 4963 // The template-name shall be the same identifier as the template-name 4964 // of the simple-template-id. 4965 // These together intend to imply that the template-name shall name a 4966 // class template. 4967 // FIXME: template<typename T> struct X {}; 4968 // template<typename T> using Y = X<T>; 4969 // Y(int) -> Y<int>; 4970 // satisfies these rules but does not name a class template. 4971 TemplateName TN = Name.TemplateName.get().get(); 4972 auto *Template = TN.getAsTemplateDecl(); 4973 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4974 Diag(Name.StartLocation, 4975 diag::err_deduction_guide_name_not_class_template) 4976 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4977 if (Template) 4978 Diag(Template->getLocation(), diag::note_template_decl_here); 4979 return DeclarationNameInfo(); 4980 } 4981 4982 NameInfo.setName( 4983 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4984 NameInfo.setLoc(Name.StartLocation); 4985 return NameInfo; 4986 } 4987 4988 case UnqualifiedIdKind::IK_OperatorFunctionId: 4989 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4990 Name.OperatorFunctionId.Operator)); 4991 NameInfo.setLoc(Name.StartLocation); 4992 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4993 = Name.OperatorFunctionId.SymbolLocations[0]; 4994 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4995 = Name.EndLocation.getRawEncoding(); 4996 return NameInfo; 4997 4998 case UnqualifiedIdKind::IK_LiteralOperatorId: 4999 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5000 Name.Identifier)); 5001 NameInfo.setLoc(Name.StartLocation); 5002 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5003 return NameInfo; 5004 5005 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5006 TypeSourceInfo *TInfo; 5007 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5008 if (Ty.isNull()) 5009 return DeclarationNameInfo(); 5010 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5011 Context.getCanonicalType(Ty))); 5012 NameInfo.setLoc(Name.StartLocation); 5013 NameInfo.setNamedTypeInfo(TInfo); 5014 return NameInfo; 5015 } 5016 5017 case UnqualifiedIdKind::IK_ConstructorName: { 5018 TypeSourceInfo *TInfo; 5019 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5020 if (Ty.isNull()) 5021 return DeclarationNameInfo(); 5022 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5023 Context.getCanonicalType(Ty))); 5024 NameInfo.setLoc(Name.StartLocation); 5025 NameInfo.setNamedTypeInfo(TInfo); 5026 return NameInfo; 5027 } 5028 5029 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5030 // In well-formed code, we can only have a constructor 5031 // template-id that refers to the current context, so go there 5032 // to find the actual type being constructed. 5033 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5034 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5035 return DeclarationNameInfo(); 5036 5037 // Determine the type of the class being constructed. 5038 QualType CurClassType = Context.getTypeDeclType(CurClass); 5039 5040 // FIXME: Check two things: that the template-id names the same type as 5041 // CurClassType, and that the template-id does not occur when the name 5042 // was qualified. 5043 5044 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5045 Context.getCanonicalType(CurClassType))); 5046 NameInfo.setLoc(Name.StartLocation); 5047 // FIXME: should we retrieve TypeSourceInfo? 5048 NameInfo.setNamedTypeInfo(nullptr); 5049 return NameInfo; 5050 } 5051 5052 case UnqualifiedIdKind::IK_DestructorName: { 5053 TypeSourceInfo *TInfo; 5054 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5055 if (Ty.isNull()) 5056 return DeclarationNameInfo(); 5057 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5058 Context.getCanonicalType(Ty))); 5059 NameInfo.setLoc(Name.StartLocation); 5060 NameInfo.setNamedTypeInfo(TInfo); 5061 return NameInfo; 5062 } 5063 5064 case UnqualifiedIdKind::IK_TemplateId: { 5065 TemplateName TName = Name.TemplateId->Template.get(); 5066 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5067 return Context.getNameForTemplate(TName, TNameLoc); 5068 } 5069 5070 } // switch (Name.getKind()) 5071 5072 llvm_unreachable("Unknown name kind"); 5073 } 5074 5075 static QualType getCoreType(QualType Ty) { 5076 do { 5077 if (Ty->isPointerType() || Ty->isReferenceType()) 5078 Ty = Ty->getPointeeType(); 5079 else if (Ty->isArrayType()) 5080 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5081 else 5082 return Ty.withoutLocalFastQualifiers(); 5083 } while (true); 5084 } 5085 5086 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5087 /// and Definition have "nearly" matching parameters. This heuristic is 5088 /// used to improve diagnostics in the case where an out-of-line function 5089 /// definition doesn't match any declaration within the class or namespace. 5090 /// Also sets Params to the list of indices to the parameters that differ 5091 /// between the declaration and the definition. If hasSimilarParameters 5092 /// returns true and Params is empty, then all of the parameters match. 5093 static bool hasSimilarParameters(ASTContext &Context, 5094 FunctionDecl *Declaration, 5095 FunctionDecl *Definition, 5096 SmallVectorImpl<unsigned> &Params) { 5097 Params.clear(); 5098 if (Declaration->param_size() != Definition->param_size()) 5099 return false; 5100 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5101 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5102 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5103 5104 // The parameter types are identical 5105 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5106 continue; 5107 5108 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5109 QualType DefParamBaseTy = getCoreType(DefParamTy); 5110 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5111 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5112 5113 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5114 (DeclTyName && DeclTyName == DefTyName)) 5115 Params.push_back(Idx); 5116 else // The two parameters aren't even close 5117 return false; 5118 } 5119 5120 return true; 5121 } 5122 5123 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5124 /// declarator needs to be rebuilt in the current instantiation. 5125 /// Any bits of declarator which appear before the name are valid for 5126 /// consideration here. That's specifically the type in the decl spec 5127 /// and the base type in any member-pointer chunks. 5128 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5129 DeclarationName Name) { 5130 // The types we specifically need to rebuild are: 5131 // - typenames, typeofs, and decltypes 5132 // - types which will become injected class names 5133 // Of course, we also need to rebuild any type referencing such a 5134 // type. It's safest to just say "dependent", but we call out a 5135 // few cases here. 5136 5137 DeclSpec &DS = D.getMutableDeclSpec(); 5138 switch (DS.getTypeSpecType()) { 5139 case DeclSpec::TST_typename: 5140 case DeclSpec::TST_typeofType: 5141 case DeclSpec::TST_underlyingType: 5142 case DeclSpec::TST_atomic: { 5143 // Grab the type from the parser. 5144 TypeSourceInfo *TSI = nullptr; 5145 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5146 if (T.isNull() || !T->isDependentType()) break; 5147 5148 // Make sure there's a type source info. This isn't really much 5149 // of a waste; most dependent types should have type source info 5150 // attached already. 5151 if (!TSI) 5152 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5153 5154 // Rebuild the type in the current instantiation. 5155 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5156 if (!TSI) return true; 5157 5158 // Store the new type back in the decl spec. 5159 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5160 DS.UpdateTypeRep(LocType); 5161 break; 5162 } 5163 5164 case DeclSpec::TST_decltype: 5165 case DeclSpec::TST_typeofExpr: { 5166 Expr *E = DS.getRepAsExpr(); 5167 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5168 if (Result.isInvalid()) return true; 5169 DS.UpdateExprRep(Result.get()); 5170 break; 5171 } 5172 5173 default: 5174 // Nothing to do for these decl specs. 5175 break; 5176 } 5177 5178 // It doesn't matter what order we do this in. 5179 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5180 DeclaratorChunk &Chunk = D.getTypeObject(I); 5181 5182 // The only type information in the declarator which can come 5183 // before the declaration name is the base type of a member 5184 // pointer. 5185 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5186 continue; 5187 5188 // Rebuild the scope specifier in-place. 5189 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5190 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5191 return true; 5192 } 5193 5194 return false; 5195 } 5196 5197 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5198 D.setFunctionDefinitionKind(FDK_Declaration); 5199 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5200 5201 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5202 Dcl && Dcl->getDeclContext()->isFileContext()) 5203 Dcl->setTopLevelDeclInObjCContainer(); 5204 5205 if (getLangOpts().OpenCL) 5206 setCurrentOpenCLExtensionForDecl(Dcl); 5207 5208 return Dcl; 5209 } 5210 5211 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5212 /// If T is the name of a class, then each of the following shall have a 5213 /// name different from T: 5214 /// - every static data member of class T; 5215 /// - every member function of class T 5216 /// - every member of class T that is itself a type; 5217 /// \returns true if the declaration name violates these rules. 5218 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5219 DeclarationNameInfo NameInfo) { 5220 DeclarationName Name = NameInfo.getName(); 5221 5222 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5223 while (Record && Record->isAnonymousStructOrUnion()) 5224 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5225 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5226 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5227 return true; 5228 } 5229 5230 return false; 5231 } 5232 5233 /// Diagnose a declaration whose declarator-id has the given 5234 /// nested-name-specifier. 5235 /// 5236 /// \param SS The nested-name-specifier of the declarator-id. 5237 /// 5238 /// \param DC The declaration context to which the nested-name-specifier 5239 /// resolves. 5240 /// 5241 /// \param Name The name of the entity being declared. 5242 /// 5243 /// \param Loc The location of the name of the entity being declared. 5244 /// 5245 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5246 /// we're declaring an explicit / partial specialization / instantiation. 5247 /// 5248 /// \returns true if we cannot safely recover from this error, false otherwise. 5249 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5250 DeclarationName Name, 5251 SourceLocation Loc, bool IsTemplateId) { 5252 DeclContext *Cur = CurContext; 5253 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5254 Cur = Cur->getParent(); 5255 5256 // If the user provided a superfluous scope specifier that refers back to the 5257 // class in which the entity is already declared, diagnose and ignore it. 5258 // 5259 // class X { 5260 // void X::f(); 5261 // }; 5262 // 5263 // Note, it was once ill-formed to give redundant qualification in all 5264 // contexts, but that rule was removed by DR482. 5265 if (Cur->Equals(DC)) { 5266 if (Cur->isRecord()) { 5267 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5268 : diag::err_member_extra_qualification) 5269 << Name << FixItHint::CreateRemoval(SS.getRange()); 5270 SS.clear(); 5271 } else { 5272 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5273 } 5274 return false; 5275 } 5276 5277 // Check whether the qualifying scope encloses the scope of the original 5278 // declaration. For a template-id, we perform the checks in 5279 // CheckTemplateSpecializationScope. 5280 if (!Cur->Encloses(DC) && !IsTemplateId) { 5281 if (Cur->isRecord()) 5282 Diag(Loc, diag::err_member_qualification) 5283 << Name << SS.getRange(); 5284 else if (isa<TranslationUnitDecl>(DC)) 5285 Diag(Loc, diag::err_invalid_declarator_global_scope) 5286 << Name << SS.getRange(); 5287 else if (isa<FunctionDecl>(Cur)) 5288 Diag(Loc, diag::err_invalid_declarator_in_function) 5289 << Name << SS.getRange(); 5290 else if (isa<BlockDecl>(Cur)) 5291 Diag(Loc, diag::err_invalid_declarator_in_block) 5292 << Name << SS.getRange(); 5293 else 5294 Diag(Loc, diag::err_invalid_declarator_scope) 5295 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5296 5297 return true; 5298 } 5299 5300 if (Cur->isRecord()) { 5301 // Cannot qualify members within a class. 5302 Diag(Loc, diag::err_member_qualification) 5303 << Name << SS.getRange(); 5304 SS.clear(); 5305 5306 // C++ constructors and destructors with incorrect scopes can break 5307 // our AST invariants by having the wrong underlying types. If 5308 // that's the case, then drop this declaration entirely. 5309 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5310 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5311 !Context.hasSameType(Name.getCXXNameType(), 5312 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5313 return true; 5314 5315 return false; 5316 } 5317 5318 // C++11 [dcl.meaning]p1: 5319 // [...] "The nested-name-specifier of the qualified declarator-id shall 5320 // not begin with a decltype-specifer" 5321 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5322 while (SpecLoc.getPrefix()) 5323 SpecLoc = SpecLoc.getPrefix(); 5324 if (dyn_cast_or_null<DecltypeType>( 5325 SpecLoc.getNestedNameSpecifier()->getAsType())) 5326 Diag(Loc, diag::err_decltype_in_declarator) 5327 << SpecLoc.getTypeLoc().getSourceRange(); 5328 5329 return false; 5330 } 5331 5332 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5333 MultiTemplateParamsArg TemplateParamLists) { 5334 // TODO: consider using NameInfo for diagnostic. 5335 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5336 DeclarationName Name = NameInfo.getName(); 5337 5338 // All of these full declarators require an identifier. If it doesn't have 5339 // one, the ParsedFreeStandingDeclSpec action should be used. 5340 if (D.isDecompositionDeclarator()) { 5341 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5342 } else if (!Name) { 5343 if (!D.isInvalidType()) // Reject this if we think it is valid. 5344 Diag(D.getDeclSpec().getLocStart(), 5345 diag::err_declarator_need_ident) 5346 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5347 return nullptr; 5348 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5349 return nullptr; 5350 5351 // The scope passed in may not be a decl scope. Zip up the scope tree until 5352 // we find one that is. 5353 while ((S->getFlags() & Scope::DeclScope) == 0 || 5354 (S->getFlags() & Scope::TemplateParamScope) != 0) 5355 S = S->getParent(); 5356 5357 DeclContext *DC = CurContext; 5358 if (D.getCXXScopeSpec().isInvalid()) 5359 D.setInvalidType(); 5360 else if (D.getCXXScopeSpec().isSet()) { 5361 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5362 UPPC_DeclarationQualifier)) 5363 return nullptr; 5364 5365 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5366 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5367 if (!DC || isa<EnumDecl>(DC)) { 5368 // If we could not compute the declaration context, it's because the 5369 // declaration context is dependent but does not refer to a class, 5370 // class template, or class template partial specialization. Complain 5371 // and return early, to avoid the coming semantic disaster. 5372 Diag(D.getIdentifierLoc(), 5373 diag::err_template_qualified_declarator_no_match) 5374 << D.getCXXScopeSpec().getScopeRep() 5375 << D.getCXXScopeSpec().getRange(); 5376 return nullptr; 5377 } 5378 bool IsDependentContext = DC->isDependentContext(); 5379 5380 if (!IsDependentContext && 5381 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5382 return nullptr; 5383 5384 // If a class is incomplete, do not parse entities inside it. 5385 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5386 Diag(D.getIdentifierLoc(), 5387 diag::err_member_def_undefined_record) 5388 << Name << DC << D.getCXXScopeSpec().getRange(); 5389 return nullptr; 5390 } 5391 if (!D.getDeclSpec().isFriendSpecified()) { 5392 if (diagnoseQualifiedDeclaration( 5393 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5394 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5395 if (DC->isRecord()) 5396 return nullptr; 5397 5398 D.setInvalidType(); 5399 } 5400 } 5401 5402 // Check whether we need to rebuild the type of the given 5403 // declaration in the current instantiation. 5404 if (EnteringContext && IsDependentContext && 5405 TemplateParamLists.size() != 0) { 5406 ContextRAII SavedContext(*this, DC); 5407 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5408 D.setInvalidType(); 5409 } 5410 } 5411 5412 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5413 QualType R = TInfo->getType(); 5414 5415 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5416 UPPC_DeclarationType)) 5417 D.setInvalidType(); 5418 5419 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5420 forRedeclarationInCurContext()); 5421 5422 // See if this is a redefinition of a variable in the same scope. 5423 if (!D.getCXXScopeSpec().isSet()) { 5424 bool IsLinkageLookup = false; 5425 bool CreateBuiltins = false; 5426 5427 // If the declaration we're planning to build will be a function 5428 // or object with linkage, then look for another declaration with 5429 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5430 // 5431 // If the declaration we're planning to build will be declared with 5432 // external linkage in the translation unit, create any builtin with 5433 // the same name. 5434 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5435 /* Do nothing*/; 5436 else if (CurContext->isFunctionOrMethod() && 5437 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5438 R->isFunctionType())) { 5439 IsLinkageLookup = true; 5440 CreateBuiltins = 5441 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5442 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5443 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5444 CreateBuiltins = true; 5445 5446 if (IsLinkageLookup) { 5447 Previous.clear(LookupRedeclarationWithLinkage); 5448 Previous.setRedeclarationKind(ForExternalRedeclaration); 5449 } 5450 5451 LookupName(Previous, S, CreateBuiltins); 5452 } else { // Something like "int foo::x;" 5453 LookupQualifiedName(Previous, DC); 5454 5455 // C++ [dcl.meaning]p1: 5456 // When the declarator-id is qualified, the declaration shall refer to a 5457 // previously declared member of the class or namespace to which the 5458 // qualifier refers (or, in the case of a namespace, of an element of the 5459 // inline namespace set of that namespace (7.3.1)) or to a specialization 5460 // thereof; [...] 5461 // 5462 // Note that we already checked the context above, and that we do not have 5463 // enough information to make sure that Previous contains the declaration 5464 // we want to match. For example, given: 5465 // 5466 // class X { 5467 // void f(); 5468 // void f(float); 5469 // }; 5470 // 5471 // void X::f(int) { } // ill-formed 5472 // 5473 // In this case, Previous will point to the overload set 5474 // containing the two f's declared in X, but neither of them 5475 // matches. 5476 5477 // C++ [dcl.meaning]p1: 5478 // [...] the member shall not merely have been introduced by a 5479 // using-declaration in the scope of the class or namespace nominated by 5480 // the nested-name-specifier of the declarator-id. 5481 RemoveUsingDecls(Previous); 5482 } 5483 5484 if (Previous.isSingleResult() && 5485 Previous.getFoundDecl()->isTemplateParameter()) { 5486 // Maybe we will complain about the shadowed template parameter. 5487 if (!D.isInvalidType()) 5488 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5489 Previous.getFoundDecl()); 5490 5491 // Just pretend that we didn't see the previous declaration. 5492 Previous.clear(); 5493 } 5494 5495 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5496 // Forget that the previous declaration is the injected-class-name. 5497 Previous.clear(); 5498 5499 // In C++, the previous declaration we find might be a tag type 5500 // (class or enum). In this case, the new declaration will hide the 5501 // tag type. Note that this applies to functions, function templates, and 5502 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5503 if (Previous.isSingleTagDecl() && 5504 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5505 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5506 Previous.clear(); 5507 5508 // Check that there are no default arguments other than in the parameters 5509 // of a function declaration (C++ only). 5510 if (getLangOpts().CPlusPlus) 5511 CheckExtraCXXDefaultArguments(D); 5512 5513 NamedDecl *New; 5514 5515 bool AddToScope = true; 5516 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5517 if (TemplateParamLists.size()) { 5518 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5519 return nullptr; 5520 } 5521 5522 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5523 } else if (R->isFunctionType()) { 5524 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5525 TemplateParamLists, 5526 AddToScope); 5527 } else { 5528 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5529 AddToScope); 5530 } 5531 5532 if (!New) 5533 return nullptr; 5534 5535 // If this has an identifier and is not a function template specialization, 5536 // add it to the scope stack. 5537 if (New->getDeclName() && AddToScope) { 5538 // Only make a locally-scoped extern declaration visible if it is the first 5539 // declaration of this entity. Qualified lookup for such an entity should 5540 // only find this declaration if there is no visible declaration of it. 5541 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5542 PushOnScopeChains(New, S, AddToContext); 5543 if (!AddToContext) 5544 CurContext->addHiddenDecl(New); 5545 } 5546 5547 if (isInOpenMPDeclareTargetContext()) 5548 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5549 5550 return New; 5551 } 5552 5553 /// Helper method to turn variable array types into constant array 5554 /// types in certain situations which would otherwise be errors (for 5555 /// GCC compatibility). 5556 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5557 ASTContext &Context, 5558 bool &SizeIsNegative, 5559 llvm::APSInt &Oversized) { 5560 // This method tries to turn a variable array into a constant 5561 // array even when the size isn't an ICE. This is necessary 5562 // for compatibility with code that depends on gcc's buggy 5563 // constant expression folding, like struct {char x[(int)(char*)2];} 5564 SizeIsNegative = false; 5565 Oversized = 0; 5566 5567 if (T->isDependentType()) 5568 return QualType(); 5569 5570 QualifierCollector Qs; 5571 const Type *Ty = Qs.strip(T); 5572 5573 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5574 QualType Pointee = PTy->getPointeeType(); 5575 QualType FixedType = 5576 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5577 Oversized); 5578 if (FixedType.isNull()) return FixedType; 5579 FixedType = Context.getPointerType(FixedType); 5580 return Qs.apply(Context, FixedType); 5581 } 5582 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5583 QualType Inner = PTy->getInnerType(); 5584 QualType FixedType = 5585 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5586 Oversized); 5587 if (FixedType.isNull()) return FixedType; 5588 FixedType = Context.getParenType(FixedType); 5589 return Qs.apply(Context, FixedType); 5590 } 5591 5592 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5593 if (!VLATy) 5594 return QualType(); 5595 // FIXME: We should probably handle this case 5596 if (VLATy->getElementType()->isVariablyModifiedType()) 5597 return QualType(); 5598 5599 llvm::APSInt Res; 5600 if (!VLATy->getSizeExpr() || 5601 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5602 return QualType(); 5603 5604 // Check whether the array size is negative. 5605 if (Res.isSigned() && Res.isNegative()) { 5606 SizeIsNegative = true; 5607 return QualType(); 5608 } 5609 5610 // Check whether the array is too large to be addressed. 5611 unsigned ActiveSizeBits 5612 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5613 Res); 5614 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5615 Oversized = Res; 5616 return QualType(); 5617 } 5618 5619 return Context.getConstantArrayType(VLATy->getElementType(), 5620 Res, ArrayType::Normal, 0); 5621 } 5622 5623 static void 5624 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5625 SrcTL = SrcTL.getUnqualifiedLoc(); 5626 DstTL = DstTL.getUnqualifiedLoc(); 5627 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5628 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5629 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5630 DstPTL.getPointeeLoc()); 5631 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5632 return; 5633 } 5634 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5635 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5636 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5637 DstPTL.getInnerLoc()); 5638 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5639 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5640 return; 5641 } 5642 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5643 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5644 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5645 TypeLoc DstElemTL = DstATL.getElementLoc(); 5646 DstElemTL.initializeFullCopy(SrcElemTL); 5647 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5648 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5649 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5650 } 5651 5652 /// Helper method to turn variable array types into constant array 5653 /// types in certain situations which would otherwise be errors (for 5654 /// GCC compatibility). 5655 static TypeSourceInfo* 5656 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5657 ASTContext &Context, 5658 bool &SizeIsNegative, 5659 llvm::APSInt &Oversized) { 5660 QualType FixedTy 5661 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5662 SizeIsNegative, Oversized); 5663 if (FixedTy.isNull()) 5664 return nullptr; 5665 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5666 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5667 FixedTInfo->getTypeLoc()); 5668 return FixedTInfo; 5669 } 5670 5671 /// Register the given locally-scoped extern "C" declaration so 5672 /// that it can be found later for redeclarations. We include any extern "C" 5673 /// declaration that is not visible in the translation unit here, not just 5674 /// function-scope declarations. 5675 void 5676 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5677 if (!getLangOpts().CPlusPlus && 5678 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5679 // Don't need to track declarations in the TU in C. 5680 return; 5681 5682 // Note that we have a locally-scoped external with this name. 5683 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5684 } 5685 5686 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5687 // FIXME: We can have multiple results via __attribute__((overloadable)). 5688 auto Result = Context.getExternCContextDecl()->lookup(Name); 5689 return Result.empty() ? nullptr : *Result.begin(); 5690 } 5691 5692 /// Diagnose function specifiers on a declaration of an identifier that 5693 /// does not identify a function. 5694 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5695 // FIXME: We should probably indicate the identifier in question to avoid 5696 // confusion for constructs like "virtual int a(), b;" 5697 if (DS.isVirtualSpecified()) 5698 Diag(DS.getVirtualSpecLoc(), 5699 diag::err_virtual_non_function); 5700 5701 if (DS.isExplicitSpecified()) 5702 Diag(DS.getExplicitSpecLoc(), 5703 diag::err_explicit_non_function); 5704 5705 if (DS.isNoreturnSpecified()) 5706 Diag(DS.getNoreturnSpecLoc(), 5707 diag::err_noreturn_non_function); 5708 } 5709 5710 NamedDecl* 5711 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5712 TypeSourceInfo *TInfo, LookupResult &Previous) { 5713 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5714 if (D.getCXXScopeSpec().isSet()) { 5715 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5716 << D.getCXXScopeSpec().getRange(); 5717 D.setInvalidType(); 5718 // Pretend we didn't see the scope specifier. 5719 DC = CurContext; 5720 Previous.clear(); 5721 } 5722 5723 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5724 5725 if (D.getDeclSpec().isInlineSpecified()) 5726 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5727 << getLangOpts().CPlusPlus17; 5728 if (D.getDeclSpec().isConstexprSpecified()) 5729 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5730 << 1; 5731 5732 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5733 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5734 Diag(D.getName().StartLocation, 5735 diag::err_deduction_guide_invalid_specifier) 5736 << "typedef"; 5737 else 5738 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5739 << D.getName().getSourceRange(); 5740 return nullptr; 5741 } 5742 5743 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5744 if (!NewTD) return nullptr; 5745 5746 // Handle attributes prior to checking for duplicates in MergeVarDecl 5747 ProcessDeclAttributes(S, NewTD, D); 5748 5749 CheckTypedefForVariablyModifiedType(S, NewTD); 5750 5751 bool Redeclaration = D.isRedeclaration(); 5752 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5753 D.setRedeclaration(Redeclaration); 5754 return ND; 5755 } 5756 5757 void 5758 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5759 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5760 // then it shall have block scope. 5761 // Note that variably modified types must be fixed before merging the decl so 5762 // that redeclarations will match. 5763 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5764 QualType T = TInfo->getType(); 5765 if (T->isVariablyModifiedType()) { 5766 setFunctionHasBranchProtectedScope(); 5767 5768 if (S->getFnParent() == nullptr) { 5769 bool SizeIsNegative; 5770 llvm::APSInt Oversized; 5771 TypeSourceInfo *FixedTInfo = 5772 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5773 SizeIsNegative, 5774 Oversized); 5775 if (FixedTInfo) { 5776 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5777 NewTD->setTypeSourceInfo(FixedTInfo); 5778 } else { 5779 if (SizeIsNegative) 5780 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5781 else if (T->isVariableArrayType()) 5782 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5783 else if (Oversized.getBoolValue()) 5784 Diag(NewTD->getLocation(), diag::err_array_too_large) 5785 << Oversized.toString(10); 5786 else 5787 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5788 NewTD->setInvalidDecl(); 5789 } 5790 } 5791 } 5792 } 5793 5794 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5795 /// declares a typedef-name, either using the 'typedef' type specifier or via 5796 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5797 NamedDecl* 5798 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5799 LookupResult &Previous, bool &Redeclaration) { 5800 5801 // Find the shadowed declaration before filtering for scope. 5802 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5803 5804 // Merge the decl with the existing one if appropriate. If the decl is 5805 // in an outer scope, it isn't the same thing. 5806 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5807 /*AllowInlineNamespace*/false); 5808 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5809 if (!Previous.empty()) { 5810 Redeclaration = true; 5811 MergeTypedefNameDecl(S, NewTD, Previous); 5812 } 5813 5814 if (ShadowedDecl && !Redeclaration) 5815 CheckShadow(NewTD, ShadowedDecl, Previous); 5816 5817 // If this is the C FILE type, notify the AST context. 5818 if (IdentifierInfo *II = NewTD->getIdentifier()) 5819 if (!NewTD->isInvalidDecl() && 5820 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5821 if (II->isStr("FILE")) 5822 Context.setFILEDecl(NewTD); 5823 else if (II->isStr("jmp_buf")) 5824 Context.setjmp_bufDecl(NewTD); 5825 else if (II->isStr("sigjmp_buf")) 5826 Context.setsigjmp_bufDecl(NewTD); 5827 else if (II->isStr("ucontext_t")) 5828 Context.setucontext_tDecl(NewTD); 5829 } 5830 5831 return NewTD; 5832 } 5833 5834 /// Determines whether the given declaration is an out-of-scope 5835 /// previous declaration. 5836 /// 5837 /// This routine should be invoked when name lookup has found a 5838 /// previous declaration (PrevDecl) that is not in the scope where a 5839 /// new declaration by the same name is being introduced. If the new 5840 /// declaration occurs in a local scope, previous declarations with 5841 /// linkage may still be considered previous declarations (C99 5842 /// 6.2.2p4-5, C++ [basic.link]p6). 5843 /// 5844 /// \param PrevDecl the previous declaration found by name 5845 /// lookup 5846 /// 5847 /// \param DC the context in which the new declaration is being 5848 /// declared. 5849 /// 5850 /// \returns true if PrevDecl is an out-of-scope previous declaration 5851 /// for a new delcaration with the same name. 5852 static bool 5853 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5854 ASTContext &Context) { 5855 if (!PrevDecl) 5856 return false; 5857 5858 if (!PrevDecl->hasLinkage()) 5859 return false; 5860 5861 if (Context.getLangOpts().CPlusPlus) { 5862 // C++ [basic.link]p6: 5863 // If there is a visible declaration of an entity with linkage 5864 // having the same name and type, ignoring entities declared 5865 // outside the innermost enclosing namespace scope, the block 5866 // scope declaration declares that same entity and receives the 5867 // linkage of the previous declaration. 5868 DeclContext *OuterContext = DC->getRedeclContext(); 5869 if (!OuterContext->isFunctionOrMethod()) 5870 // This rule only applies to block-scope declarations. 5871 return false; 5872 5873 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5874 if (PrevOuterContext->isRecord()) 5875 // We found a member function: ignore it. 5876 return false; 5877 5878 // Find the innermost enclosing namespace for the new and 5879 // previous declarations. 5880 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5881 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5882 5883 // The previous declaration is in a different namespace, so it 5884 // isn't the same function. 5885 if (!OuterContext->Equals(PrevOuterContext)) 5886 return false; 5887 } 5888 5889 return true; 5890 } 5891 5892 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5893 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5894 if (!SS.isSet()) return; 5895 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5896 } 5897 5898 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5899 QualType type = decl->getType(); 5900 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5901 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5902 // Various kinds of declaration aren't allowed to be __autoreleasing. 5903 unsigned kind = -1U; 5904 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5905 if (var->hasAttr<BlocksAttr>()) 5906 kind = 0; // __block 5907 else if (!var->hasLocalStorage()) 5908 kind = 1; // global 5909 } else if (isa<ObjCIvarDecl>(decl)) { 5910 kind = 3; // ivar 5911 } else if (isa<FieldDecl>(decl)) { 5912 kind = 2; // field 5913 } 5914 5915 if (kind != -1U) { 5916 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5917 << kind; 5918 } 5919 } else if (lifetime == Qualifiers::OCL_None) { 5920 // Try to infer lifetime. 5921 if (!type->isObjCLifetimeType()) 5922 return false; 5923 5924 lifetime = type->getObjCARCImplicitLifetime(); 5925 type = Context.getLifetimeQualifiedType(type, lifetime); 5926 decl->setType(type); 5927 } 5928 5929 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5930 // Thread-local variables cannot have lifetime. 5931 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5932 var->getTLSKind()) { 5933 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5934 << var->getType(); 5935 return true; 5936 } 5937 } 5938 5939 return false; 5940 } 5941 5942 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5943 // Ensure that an auto decl is deduced otherwise the checks below might cache 5944 // the wrong linkage. 5945 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5946 5947 // 'weak' only applies to declarations with external linkage. 5948 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5949 if (!ND.isExternallyVisible()) { 5950 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5951 ND.dropAttr<WeakAttr>(); 5952 } 5953 } 5954 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5955 if (ND.isExternallyVisible()) { 5956 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5957 ND.dropAttr<WeakRefAttr>(); 5958 ND.dropAttr<AliasAttr>(); 5959 } 5960 } 5961 5962 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5963 if (VD->hasInit()) { 5964 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5965 assert(VD->isThisDeclarationADefinition() && 5966 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5967 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5968 VD->dropAttr<AliasAttr>(); 5969 } 5970 } 5971 } 5972 5973 // 'selectany' only applies to externally visible variable declarations. 5974 // It does not apply to functions. 5975 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5976 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5977 S.Diag(Attr->getLocation(), 5978 diag::err_attribute_selectany_non_extern_data); 5979 ND.dropAttr<SelectAnyAttr>(); 5980 } 5981 } 5982 5983 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5984 // dll attributes require external linkage. Static locals may have external 5985 // linkage but still cannot be explicitly imported or exported. 5986 auto *VD = dyn_cast<VarDecl>(&ND); 5987 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5988 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5989 << &ND << Attr; 5990 ND.setInvalidDecl(); 5991 } 5992 } 5993 5994 // Virtual functions cannot be marked as 'notail'. 5995 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5996 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5997 if (MD->isVirtual()) { 5998 S.Diag(ND.getLocation(), 5999 diag::err_invalid_attribute_on_virtual_function) 6000 << Attr; 6001 ND.dropAttr<NotTailCalledAttr>(); 6002 } 6003 } 6004 6005 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6006 NamedDecl *NewDecl, 6007 bool IsSpecialization, 6008 bool IsDefinition) { 6009 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6010 return; 6011 6012 bool IsTemplate = false; 6013 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6014 OldDecl = OldTD->getTemplatedDecl(); 6015 IsTemplate = true; 6016 if (!IsSpecialization) 6017 IsDefinition = false; 6018 } 6019 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6020 NewDecl = NewTD->getTemplatedDecl(); 6021 IsTemplate = true; 6022 } 6023 6024 if (!OldDecl || !NewDecl) 6025 return; 6026 6027 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6028 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6029 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6030 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6031 6032 // dllimport and dllexport are inheritable attributes so we have to exclude 6033 // inherited attribute instances. 6034 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6035 (NewExportAttr && !NewExportAttr->isInherited()); 6036 6037 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6038 // the only exception being explicit specializations. 6039 // Implicitly generated declarations are also excluded for now because there 6040 // is no other way to switch these to use dllimport or dllexport. 6041 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6042 6043 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6044 // Allow with a warning for free functions and global variables. 6045 bool JustWarn = false; 6046 if (!OldDecl->isCXXClassMember()) { 6047 auto *VD = dyn_cast<VarDecl>(OldDecl); 6048 if (VD && !VD->getDescribedVarTemplate()) 6049 JustWarn = true; 6050 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6051 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6052 JustWarn = true; 6053 } 6054 6055 // We cannot change a declaration that's been used because IR has already 6056 // been emitted. Dllimported functions will still work though (modulo 6057 // address equality) as they can use the thunk. 6058 if (OldDecl->isUsed()) 6059 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6060 JustWarn = false; 6061 6062 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6063 : diag::err_attribute_dll_redeclaration; 6064 S.Diag(NewDecl->getLocation(), DiagID) 6065 << NewDecl 6066 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6067 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6068 if (!JustWarn) { 6069 NewDecl->setInvalidDecl(); 6070 return; 6071 } 6072 } 6073 6074 // A redeclaration is not allowed to drop a dllimport attribute, the only 6075 // exceptions being inline function definitions (except for function 6076 // templates), local extern declarations, qualified friend declarations or 6077 // special MSVC extension: in the last case, the declaration is treated as if 6078 // it were marked dllexport. 6079 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6080 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6081 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6082 // Ignore static data because out-of-line definitions are diagnosed 6083 // separately. 6084 IsStaticDataMember = VD->isStaticDataMember(); 6085 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6086 VarDecl::DeclarationOnly; 6087 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6088 IsInline = FD->isInlined(); 6089 IsQualifiedFriend = FD->getQualifier() && 6090 FD->getFriendObjectKind() == Decl::FOK_Declared; 6091 } 6092 6093 if (OldImportAttr && !HasNewAttr && 6094 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6095 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6096 if (IsMicrosoft && IsDefinition) { 6097 S.Diag(NewDecl->getLocation(), 6098 diag::warn_redeclaration_without_import_attribute) 6099 << NewDecl; 6100 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6101 NewDecl->dropAttr<DLLImportAttr>(); 6102 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6103 NewImportAttr->getRange(), S.Context, 6104 NewImportAttr->getSpellingListIndex())); 6105 } else { 6106 S.Diag(NewDecl->getLocation(), 6107 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6108 << NewDecl << OldImportAttr; 6109 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6110 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6111 OldDecl->dropAttr<DLLImportAttr>(); 6112 NewDecl->dropAttr<DLLImportAttr>(); 6113 } 6114 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6115 // In MinGW, seeing a function declared inline drops the dllimport 6116 // attribute. 6117 OldDecl->dropAttr<DLLImportAttr>(); 6118 NewDecl->dropAttr<DLLImportAttr>(); 6119 S.Diag(NewDecl->getLocation(), 6120 diag::warn_dllimport_dropped_from_inline_function) 6121 << NewDecl << OldImportAttr; 6122 } 6123 6124 // A specialization of a class template member function is processed here 6125 // since it's a redeclaration. If the parent class is dllexport, the 6126 // specialization inherits that attribute. This doesn't happen automatically 6127 // since the parent class isn't instantiated until later. 6128 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6129 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6130 !NewImportAttr && !NewExportAttr) { 6131 if (const DLLExportAttr *ParentExportAttr = 6132 MD->getParent()->getAttr<DLLExportAttr>()) { 6133 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6134 NewAttr->setInherited(true); 6135 NewDecl->addAttr(NewAttr); 6136 } 6137 } 6138 } 6139 } 6140 6141 /// Given that we are within the definition of the given function, 6142 /// will that definition behave like C99's 'inline', where the 6143 /// definition is discarded except for optimization purposes? 6144 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6145 // Try to avoid calling GetGVALinkageForFunction. 6146 6147 // All cases of this require the 'inline' keyword. 6148 if (!FD->isInlined()) return false; 6149 6150 // This is only possible in C++ with the gnu_inline attribute. 6151 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6152 return false; 6153 6154 // Okay, go ahead and call the relatively-more-expensive function. 6155 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6156 } 6157 6158 /// Determine whether a variable is extern "C" prior to attaching 6159 /// an initializer. We can't just call isExternC() here, because that 6160 /// will also compute and cache whether the declaration is externally 6161 /// visible, which might change when we attach the initializer. 6162 /// 6163 /// This can only be used if the declaration is known to not be a 6164 /// redeclaration of an internal linkage declaration. 6165 /// 6166 /// For instance: 6167 /// 6168 /// auto x = []{}; 6169 /// 6170 /// Attaching the initializer here makes this declaration not externally 6171 /// visible, because its type has internal linkage. 6172 /// 6173 /// FIXME: This is a hack. 6174 template<typename T> 6175 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6176 if (S.getLangOpts().CPlusPlus) { 6177 // In C++, the overloadable attribute negates the effects of extern "C". 6178 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6179 return false; 6180 6181 // So do CUDA's host/device attributes. 6182 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6183 D->template hasAttr<CUDAHostAttr>())) 6184 return false; 6185 } 6186 return D->isExternC(); 6187 } 6188 6189 static bool shouldConsiderLinkage(const VarDecl *VD) { 6190 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6191 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6192 return VD->hasExternalStorage(); 6193 if (DC->isFileContext()) 6194 return true; 6195 if (DC->isRecord()) 6196 return false; 6197 llvm_unreachable("Unexpected context"); 6198 } 6199 6200 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6201 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6202 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6203 isa<OMPDeclareReductionDecl>(DC)) 6204 return true; 6205 if (DC->isRecord()) 6206 return false; 6207 llvm_unreachable("Unexpected context"); 6208 } 6209 6210 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6211 AttributeList::Kind Kind) { 6212 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6213 if (L->getKind() == Kind) 6214 return true; 6215 return false; 6216 } 6217 6218 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6219 AttributeList::Kind Kind) { 6220 // Check decl attributes on the DeclSpec. 6221 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6222 return true; 6223 6224 // Walk the declarator structure, checking decl attributes that were in a type 6225 // position to the decl itself. 6226 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6227 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6228 return true; 6229 } 6230 6231 // Finally, check attributes on the decl itself. 6232 return hasParsedAttr(S, PD.getAttributes(), Kind); 6233 } 6234 6235 /// Adjust the \c DeclContext for a function or variable that might be a 6236 /// function-local external declaration. 6237 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6238 if (!DC->isFunctionOrMethod()) 6239 return false; 6240 6241 // If this is a local extern function or variable declared within a function 6242 // template, don't add it into the enclosing namespace scope until it is 6243 // instantiated; it might have a dependent type right now. 6244 if (DC->isDependentContext()) 6245 return true; 6246 6247 // C++11 [basic.link]p7: 6248 // When a block scope declaration of an entity with linkage is not found to 6249 // refer to some other declaration, then that entity is a member of the 6250 // innermost enclosing namespace. 6251 // 6252 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6253 // semantically-enclosing namespace, not a lexically-enclosing one. 6254 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6255 DC = DC->getParent(); 6256 return true; 6257 } 6258 6259 /// Returns true if given declaration has external C language linkage. 6260 static bool isDeclExternC(const Decl *D) { 6261 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6262 return FD->isExternC(); 6263 if (const auto *VD = dyn_cast<VarDecl>(D)) 6264 return VD->isExternC(); 6265 6266 llvm_unreachable("Unknown type of decl!"); 6267 } 6268 6269 NamedDecl *Sema::ActOnVariableDeclarator( 6270 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6271 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6272 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6273 QualType R = TInfo->getType(); 6274 DeclarationName Name = GetNameForDeclarator(D).getName(); 6275 6276 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6277 6278 if (D.isDecompositionDeclarator()) { 6279 // Take the name of the first declarator as our name for diagnostic 6280 // purposes. 6281 auto &Decomp = D.getDecompositionDeclarator(); 6282 if (!Decomp.bindings().empty()) { 6283 II = Decomp.bindings()[0].Name; 6284 Name = II; 6285 } 6286 } else if (!II) { 6287 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6288 return nullptr; 6289 } 6290 6291 if (getLangOpts().OpenCL) { 6292 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6293 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6294 // argument. 6295 if (R->isImageType() || R->isPipeType()) { 6296 Diag(D.getIdentifierLoc(), 6297 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6298 << R; 6299 D.setInvalidType(); 6300 return nullptr; 6301 } 6302 6303 // OpenCL v1.2 s6.9.r: 6304 // The event type cannot be used to declare a program scope variable. 6305 // OpenCL v2.0 s6.9.q: 6306 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6307 if (NULL == S->getParent()) { 6308 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6309 Diag(D.getIdentifierLoc(), 6310 diag::err_invalid_type_for_program_scope_var) << R; 6311 D.setInvalidType(); 6312 return nullptr; 6313 } 6314 } 6315 6316 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6317 QualType NR = R; 6318 while (NR->isPointerType()) { 6319 if (NR->isFunctionPointerType()) { 6320 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6321 D.setInvalidType(); 6322 break; 6323 } 6324 NR = NR->getPointeeType(); 6325 } 6326 6327 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6328 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6329 // half array type (unless the cl_khr_fp16 extension is enabled). 6330 if (Context.getBaseElementType(R)->isHalfType()) { 6331 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6332 D.setInvalidType(); 6333 } 6334 } 6335 6336 if (R->isSamplerT()) { 6337 // OpenCL v1.2 s6.9.b p4: 6338 // The sampler type cannot be used with the __local and __global address 6339 // space qualifiers. 6340 if (R.getAddressSpace() == LangAS::opencl_local || 6341 R.getAddressSpace() == LangAS::opencl_global) { 6342 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6343 } 6344 6345 // OpenCL v1.2 s6.12.14.1: 6346 // A global sampler must be declared with either the constant address 6347 // space qualifier or with the const qualifier. 6348 if (DC->isTranslationUnit() && 6349 !(R.getAddressSpace() == LangAS::opencl_constant || 6350 R.isConstQualified())) { 6351 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6352 D.setInvalidType(); 6353 } 6354 } 6355 6356 // OpenCL v1.2 s6.9.r: 6357 // The event type cannot be used with the __local, __constant and __global 6358 // address space qualifiers. 6359 if (R->isEventT()) { 6360 if (R.getAddressSpace() != LangAS::opencl_private) { 6361 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6362 D.setInvalidType(); 6363 } 6364 } 6365 6366 // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not 6367 // supported. OpenCL C does not support thread_local either, and 6368 // also reject all other thread storage class specifiers. 6369 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6370 if (TSC != TSCS_unspecified) { 6371 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6372 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6373 diag::err_opencl_unknown_type_specifier) 6374 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6375 << DeclSpec::getSpecifierName(TSC) << 1; 6376 D.setInvalidType(); 6377 return nullptr; 6378 } 6379 } 6380 6381 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6382 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6383 6384 // dllimport globals without explicit storage class are treated as extern. We 6385 // have to change the storage class this early to get the right DeclContext. 6386 if (SC == SC_None && !DC->isRecord() && 6387 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6388 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6389 SC = SC_Extern; 6390 6391 DeclContext *OriginalDC = DC; 6392 bool IsLocalExternDecl = SC == SC_Extern && 6393 adjustContextForLocalExternDecl(DC); 6394 6395 if (SCSpec == DeclSpec::SCS_mutable) { 6396 // mutable can only appear on non-static class members, so it's always 6397 // an error here 6398 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6399 D.setInvalidType(); 6400 SC = SC_None; 6401 } 6402 6403 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6404 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6405 D.getDeclSpec().getStorageClassSpecLoc())) { 6406 // In C++11, the 'register' storage class specifier is deprecated. 6407 // Suppress the warning in system macros, it's used in macros in some 6408 // popular C system headers, such as in glibc's htonl() macro. 6409 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6410 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6411 : diag::warn_deprecated_register) 6412 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6413 } 6414 6415 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6416 6417 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6418 // C99 6.9p2: The storage-class specifiers auto and register shall not 6419 // appear in the declaration specifiers in an external declaration. 6420 // Global Register+Asm is a GNU extension we support. 6421 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6422 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6423 D.setInvalidType(); 6424 } 6425 } 6426 6427 bool IsMemberSpecialization = false; 6428 bool IsVariableTemplateSpecialization = false; 6429 bool IsPartialSpecialization = false; 6430 bool IsVariableTemplate = false; 6431 VarDecl *NewVD = nullptr; 6432 VarTemplateDecl *NewTemplate = nullptr; 6433 TemplateParameterList *TemplateParams = nullptr; 6434 if (!getLangOpts().CPlusPlus) { 6435 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6436 D.getIdentifierLoc(), II, 6437 R, TInfo, SC); 6438 6439 if (R->getContainedDeducedType()) 6440 ParsingInitForAutoVars.insert(NewVD); 6441 6442 if (D.isInvalidType()) 6443 NewVD->setInvalidDecl(); 6444 } else { 6445 bool Invalid = false; 6446 6447 if (DC->isRecord() && !CurContext->isRecord()) { 6448 // This is an out-of-line definition of a static data member. 6449 switch (SC) { 6450 case SC_None: 6451 break; 6452 case SC_Static: 6453 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6454 diag::err_static_out_of_line) 6455 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6456 break; 6457 case SC_Auto: 6458 case SC_Register: 6459 case SC_Extern: 6460 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6461 // to names of variables declared in a block or to function parameters. 6462 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6463 // of class members 6464 6465 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6466 diag::err_storage_class_for_static_member) 6467 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6468 break; 6469 case SC_PrivateExtern: 6470 llvm_unreachable("C storage class in c++!"); 6471 } 6472 } 6473 6474 if (SC == SC_Static && CurContext->isRecord()) { 6475 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6476 if (RD->isLocalClass()) 6477 Diag(D.getIdentifierLoc(), 6478 diag::err_static_data_member_not_allowed_in_local_class) 6479 << Name << RD->getDeclName(); 6480 6481 // C++98 [class.union]p1: If a union contains a static data member, 6482 // the program is ill-formed. C++11 drops this restriction. 6483 if (RD->isUnion()) 6484 Diag(D.getIdentifierLoc(), 6485 getLangOpts().CPlusPlus11 6486 ? diag::warn_cxx98_compat_static_data_member_in_union 6487 : diag::ext_static_data_member_in_union) << Name; 6488 // We conservatively disallow static data members in anonymous structs. 6489 else if (!RD->getDeclName()) 6490 Diag(D.getIdentifierLoc(), 6491 diag::err_static_data_member_not_allowed_in_anon_struct) 6492 << Name << RD->isUnion(); 6493 } 6494 } 6495 6496 // Match up the template parameter lists with the scope specifier, then 6497 // determine whether we have a template or a template specialization. 6498 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6499 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6500 D.getCXXScopeSpec(), 6501 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6502 ? D.getName().TemplateId 6503 : nullptr, 6504 TemplateParamLists, 6505 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6506 6507 if (TemplateParams) { 6508 if (!TemplateParams->size() && 6509 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6510 // There is an extraneous 'template<>' for this variable. Complain 6511 // about it, but allow the declaration of the variable. 6512 Diag(TemplateParams->getTemplateLoc(), 6513 diag::err_template_variable_noparams) 6514 << II 6515 << SourceRange(TemplateParams->getTemplateLoc(), 6516 TemplateParams->getRAngleLoc()); 6517 TemplateParams = nullptr; 6518 } else { 6519 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6520 // This is an explicit specialization or a partial specialization. 6521 // FIXME: Check that we can declare a specialization here. 6522 IsVariableTemplateSpecialization = true; 6523 IsPartialSpecialization = TemplateParams->size() > 0; 6524 } else { // if (TemplateParams->size() > 0) 6525 // This is a template declaration. 6526 IsVariableTemplate = true; 6527 6528 // Check that we can declare a template here. 6529 if (CheckTemplateDeclScope(S, TemplateParams)) 6530 return nullptr; 6531 6532 // Only C++1y supports variable templates (N3651). 6533 Diag(D.getIdentifierLoc(), 6534 getLangOpts().CPlusPlus14 6535 ? diag::warn_cxx11_compat_variable_template 6536 : diag::ext_variable_template); 6537 } 6538 } 6539 } else { 6540 assert((Invalid || 6541 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6542 "should have a 'template<>' for this decl"); 6543 } 6544 6545 if (IsVariableTemplateSpecialization) { 6546 SourceLocation TemplateKWLoc = 6547 TemplateParamLists.size() > 0 6548 ? TemplateParamLists[0]->getTemplateLoc() 6549 : SourceLocation(); 6550 DeclResult Res = ActOnVarTemplateSpecialization( 6551 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6552 IsPartialSpecialization); 6553 if (Res.isInvalid()) 6554 return nullptr; 6555 NewVD = cast<VarDecl>(Res.get()); 6556 AddToScope = false; 6557 } else if (D.isDecompositionDeclarator()) { 6558 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6559 D.getIdentifierLoc(), R, TInfo, SC, 6560 Bindings); 6561 } else 6562 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6563 D.getIdentifierLoc(), II, R, TInfo, SC); 6564 6565 // If this is supposed to be a variable template, create it as such. 6566 if (IsVariableTemplate) { 6567 NewTemplate = 6568 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6569 TemplateParams, NewVD); 6570 NewVD->setDescribedVarTemplate(NewTemplate); 6571 } 6572 6573 // If this decl has an auto type in need of deduction, make a note of the 6574 // Decl so we can diagnose uses of it in its own initializer. 6575 if (R->getContainedDeducedType()) 6576 ParsingInitForAutoVars.insert(NewVD); 6577 6578 if (D.isInvalidType() || Invalid) { 6579 NewVD->setInvalidDecl(); 6580 if (NewTemplate) 6581 NewTemplate->setInvalidDecl(); 6582 } 6583 6584 SetNestedNameSpecifier(NewVD, D); 6585 6586 // If we have any template parameter lists that don't directly belong to 6587 // the variable (matching the scope specifier), store them. 6588 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6589 if (TemplateParamLists.size() > VDTemplateParamLists) 6590 NewVD->setTemplateParameterListsInfo( 6591 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6592 6593 if (D.getDeclSpec().isConstexprSpecified()) { 6594 NewVD->setConstexpr(true); 6595 // C++1z [dcl.spec.constexpr]p1: 6596 // A static data member declared with the constexpr specifier is 6597 // implicitly an inline variable. 6598 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6599 NewVD->setImplicitlyInline(); 6600 } 6601 } 6602 6603 if (D.getDeclSpec().isInlineSpecified()) { 6604 if (!getLangOpts().CPlusPlus) { 6605 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6606 << 0; 6607 } else if (CurContext->isFunctionOrMethod()) { 6608 // 'inline' is not allowed on block scope variable declaration. 6609 Diag(D.getDeclSpec().getInlineSpecLoc(), 6610 diag::err_inline_declaration_block_scope) << Name 6611 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6612 } else { 6613 Diag(D.getDeclSpec().getInlineSpecLoc(), 6614 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6615 : diag::ext_inline_variable); 6616 NewVD->setInlineSpecified(); 6617 } 6618 } 6619 6620 // Set the lexical context. If the declarator has a C++ scope specifier, the 6621 // lexical context will be different from the semantic context. 6622 NewVD->setLexicalDeclContext(CurContext); 6623 if (NewTemplate) 6624 NewTemplate->setLexicalDeclContext(CurContext); 6625 6626 if (IsLocalExternDecl) { 6627 if (D.isDecompositionDeclarator()) 6628 for (auto *B : Bindings) 6629 B->setLocalExternDecl(); 6630 else 6631 NewVD->setLocalExternDecl(); 6632 } 6633 6634 bool EmitTLSUnsupportedError = false; 6635 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6636 // C++11 [dcl.stc]p4: 6637 // When thread_local is applied to a variable of block scope the 6638 // storage-class-specifier static is implied if it does not appear 6639 // explicitly. 6640 // Core issue: 'static' is not implied if the variable is declared 6641 // 'extern'. 6642 if (NewVD->hasLocalStorage() && 6643 (SCSpec != DeclSpec::SCS_unspecified || 6644 TSCS != DeclSpec::TSCS_thread_local || 6645 !DC->isFunctionOrMethod())) 6646 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6647 diag::err_thread_non_global) 6648 << DeclSpec::getSpecifierName(TSCS); 6649 else if (!Context.getTargetInfo().isTLSSupported()) { 6650 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6651 // Postpone error emission until we've collected attributes required to 6652 // figure out whether it's a host or device variable and whether the 6653 // error should be ignored. 6654 EmitTLSUnsupportedError = true; 6655 // We still need to mark the variable as TLS so it shows up in AST with 6656 // proper storage class for other tools to use even if we're not going 6657 // to emit any code for it. 6658 NewVD->setTSCSpec(TSCS); 6659 } else 6660 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6661 diag::err_thread_unsupported); 6662 } else 6663 NewVD->setTSCSpec(TSCS); 6664 } 6665 6666 // C99 6.7.4p3 6667 // An inline definition of a function with external linkage shall 6668 // not contain a definition of a modifiable object with static or 6669 // thread storage duration... 6670 // We only apply this when the function is required to be defined 6671 // elsewhere, i.e. when the function is not 'extern inline'. Note 6672 // that a local variable with thread storage duration still has to 6673 // be marked 'static'. Also note that it's possible to get these 6674 // semantics in C++ using __attribute__((gnu_inline)). 6675 if (SC == SC_Static && S->getFnParent() != nullptr && 6676 !NewVD->getType().isConstQualified()) { 6677 FunctionDecl *CurFD = getCurFunctionDecl(); 6678 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6679 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6680 diag::warn_static_local_in_extern_inline); 6681 MaybeSuggestAddingStaticToDecl(CurFD); 6682 } 6683 } 6684 6685 if (D.getDeclSpec().isModulePrivateSpecified()) { 6686 if (IsVariableTemplateSpecialization) 6687 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6688 << (IsPartialSpecialization ? 1 : 0) 6689 << FixItHint::CreateRemoval( 6690 D.getDeclSpec().getModulePrivateSpecLoc()); 6691 else if (IsMemberSpecialization) 6692 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6693 << 2 6694 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6695 else if (NewVD->hasLocalStorage()) 6696 Diag(NewVD->getLocation(), diag::err_module_private_local) 6697 << 0 << NewVD->getDeclName() 6698 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6699 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6700 else { 6701 NewVD->setModulePrivate(); 6702 if (NewTemplate) 6703 NewTemplate->setModulePrivate(); 6704 for (auto *B : Bindings) 6705 B->setModulePrivate(); 6706 } 6707 } 6708 6709 // Handle attributes prior to checking for duplicates in MergeVarDecl 6710 ProcessDeclAttributes(S, NewVD, D); 6711 6712 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6713 if (EmitTLSUnsupportedError && 6714 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6715 (getLangOpts().OpenMPIsDevice && 6716 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6717 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6718 diag::err_thread_unsupported); 6719 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6720 // storage [duration]." 6721 if (SC == SC_None && S->getFnParent() != nullptr && 6722 (NewVD->hasAttr<CUDASharedAttr>() || 6723 NewVD->hasAttr<CUDAConstantAttr>())) { 6724 NewVD->setStorageClass(SC_Static); 6725 } 6726 } 6727 6728 // Ensure that dllimport globals without explicit storage class are treated as 6729 // extern. The storage class is set above using parsed attributes. Now we can 6730 // check the VarDecl itself. 6731 assert(!NewVD->hasAttr<DLLImportAttr>() || 6732 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6733 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6734 6735 // In auto-retain/release, infer strong retension for variables of 6736 // retainable type. 6737 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6738 NewVD->setInvalidDecl(); 6739 6740 // Handle GNU asm-label extension (encoded as an attribute). 6741 if (Expr *E = (Expr*)D.getAsmLabel()) { 6742 // The parser guarantees this is a string. 6743 StringLiteral *SE = cast<StringLiteral>(E); 6744 StringRef Label = SE->getString(); 6745 if (S->getFnParent() != nullptr) { 6746 switch (SC) { 6747 case SC_None: 6748 case SC_Auto: 6749 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6750 break; 6751 case SC_Register: 6752 // Local Named register 6753 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6754 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6755 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6756 break; 6757 case SC_Static: 6758 case SC_Extern: 6759 case SC_PrivateExtern: 6760 break; 6761 } 6762 } else if (SC == SC_Register) { 6763 // Global Named register 6764 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6765 const auto &TI = Context.getTargetInfo(); 6766 bool HasSizeMismatch; 6767 6768 if (!TI.isValidGCCRegisterName(Label)) 6769 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6770 else if (!TI.validateGlobalRegisterVariable(Label, 6771 Context.getTypeSize(R), 6772 HasSizeMismatch)) 6773 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6774 else if (HasSizeMismatch) 6775 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6776 } 6777 6778 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6779 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6780 NewVD->setInvalidDecl(true); 6781 } 6782 } 6783 6784 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6785 Context, Label, 0)); 6786 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6787 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6788 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6789 if (I != ExtnameUndeclaredIdentifiers.end()) { 6790 if (isDeclExternC(NewVD)) { 6791 NewVD->addAttr(I->second); 6792 ExtnameUndeclaredIdentifiers.erase(I); 6793 } else 6794 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6795 << /*Variable*/1 << NewVD; 6796 } 6797 } 6798 6799 // Find the shadowed declaration before filtering for scope. 6800 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6801 ? getShadowedDeclaration(NewVD, Previous) 6802 : nullptr; 6803 6804 // Don't consider existing declarations that are in a different 6805 // scope and are out-of-semantic-context declarations (if the new 6806 // declaration has linkage). 6807 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6808 D.getCXXScopeSpec().isNotEmpty() || 6809 IsMemberSpecialization || 6810 IsVariableTemplateSpecialization); 6811 6812 // Check whether the previous declaration is in the same block scope. This 6813 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6814 if (getLangOpts().CPlusPlus && 6815 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6816 NewVD->setPreviousDeclInSameBlockScope( 6817 Previous.isSingleResult() && !Previous.isShadowed() && 6818 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6819 6820 if (!getLangOpts().CPlusPlus) { 6821 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6822 } else { 6823 // If this is an explicit specialization of a static data member, check it. 6824 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6825 CheckMemberSpecialization(NewVD, Previous)) 6826 NewVD->setInvalidDecl(); 6827 6828 // Merge the decl with the existing one if appropriate. 6829 if (!Previous.empty()) { 6830 if (Previous.isSingleResult() && 6831 isa<FieldDecl>(Previous.getFoundDecl()) && 6832 D.getCXXScopeSpec().isSet()) { 6833 // The user tried to define a non-static data member 6834 // out-of-line (C++ [dcl.meaning]p1). 6835 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6836 << D.getCXXScopeSpec().getRange(); 6837 Previous.clear(); 6838 NewVD->setInvalidDecl(); 6839 } 6840 } else if (D.getCXXScopeSpec().isSet()) { 6841 // No previous declaration in the qualifying scope. 6842 Diag(D.getIdentifierLoc(), diag::err_no_member) 6843 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6844 << D.getCXXScopeSpec().getRange(); 6845 NewVD->setInvalidDecl(); 6846 } 6847 6848 if (!IsVariableTemplateSpecialization) 6849 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6850 6851 if (NewTemplate) { 6852 VarTemplateDecl *PrevVarTemplate = 6853 NewVD->getPreviousDecl() 6854 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6855 : nullptr; 6856 6857 // Check the template parameter list of this declaration, possibly 6858 // merging in the template parameter list from the previous variable 6859 // template declaration. 6860 if (CheckTemplateParameterList( 6861 TemplateParams, 6862 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6863 : nullptr, 6864 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6865 DC->isDependentContext()) 6866 ? TPC_ClassTemplateMember 6867 : TPC_VarTemplate)) 6868 NewVD->setInvalidDecl(); 6869 6870 // If we are providing an explicit specialization of a static variable 6871 // template, make a note of that. 6872 if (PrevVarTemplate && 6873 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6874 PrevVarTemplate->setMemberSpecialization(); 6875 } 6876 } 6877 6878 // Diagnose shadowed variables iff this isn't a redeclaration. 6879 if (ShadowedDecl && !D.isRedeclaration()) 6880 CheckShadow(NewVD, ShadowedDecl, Previous); 6881 6882 ProcessPragmaWeak(S, NewVD); 6883 6884 // If this is the first declaration of an extern C variable, update 6885 // the map of such variables. 6886 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6887 isIncompleteDeclExternC(*this, NewVD)) 6888 RegisterLocallyScopedExternCDecl(NewVD, S); 6889 6890 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6891 Decl *ManglingContextDecl; 6892 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6893 NewVD->getDeclContext(), ManglingContextDecl)) { 6894 Context.setManglingNumber( 6895 NewVD, MCtx->getManglingNumber( 6896 NewVD, getMSManglingNumber(getLangOpts(), S))); 6897 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6898 } 6899 } 6900 6901 // Special handling of variable named 'main'. 6902 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6903 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6904 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6905 6906 // C++ [basic.start.main]p3 6907 // A program that declares a variable main at global scope is ill-formed. 6908 if (getLangOpts().CPlusPlus) 6909 Diag(D.getLocStart(), diag::err_main_global_variable); 6910 6911 // In C, and external-linkage variable named main results in undefined 6912 // behavior. 6913 else if (NewVD->hasExternalFormalLinkage()) 6914 Diag(D.getLocStart(), diag::warn_main_redefined); 6915 } 6916 6917 if (D.isRedeclaration() && !Previous.empty()) { 6918 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6919 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6920 D.isFunctionDefinition()); 6921 } 6922 6923 if (NewTemplate) { 6924 if (NewVD->isInvalidDecl()) 6925 NewTemplate->setInvalidDecl(); 6926 ActOnDocumentableDecl(NewTemplate); 6927 return NewTemplate; 6928 } 6929 6930 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6931 CompleteMemberSpecialization(NewVD, Previous); 6932 6933 return NewVD; 6934 } 6935 6936 /// Enum describing the %select options in diag::warn_decl_shadow. 6937 enum ShadowedDeclKind { 6938 SDK_Local, 6939 SDK_Global, 6940 SDK_StaticMember, 6941 SDK_Field, 6942 SDK_Typedef, 6943 SDK_Using 6944 }; 6945 6946 /// Determine what kind of declaration we're shadowing. 6947 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6948 const DeclContext *OldDC) { 6949 if (isa<TypeAliasDecl>(ShadowedDecl)) 6950 return SDK_Using; 6951 else if (isa<TypedefDecl>(ShadowedDecl)) 6952 return SDK_Typedef; 6953 else if (isa<RecordDecl>(OldDC)) 6954 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6955 6956 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6957 } 6958 6959 /// Return the location of the capture if the given lambda captures the given 6960 /// variable \p VD, or an invalid source location otherwise. 6961 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6962 const VarDecl *VD) { 6963 for (const Capture &Capture : LSI->Captures) { 6964 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6965 return Capture.getLocation(); 6966 } 6967 return SourceLocation(); 6968 } 6969 6970 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6971 const LookupResult &R) { 6972 // Only diagnose if we're shadowing an unambiguous field or variable. 6973 if (R.getResultKind() != LookupResult::Found) 6974 return false; 6975 6976 // Return false if warning is ignored. 6977 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6978 } 6979 6980 /// Return the declaration shadowed by the given variable \p D, or null 6981 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6982 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6983 const LookupResult &R) { 6984 if (!shouldWarnIfShadowedDecl(Diags, R)) 6985 return nullptr; 6986 6987 // Don't diagnose declarations at file scope. 6988 if (D->hasGlobalStorage()) 6989 return nullptr; 6990 6991 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6992 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6993 ? ShadowedDecl 6994 : nullptr; 6995 } 6996 6997 /// Return the declaration shadowed by the given typedef \p D, or null 6998 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6999 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7000 const LookupResult &R) { 7001 // Don't warn if typedef declaration is part of a class 7002 if (D->getDeclContext()->isRecord()) 7003 return nullptr; 7004 7005 if (!shouldWarnIfShadowedDecl(Diags, R)) 7006 return nullptr; 7007 7008 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7009 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7010 } 7011 7012 /// Diagnose variable or built-in function shadowing. Implements 7013 /// -Wshadow. 7014 /// 7015 /// This method is called whenever a VarDecl is added to a "useful" 7016 /// scope. 7017 /// 7018 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7019 /// \param R the lookup of the name 7020 /// 7021 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7022 const LookupResult &R) { 7023 DeclContext *NewDC = D->getDeclContext(); 7024 7025 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7026 // Fields are not shadowed by variables in C++ static methods. 7027 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7028 if (MD->isStatic()) 7029 return; 7030 7031 // Fields shadowed by constructor parameters are a special case. Usually 7032 // the constructor initializes the field with the parameter. 7033 if (isa<CXXConstructorDecl>(NewDC)) 7034 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7035 // Remember that this was shadowed so we can either warn about its 7036 // modification or its existence depending on warning settings. 7037 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7038 return; 7039 } 7040 } 7041 7042 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7043 if (shadowedVar->isExternC()) { 7044 // For shadowing external vars, make sure that we point to the global 7045 // declaration, not a locally scoped extern declaration. 7046 for (auto I : shadowedVar->redecls()) 7047 if (I->isFileVarDecl()) { 7048 ShadowedDecl = I; 7049 break; 7050 } 7051 } 7052 7053 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7054 7055 unsigned WarningDiag = diag::warn_decl_shadow; 7056 SourceLocation CaptureLoc; 7057 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7058 isa<CXXMethodDecl>(NewDC)) { 7059 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7060 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7061 if (RD->getLambdaCaptureDefault() == LCD_None) { 7062 // Try to avoid warnings for lambdas with an explicit capture list. 7063 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7064 // Warn only when the lambda captures the shadowed decl explicitly. 7065 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7066 if (CaptureLoc.isInvalid()) 7067 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7068 } else { 7069 // Remember that this was shadowed so we can avoid the warning if the 7070 // shadowed decl isn't captured and the warning settings allow it. 7071 cast<LambdaScopeInfo>(getCurFunction()) 7072 ->ShadowingDecls.push_back( 7073 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7074 return; 7075 } 7076 } 7077 7078 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7079 // A variable can't shadow a local variable in an enclosing scope, if 7080 // they are separated by a non-capturing declaration context. 7081 for (DeclContext *ParentDC = NewDC; 7082 ParentDC && !ParentDC->Equals(OldDC); 7083 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7084 // Only block literals, captured statements, and lambda expressions 7085 // can capture; other scopes don't. 7086 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7087 !isLambdaCallOperator(ParentDC)) { 7088 return; 7089 } 7090 } 7091 } 7092 } 7093 } 7094 7095 // Only warn about certain kinds of shadowing for class members. 7096 if (NewDC && NewDC->isRecord()) { 7097 // In particular, don't warn about shadowing non-class members. 7098 if (!OldDC->isRecord()) 7099 return; 7100 7101 // TODO: should we warn about static data members shadowing 7102 // static data members from base classes? 7103 7104 // TODO: don't diagnose for inaccessible shadowed members. 7105 // This is hard to do perfectly because we might friend the 7106 // shadowing context, but that's just a false negative. 7107 } 7108 7109 7110 DeclarationName Name = R.getLookupName(); 7111 7112 // Emit warning and note. 7113 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7114 return; 7115 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7116 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7117 if (!CaptureLoc.isInvalid()) 7118 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7119 << Name << /*explicitly*/ 1; 7120 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7121 } 7122 7123 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7124 /// when these variables are captured by the lambda. 7125 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7126 for (const auto &Shadow : LSI->ShadowingDecls) { 7127 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7128 // Try to avoid the warning when the shadowed decl isn't captured. 7129 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7130 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7131 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7132 ? diag::warn_decl_shadow_uncaptured_local 7133 : diag::warn_decl_shadow) 7134 << Shadow.VD->getDeclName() 7135 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7136 if (!CaptureLoc.isInvalid()) 7137 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7138 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7139 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7140 } 7141 } 7142 7143 /// Check -Wshadow without the advantage of a previous lookup. 7144 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7145 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7146 return; 7147 7148 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7149 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7150 LookupName(R, S); 7151 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7152 CheckShadow(D, ShadowedDecl, R); 7153 } 7154 7155 /// Check if 'E', which is an expression that is about to be modified, refers 7156 /// to a constructor parameter that shadows a field. 7157 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7158 // Quickly ignore expressions that can't be shadowing ctor parameters. 7159 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7160 return; 7161 E = E->IgnoreParenImpCasts(); 7162 auto *DRE = dyn_cast<DeclRefExpr>(E); 7163 if (!DRE) 7164 return; 7165 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7166 auto I = ShadowingDecls.find(D); 7167 if (I == ShadowingDecls.end()) 7168 return; 7169 const NamedDecl *ShadowedDecl = I->second; 7170 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7171 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7172 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7173 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7174 7175 // Avoid issuing multiple warnings about the same decl. 7176 ShadowingDecls.erase(I); 7177 } 7178 7179 /// Check for conflict between this global or extern "C" declaration and 7180 /// previous global or extern "C" declarations. This is only used in C++. 7181 template<typename T> 7182 static bool checkGlobalOrExternCConflict( 7183 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7184 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7185 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7186 7187 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7188 // The common case: this global doesn't conflict with any extern "C" 7189 // declaration. 7190 return false; 7191 } 7192 7193 if (Prev) { 7194 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7195 // Both the old and new declarations have C language linkage. This is a 7196 // redeclaration. 7197 Previous.clear(); 7198 Previous.addDecl(Prev); 7199 return true; 7200 } 7201 7202 // This is a global, non-extern "C" declaration, and there is a previous 7203 // non-global extern "C" declaration. Diagnose if this is a variable 7204 // declaration. 7205 if (!isa<VarDecl>(ND)) 7206 return false; 7207 } else { 7208 // The declaration is extern "C". Check for any declaration in the 7209 // translation unit which might conflict. 7210 if (IsGlobal) { 7211 // We have already performed the lookup into the translation unit. 7212 IsGlobal = false; 7213 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7214 I != E; ++I) { 7215 if (isa<VarDecl>(*I)) { 7216 Prev = *I; 7217 break; 7218 } 7219 } 7220 } else { 7221 DeclContext::lookup_result R = 7222 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7223 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7224 I != E; ++I) { 7225 if (isa<VarDecl>(*I)) { 7226 Prev = *I; 7227 break; 7228 } 7229 // FIXME: If we have any other entity with this name in global scope, 7230 // the declaration is ill-formed, but that is a defect: it breaks the 7231 // 'stat' hack, for instance. Only variables can have mangled name 7232 // clashes with extern "C" declarations, so only they deserve a 7233 // diagnostic. 7234 } 7235 } 7236 7237 if (!Prev) 7238 return false; 7239 } 7240 7241 // Use the first declaration's location to ensure we point at something which 7242 // is lexically inside an extern "C" linkage-spec. 7243 assert(Prev && "should have found a previous declaration to diagnose"); 7244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7245 Prev = FD->getFirstDecl(); 7246 else 7247 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7248 7249 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7250 << IsGlobal << ND; 7251 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7252 << IsGlobal; 7253 return false; 7254 } 7255 7256 /// Apply special rules for handling extern "C" declarations. Returns \c true 7257 /// if we have found that this is a redeclaration of some prior entity. 7258 /// 7259 /// Per C++ [dcl.link]p6: 7260 /// Two declarations [for a function or variable] with C language linkage 7261 /// with the same name that appear in different scopes refer to the same 7262 /// [entity]. An entity with C language linkage shall not be declared with 7263 /// the same name as an entity in global scope. 7264 template<typename T> 7265 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7266 LookupResult &Previous) { 7267 if (!S.getLangOpts().CPlusPlus) { 7268 // In C, when declaring a global variable, look for a corresponding 'extern' 7269 // variable declared in function scope. We don't need this in C++, because 7270 // we find local extern decls in the surrounding file-scope DeclContext. 7271 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7272 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7273 Previous.clear(); 7274 Previous.addDecl(Prev); 7275 return true; 7276 } 7277 } 7278 return false; 7279 } 7280 7281 // A declaration in the translation unit can conflict with an extern "C" 7282 // declaration. 7283 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7284 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7285 7286 // An extern "C" declaration can conflict with a declaration in the 7287 // translation unit or can be a redeclaration of an extern "C" declaration 7288 // in another scope. 7289 if (isIncompleteDeclExternC(S,ND)) 7290 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7291 7292 // Neither global nor extern "C": nothing to do. 7293 return false; 7294 } 7295 7296 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7297 // If the decl is already known invalid, don't check it. 7298 if (NewVD->isInvalidDecl()) 7299 return; 7300 7301 QualType T = NewVD->getType(); 7302 7303 // Defer checking an 'auto' type until its initializer is attached. 7304 if (T->isUndeducedType()) 7305 return; 7306 7307 if (NewVD->hasAttrs()) 7308 CheckAlignasUnderalignment(NewVD); 7309 7310 if (T->isObjCObjectType()) { 7311 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7312 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7313 T = Context.getObjCObjectPointerType(T); 7314 NewVD->setType(T); 7315 } 7316 7317 // Emit an error if an address space was applied to decl with local storage. 7318 // This includes arrays of objects with address space qualifiers, but not 7319 // automatic variables that point to other address spaces. 7320 // ISO/IEC TR 18037 S5.1.2 7321 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7322 T.getAddressSpace() != LangAS::Default) { 7323 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7324 NewVD->setInvalidDecl(); 7325 return; 7326 } 7327 7328 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7329 // scope. 7330 if (getLangOpts().OpenCLVersion == 120 && 7331 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7332 NewVD->isStaticLocal()) { 7333 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7334 NewVD->setInvalidDecl(); 7335 return; 7336 } 7337 7338 if (getLangOpts().OpenCL) { 7339 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7340 if (NewVD->hasAttr<BlocksAttr>()) { 7341 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7342 return; 7343 } 7344 7345 if (T->isBlockPointerType()) { 7346 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7347 // can't use 'extern' storage class. 7348 if (!T.isConstQualified()) { 7349 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7350 << 0 /*const*/; 7351 NewVD->setInvalidDecl(); 7352 return; 7353 } 7354 if (NewVD->hasExternalStorage()) { 7355 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7356 NewVD->setInvalidDecl(); 7357 return; 7358 } 7359 } 7360 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7361 // __constant address space. 7362 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7363 // variables inside a function can also be declared in the global 7364 // address space. 7365 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7366 NewVD->hasExternalStorage()) { 7367 if (!T->isSamplerT() && 7368 !(T.getAddressSpace() == LangAS::opencl_constant || 7369 (T.getAddressSpace() == LangAS::opencl_global && 7370 getLangOpts().OpenCLVersion == 200))) { 7371 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7372 if (getLangOpts().OpenCLVersion == 200) 7373 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7374 << Scope << "global or constant"; 7375 else 7376 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7377 << Scope << "constant"; 7378 NewVD->setInvalidDecl(); 7379 return; 7380 } 7381 } else { 7382 if (T.getAddressSpace() == LangAS::opencl_global) { 7383 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7384 << 1 /*is any function*/ << "global"; 7385 NewVD->setInvalidDecl(); 7386 return; 7387 } 7388 if (T.getAddressSpace() == LangAS::opencl_constant || 7389 T.getAddressSpace() == LangAS::opencl_local) { 7390 FunctionDecl *FD = getCurFunctionDecl(); 7391 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7392 // in functions. 7393 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7394 if (T.getAddressSpace() == LangAS::opencl_constant) 7395 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7396 << 0 /*non-kernel only*/ << "constant"; 7397 else 7398 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7399 << 0 /*non-kernel only*/ << "local"; 7400 NewVD->setInvalidDecl(); 7401 return; 7402 } 7403 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7404 // in the outermost scope of a kernel function. 7405 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7406 if (!getCurScope()->isFunctionScope()) { 7407 if (T.getAddressSpace() == LangAS::opencl_constant) 7408 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7409 << "constant"; 7410 else 7411 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7412 << "local"; 7413 NewVD->setInvalidDecl(); 7414 return; 7415 } 7416 } 7417 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7418 // Do not allow other address spaces on automatic variable. 7419 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7420 NewVD->setInvalidDecl(); 7421 return; 7422 } 7423 } 7424 } 7425 7426 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7427 && !NewVD->hasAttr<BlocksAttr>()) { 7428 if (getLangOpts().getGC() != LangOptions::NonGC) 7429 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7430 else { 7431 assert(!getLangOpts().ObjCAutoRefCount); 7432 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7433 } 7434 } 7435 7436 bool isVM = T->isVariablyModifiedType(); 7437 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7438 NewVD->hasAttr<BlocksAttr>()) 7439 setFunctionHasBranchProtectedScope(); 7440 7441 if ((isVM && NewVD->hasLinkage()) || 7442 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7443 bool SizeIsNegative; 7444 llvm::APSInt Oversized; 7445 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7446 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7447 QualType FixedT; 7448 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7449 FixedT = FixedTInfo->getType(); 7450 else if (FixedTInfo) { 7451 // Type and type-as-written are canonically different. We need to fix up 7452 // both types separately. 7453 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7454 Oversized); 7455 } 7456 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7457 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7458 // FIXME: This won't give the correct result for 7459 // int a[10][n]; 7460 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7461 7462 if (NewVD->isFileVarDecl()) 7463 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7464 << SizeRange; 7465 else if (NewVD->isStaticLocal()) 7466 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7467 << SizeRange; 7468 else 7469 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7470 << SizeRange; 7471 NewVD->setInvalidDecl(); 7472 return; 7473 } 7474 7475 if (!FixedTInfo) { 7476 if (NewVD->isFileVarDecl()) 7477 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7478 else 7479 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7480 NewVD->setInvalidDecl(); 7481 return; 7482 } 7483 7484 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7485 NewVD->setType(FixedT); 7486 NewVD->setTypeSourceInfo(FixedTInfo); 7487 } 7488 7489 if (T->isVoidType()) { 7490 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7491 // of objects and functions. 7492 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7493 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7494 << T; 7495 NewVD->setInvalidDecl(); 7496 return; 7497 } 7498 } 7499 7500 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7501 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7502 NewVD->setInvalidDecl(); 7503 return; 7504 } 7505 7506 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7507 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7508 NewVD->setInvalidDecl(); 7509 return; 7510 } 7511 7512 if (NewVD->isConstexpr() && !T->isDependentType() && 7513 RequireLiteralType(NewVD->getLocation(), T, 7514 diag::err_constexpr_var_non_literal)) { 7515 NewVD->setInvalidDecl(); 7516 return; 7517 } 7518 } 7519 7520 /// Perform semantic checking on a newly-created variable 7521 /// declaration. 7522 /// 7523 /// This routine performs all of the type-checking required for a 7524 /// variable declaration once it has been built. It is used both to 7525 /// check variables after they have been parsed and their declarators 7526 /// have been translated into a declaration, and to check variables 7527 /// that have been instantiated from a template. 7528 /// 7529 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7530 /// 7531 /// Returns true if the variable declaration is a redeclaration. 7532 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7533 CheckVariableDeclarationType(NewVD); 7534 7535 // If the decl is already known invalid, don't check it. 7536 if (NewVD->isInvalidDecl()) 7537 return false; 7538 7539 // If we did not find anything by this name, look for a non-visible 7540 // extern "C" declaration with the same name. 7541 if (Previous.empty() && 7542 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7543 Previous.setShadowed(); 7544 7545 if (!Previous.empty()) { 7546 MergeVarDecl(NewVD, Previous); 7547 return true; 7548 } 7549 return false; 7550 } 7551 7552 namespace { 7553 struct FindOverriddenMethod { 7554 Sema *S; 7555 CXXMethodDecl *Method; 7556 7557 /// Member lookup function that determines whether a given C++ 7558 /// method overrides a method in a base class, to be used with 7559 /// CXXRecordDecl::lookupInBases(). 7560 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7561 RecordDecl *BaseRecord = 7562 Specifier->getType()->getAs<RecordType>()->getDecl(); 7563 7564 DeclarationName Name = Method->getDeclName(); 7565 7566 // FIXME: Do we care about other names here too? 7567 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7568 // We really want to find the base class destructor here. 7569 QualType T = S->Context.getTypeDeclType(BaseRecord); 7570 CanQualType CT = S->Context.getCanonicalType(T); 7571 7572 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7573 } 7574 7575 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7576 Path.Decls = Path.Decls.slice(1)) { 7577 NamedDecl *D = Path.Decls.front(); 7578 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7579 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7580 return true; 7581 } 7582 } 7583 7584 return false; 7585 } 7586 }; 7587 7588 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7589 } // end anonymous namespace 7590 7591 /// Report an error regarding overriding, along with any relevant 7592 /// overridden methods. 7593 /// 7594 /// \param DiagID the primary error to report. 7595 /// \param MD the overriding method. 7596 /// \param OEK which overrides to include as notes. 7597 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7598 OverrideErrorKind OEK = OEK_All) { 7599 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7600 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7601 // This check (& the OEK parameter) could be replaced by a predicate, but 7602 // without lambdas that would be overkill. This is still nicer than writing 7603 // out the diag loop 3 times. 7604 if ((OEK == OEK_All) || 7605 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7606 (OEK == OEK_Deleted && O->isDeleted())) 7607 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7608 } 7609 } 7610 7611 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7612 /// and if so, check that it's a valid override and remember it. 7613 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7614 // Look for methods in base classes that this method might override. 7615 CXXBasePaths Paths; 7616 FindOverriddenMethod FOM; 7617 FOM.Method = MD; 7618 FOM.S = this; 7619 bool hasDeletedOverridenMethods = false; 7620 bool hasNonDeletedOverridenMethods = false; 7621 bool AddedAny = false; 7622 if (DC->lookupInBases(FOM, Paths)) { 7623 for (auto *I : Paths.found_decls()) { 7624 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7625 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7626 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7627 !CheckOverridingFunctionAttributes(MD, OldMD) && 7628 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7629 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7630 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7631 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7632 AddedAny = true; 7633 } 7634 } 7635 } 7636 } 7637 7638 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7639 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7640 } 7641 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7642 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7643 } 7644 7645 return AddedAny; 7646 } 7647 7648 namespace { 7649 // Struct for holding all of the extra arguments needed by 7650 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7651 struct ActOnFDArgs { 7652 Scope *S; 7653 Declarator &D; 7654 MultiTemplateParamsArg TemplateParamLists; 7655 bool AddToScope; 7656 }; 7657 } // end anonymous namespace 7658 7659 namespace { 7660 7661 // Callback to only accept typo corrections that have a non-zero edit distance. 7662 // Also only accept corrections that have the same parent decl. 7663 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7664 public: 7665 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7666 CXXRecordDecl *Parent) 7667 : Context(Context), OriginalFD(TypoFD), 7668 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7669 7670 bool ValidateCandidate(const TypoCorrection &candidate) override { 7671 if (candidate.getEditDistance() == 0) 7672 return false; 7673 7674 SmallVector<unsigned, 1> MismatchedParams; 7675 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7676 CDeclEnd = candidate.end(); 7677 CDecl != CDeclEnd; ++CDecl) { 7678 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7679 7680 if (FD && !FD->hasBody() && 7681 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7682 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7683 CXXRecordDecl *Parent = MD->getParent(); 7684 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7685 return true; 7686 } else if (!ExpectedParent) { 7687 return true; 7688 } 7689 } 7690 } 7691 7692 return false; 7693 } 7694 7695 private: 7696 ASTContext &Context; 7697 FunctionDecl *OriginalFD; 7698 CXXRecordDecl *ExpectedParent; 7699 }; 7700 7701 } // end anonymous namespace 7702 7703 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7704 TypoCorrectedFunctionDefinitions.insert(F); 7705 } 7706 7707 /// Generate diagnostics for an invalid function redeclaration. 7708 /// 7709 /// This routine handles generating the diagnostic messages for an invalid 7710 /// function redeclaration, including finding possible similar declarations 7711 /// or performing typo correction if there are no previous declarations with 7712 /// the same name. 7713 /// 7714 /// Returns a NamedDecl iff typo correction was performed and substituting in 7715 /// the new declaration name does not cause new errors. 7716 static NamedDecl *DiagnoseInvalidRedeclaration( 7717 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7718 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7719 DeclarationName Name = NewFD->getDeclName(); 7720 DeclContext *NewDC = NewFD->getDeclContext(); 7721 SmallVector<unsigned, 1> MismatchedParams; 7722 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7723 TypoCorrection Correction; 7724 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7725 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7726 : diag::err_member_decl_does_not_match; 7727 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7728 IsLocalFriend ? Sema::LookupLocalFriendName 7729 : Sema::LookupOrdinaryName, 7730 Sema::ForVisibleRedeclaration); 7731 7732 NewFD->setInvalidDecl(); 7733 if (IsLocalFriend) 7734 SemaRef.LookupName(Prev, S); 7735 else 7736 SemaRef.LookupQualifiedName(Prev, NewDC); 7737 assert(!Prev.isAmbiguous() && 7738 "Cannot have an ambiguity in previous-declaration lookup"); 7739 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7740 if (!Prev.empty()) { 7741 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7742 Func != FuncEnd; ++Func) { 7743 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7744 if (FD && 7745 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7746 // Add 1 to the index so that 0 can mean the mismatch didn't 7747 // involve a parameter 7748 unsigned ParamNum = 7749 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7750 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7751 } 7752 } 7753 // If the qualified name lookup yielded nothing, try typo correction 7754 } else if ((Correction = SemaRef.CorrectTypo( 7755 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7756 &ExtraArgs.D.getCXXScopeSpec(), 7757 llvm::make_unique<DifferentNameValidatorCCC>( 7758 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7759 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7760 // Set up everything for the call to ActOnFunctionDeclarator 7761 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7762 ExtraArgs.D.getIdentifierLoc()); 7763 Previous.clear(); 7764 Previous.setLookupName(Correction.getCorrection()); 7765 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7766 CDeclEnd = Correction.end(); 7767 CDecl != CDeclEnd; ++CDecl) { 7768 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7769 if (FD && !FD->hasBody() && 7770 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7771 Previous.addDecl(FD); 7772 } 7773 } 7774 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7775 7776 NamedDecl *Result; 7777 // Retry building the function declaration with the new previous 7778 // declarations, and with errors suppressed. 7779 { 7780 // Trap errors. 7781 Sema::SFINAETrap Trap(SemaRef); 7782 7783 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7784 // pieces need to verify the typo-corrected C++ declaration and hopefully 7785 // eliminate the need for the parameter pack ExtraArgs. 7786 Result = SemaRef.ActOnFunctionDeclarator( 7787 ExtraArgs.S, ExtraArgs.D, 7788 Correction.getCorrectionDecl()->getDeclContext(), 7789 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7790 ExtraArgs.AddToScope); 7791 7792 if (Trap.hasErrorOccurred()) 7793 Result = nullptr; 7794 } 7795 7796 if (Result) { 7797 // Determine which correction we picked. 7798 Decl *Canonical = Result->getCanonicalDecl(); 7799 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7800 I != E; ++I) 7801 if ((*I)->getCanonicalDecl() == Canonical) 7802 Correction.setCorrectionDecl(*I); 7803 7804 // Let Sema know about the correction. 7805 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7806 SemaRef.diagnoseTypo( 7807 Correction, 7808 SemaRef.PDiag(IsLocalFriend 7809 ? diag::err_no_matching_local_friend_suggest 7810 : diag::err_member_decl_does_not_match_suggest) 7811 << Name << NewDC << IsDefinition); 7812 return Result; 7813 } 7814 7815 // Pretend the typo correction never occurred 7816 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7817 ExtraArgs.D.getIdentifierLoc()); 7818 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7819 Previous.clear(); 7820 Previous.setLookupName(Name); 7821 } 7822 7823 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7824 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7825 7826 bool NewFDisConst = false; 7827 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7828 NewFDisConst = NewMD->isConst(); 7829 7830 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7831 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7832 NearMatch != NearMatchEnd; ++NearMatch) { 7833 FunctionDecl *FD = NearMatch->first; 7834 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7835 bool FDisConst = MD && MD->isConst(); 7836 bool IsMember = MD || !IsLocalFriend; 7837 7838 // FIXME: These notes are poorly worded for the local friend case. 7839 if (unsigned Idx = NearMatch->second) { 7840 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7841 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7842 if (Loc.isInvalid()) Loc = FD->getLocation(); 7843 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7844 : diag::note_local_decl_close_param_match) 7845 << Idx << FDParam->getType() 7846 << NewFD->getParamDecl(Idx - 1)->getType(); 7847 } else if (FDisConst != NewFDisConst) { 7848 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7849 << NewFDisConst << FD->getSourceRange().getEnd(); 7850 } else 7851 SemaRef.Diag(FD->getLocation(), 7852 IsMember ? diag::note_member_def_close_match 7853 : diag::note_local_decl_close_match); 7854 } 7855 return nullptr; 7856 } 7857 7858 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7859 switch (D.getDeclSpec().getStorageClassSpec()) { 7860 default: llvm_unreachable("Unknown storage class!"); 7861 case DeclSpec::SCS_auto: 7862 case DeclSpec::SCS_register: 7863 case DeclSpec::SCS_mutable: 7864 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7865 diag::err_typecheck_sclass_func); 7866 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7867 D.setInvalidType(); 7868 break; 7869 case DeclSpec::SCS_unspecified: break; 7870 case DeclSpec::SCS_extern: 7871 if (D.getDeclSpec().isExternInLinkageSpec()) 7872 return SC_None; 7873 return SC_Extern; 7874 case DeclSpec::SCS_static: { 7875 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7876 // C99 6.7.1p5: 7877 // The declaration of an identifier for a function that has 7878 // block scope shall have no explicit storage-class specifier 7879 // other than extern 7880 // See also (C++ [dcl.stc]p4). 7881 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7882 diag::err_static_block_func); 7883 break; 7884 } else 7885 return SC_Static; 7886 } 7887 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7888 } 7889 7890 // No explicit storage class has already been returned 7891 return SC_None; 7892 } 7893 7894 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7895 DeclContext *DC, QualType &R, 7896 TypeSourceInfo *TInfo, 7897 StorageClass SC, 7898 bool &IsVirtualOkay) { 7899 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7900 DeclarationName Name = NameInfo.getName(); 7901 7902 FunctionDecl *NewFD = nullptr; 7903 bool isInline = D.getDeclSpec().isInlineSpecified(); 7904 7905 if (!SemaRef.getLangOpts().CPlusPlus) { 7906 // Determine whether the function was written with a 7907 // prototype. This true when: 7908 // - there is a prototype in the declarator, or 7909 // - the type R of the function is some kind of typedef or other non- 7910 // attributed reference to a type name (which eventually refers to a 7911 // function type). 7912 bool HasPrototype = 7913 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7914 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7915 7916 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7917 D.getLocStart(), NameInfo, R, 7918 TInfo, SC, isInline, 7919 HasPrototype, false); 7920 if (D.isInvalidType()) 7921 NewFD->setInvalidDecl(); 7922 7923 return NewFD; 7924 } 7925 7926 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7927 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7928 7929 // Check that the return type is not an abstract class type. 7930 // For record types, this is done by the AbstractClassUsageDiagnoser once 7931 // the class has been completely parsed. 7932 if (!DC->isRecord() && 7933 SemaRef.RequireNonAbstractType( 7934 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7935 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7936 D.setInvalidType(); 7937 7938 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7939 // This is a C++ constructor declaration. 7940 assert(DC->isRecord() && 7941 "Constructors can only be declared in a member context"); 7942 7943 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7944 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7945 D.getLocStart(), NameInfo, 7946 R, TInfo, isExplicit, isInline, 7947 /*isImplicitlyDeclared=*/false, 7948 isConstexpr); 7949 7950 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7951 // This is a C++ destructor declaration. 7952 if (DC->isRecord()) { 7953 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7954 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7955 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7956 SemaRef.Context, Record, 7957 D.getLocStart(), 7958 NameInfo, R, TInfo, isInline, 7959 /*isImplicitlyDeclared=*/false); 7960 7961 // If the class is complete, then we now create the implicit exception 7962 // specification. If the class is incomplete or dependent, we can't do 7963 // it yet. 7964 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7965 Record->getDefinition() && !Record->isBeingDefined() && 7966 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7967 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7968 } 7969 7970 IsVirtualOkay = true; 7971 return NewDD; 7972 7973 } else { 7974 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7975 D.setInvalidType(); 7976 7977 // Create a FunctionDecl to satisfy the function definition parsing 7978 // code path. 7979 return FunctionDecl::Create(SemaRef.Context, DC, 7980 D.getLocStart(), 7981 D.getIdentifierLoc(), Name, R, TInfo, 7982 SC, isInline, 7983 /*hasPrototype=*/true, isConstexpr); 7984 } 7985 7986 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7987 if (!DC->isRecord()) { 7988 SemaRef.Diag(D.getIdentifierLoc(), 7989 diag::err_conv_function_not_member); 7990 return nullptr; 7991 } 7992 7993 SemaRef.CheckConversionDeclarator(D, R, SC); 7994 IsVirtualOkay = true; 7995 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7996 D.getLocStart(), NameInfo, 7997 R, TInfo, isInline, isExplicit, 7998 isConstexpr, SourceLocation()); 7999 8000 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8001 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8002 8003 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 8004 isExplicit, NameInfo, R, TInfo, 8005 D.getLocEnd()); 8006 } else if (DC->isRecord()) { 8007 // If the name of the function is the same as the name of the record, 8008 // then this must be an invalid constructor that has a return type. 8009 // (The parser checks for a return type and makes the declarator a 8010 // constructor if it has no return type). 8011 if (Name.getAsIdentifierInfo() && 8012 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8013 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8014 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8015 << SourceRange(D.getIdentifierLoc()); 8016 return nullptr; 8017 } 8018 8019 // This is a C++ method declaration. 8020 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 8021 cast<CXXRecordDecl>(DC), 8022 D.getLocStart(), NameInfo, R, 8023 TInfo, SC, isInline, 8024 isConstexpr, SourceLocation()); 8025 IsVirtualOkay = !Ret->isStatic(); 8026 return Ret; 8027 } else { 8028 bool isFriend = 8029 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8030 if (!isFriend && SemaRef.CurContext->isRecord()) 8031 return nullptr; 8032 8033 // Determine whether the function was written with a 8034 // prototype. This true when: 8035 // - we're in C++ (where every function has a prototype), 8036 return FunctionDecl::Create(SemaRef.Context, DC, 8037 D.getLocStart(), 8038 NameInfo, R, TInfo, SC, isInline, 8039 true/*HasPrototype*/, isConstexpr); 8040 } 8041 } 8042 8043 enum OpenCLParamType { 8044 ValidKernelParam, 8045 PtrPtrKernelParam, 8046 PtrKernelParam, 8047 InvalidAddrSpacePtrKernelParam, 8048 InvalidKernelParam, 8049 RecordKernelParam 8050 }; 8051 8052 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8053 if (PT->isPointerType()) { 8054 QualType PointeeType = PT->getPointeeType(); 8055 if (PointeeType->isPointerType()) 8056 return PtrPtrKernelParam; 8057 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8058 PointeeType.getAddressSpace() == LangAS::opencl_private || 8059 PointeeType.getAddressSpace() == LangAS::Default) 8060 return InvalidAddrSpacePtrKernelParam; 8061 return PtrKernelParam; 8062 } 8063 8064 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 8065 // be used as builtin types. 8066 8067 if (PT->isImageType()) 8068 return PtrKernelParam; 8069 8070 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8071 return InvalidKernelParam; 8072 8073 // OpenCL extension spec v1.2 s9.5: 8074 // This extension adds support for half scalar and vector types as built-in 8075 // types that can be used for arithmetic operations, conversions etc. 8076 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8077 return InvalidKernelParam; 8078 8079 if (PT->isRecordType()) 8080 return RecordKernelParam; 8081 8082 return ValidKernelParam; 8083 } 8084 8085 static void checkIsValidOpenCLKernelParameter( 8086 Sema &S, 8087 Declarator &D, 8088 ParmVarDecl *Param, 8089 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8090 QualType PT = Param->getType(); 8091 8092 // Cache the valid types we encounter to avoid rechecking structs that are 8093 // used again 8094 if (ValidTypes.count(PT.getTypePtr())) 8095 return; 8096 8097 switch (getOpenCLKernelParameterType(S, PT)) { 8098 case PtrPtrKernelParam: 8099 // OpenCL v1.2 s6.9.a: 8100 // A kernel function argument cannot be declared as a 8101 // pointer to a pointer type. 8102 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8103 D.setInvalidType(); 8104 return; 8105 8106 case InvalidAddrSpacePtrKernelParam: 8107 // OpenCL v1.0 s6.5: 8108 // __kernel function arguments declared to be a pointer of a type can point 8109 // to one of the following address spaces only : __global, __local or 8110 // __constant. 8111 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8112 D.setInvalidType(); 8113 return; 8114 8115 // OpenCL v1.2 s6.9.k: 8116 // Arguments to kernel functions in a program cannot be declared with the 8117 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8118 // uintptr_t or a struct and/or union that contain fields declared to be 8119 // one of these built-in scalar types. 8120 8121 case InvalidKernelParam: 8122 // OpenCL v1.2 s6.8 n: 8123 // A kernel function argument cannot be declared 8124 // of event_t type. 8125 // Do not diagnose half type since it is diagnosed as invalid argument 8126 // type for any function elsewhere. 8127 if (!PT->isHalfType()) 8128 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8129 D.setInvalidType(); 8130 return; 8131 8132 case PtrKernelParam: 8133 case ValidKernelParam: 8134 ValidTypes.insert(PT.getTypePtr()); 8135 return; 8136 8137 case RecordKernelParam: 8138 break; 8139 } 8140 8141 // Track nested structs we will inspect 8142 SmallVector<const Decl *, 4> VisitStack; 8143 8144 // Track where we are in the nested structs. Items will migrate from 8145 // VisitStack to HistoryStack as we do the DFS for bad field. 8146 SmallVector<const FieldDecl *, 4> HistoryStack; 8147 HistoryStack.push_back(nullptr); 8148 8149 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8150 VisitStack.push_back(PD); 8151 8152 assert(VisitStack.back() && "First decl null?"); 8153 8154 do { 8155 const Decl *Next = VisitStack.pop_back_val(); 8156 if (!Next) { 8157 assert(!HistoryStack.empty()); 8158 // Found a marker, we have gone up a level 8159 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8160 ValidTypes.insert(Hist->getType().getTypePtr()); 8161 8162 continue; 8163 } 8164 8165 // Adds everything except the original parameter declaration (which is not a 8166 // field itself) to the history stack. 8167 const RecordDecl *RD; 8168 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8169 HistoryStack.push_back(Field); 8170 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8171 } else { 8172 RD = cast<RecordDecl>(Next); 8173 } 8174 8175 // Add a null marker so we know when we've gone back up a level 8176 VisitStack.push_back(nullptr); 8177 8178 for (const auto *FD : RD->fields()) { 8179 QualType QT = FD->getType(); 8180 8181 if (ValidTypes.count(QT.getTypePtr())) 8182 continue; 8183 8184 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8185 if (ParamType == ValidKernelParam) 8186 continue; 8187 8188 if (ParamType == RecordKernelParam) { 8189 VisitStack.push_back(FD); 8190 continue; 8191 } 8192 8193 // OpenCL v1.2 s6.9.p: 8194 // Arguments to kernel functions that are declared to be a struct or union 8195 // do not allow OpenCL objects to be passed as elements of the struct or 8196 // union. 8197 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8198 ParamType == InvalidAddrSpacePtrKernelParam) { 8199 S.Diag(Param->getLocation(), 8200 diag::err_record_with_pointers_kernel_param) 8201 << PT->isUnionType() 8202 << PT; 8203 } else { 8204 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8205 } 8206 8207 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8208 << PD->getDeclName(); 8209 8210 // We have an error, now let's go back up through history and show where 8211 // the offending field came from 8212 for (ArrayRef<const FieldDecl *>::const_iterator 8213 I = HistoryStack.begin() + 1, 8214 E = HistoryStack.end(); 8215 I != E; ++I) { 8216 const FieldDecl *OuterField = *I; 8217 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8218 << OuterField->getType(); 8219 } 8220 8221 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8222 << QT->isPointerType() 8223 << QT; 8224 D.setInvalidType(); 8225 return; 8226 } 8227 } while (!VisitStack.empty()); 8228 } 8229 8230 /// Find the DeclContext in which a tag is implicitly declared if we see an 8231 /// elaborated type specifier in the specified context, and lookup finds 8232 /// nothing. 8233 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8234 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8235 DC = DC->getParent(); 8236 return DC; 8237 } 8238 8239 /// Find the Scope in which a tag is implicitly declared if we see an 8240 /// elaborated type specifier in the specified context, and lookup finds 8241 /// nothing. 8242 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8243 while (S->isClassScope() || 8244 (LangOpts.CPlusPlus && 8245 S->isFunctionPrototypeScope()) || 8246 ((S->getFlags() & Scope::DeclScope) == 0) || 8247 (S->getEntity() && S->getEntity()->isTransparentContext())) 8248 S = S->getParent(); 8249 return S; 8250 } 8251 8252 NamedDecl* 8253 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8254 TypeSourceInfo *TInfo, LookupResult &Previous, 8255 MultiTemplateParamsArg TemplateParamLists, 8256 bool &AddToScope) { 8257 QualType R = TInfo->getType(); 8258 8259 assert(R.getTypePtr()->isFunctionType()); 8260 8261 // TODO: consider using NameInfo for diagnostic. 8262 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8263 DeclarationName Name = NameInfo.getName(); 8264 StorageClass SC = getFunctionStorageClass(*this, D); 8265 8266 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8267 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8268 diag::err_invalid_thread) 8269 << DeclSpec::getSpecifierName(TSCS); 8270 8271 if (D.isFirstDeclarationOfMember()) 8272 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8273 D.getIdentifierLoc()); 8274 8275 bool isFriend = false; 8276 FunctionTemplateDecl *FunctionTemplate = nullptr; 8277 bool isMemberSpecialization = false; 8278 bool isFunctionTemplateSpecialization = false; 8279 8280 bool isDependentClassScopeExplicitSpecialization = false; 8281 bool HasExplicitTemplateArgs = false; 8282 TemplateArgumentListInfo TemplateArgs; 8283 8284 bool isVirtualOkay = false; 8285 8286 DeclContext *OriginalDC = DC; 8287 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8288 8289 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8290 isVirtualOkay); 8291 if (!NewFD) return nullptr; 8292 8293 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8294 NewFD->setTopLevelDeclInObjCContainer(); 8295 8296 // Set the lexical context. If this is a function-scope declaration, or has a 8297 // C++ scope specifier, or is the object of a friend declaration, the lexical 8298 // context will be different from the semantic context. 8299 NewFD->setLexicalDeclContext(CurContext); 8300 8301 if (IsLocalExternDecl) 8302 NewFD->setLocalExternDecl(); 8303 8304 if (getLangOpts().CPlusPlus) { 8305 bool isInline = D.getDeclSpec().isInlineSpecified(); 8306 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8307 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8308 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8309 isFriend = D.getDeclSpec().isFriendSpecified(); 8310 if (isFriend && !isInline && D.isFunctionDefinition()) { 8311 // C++ [class.friend]p5 8312 // A function can be defined in a friend declaration of a 8313 // class . . . . Such a function is implicitly inline. 8314 NewFD->setImplicitlyInline(); 8315 } 8316 8317 // If this is a method defined in an __interface, and is not a constructor 8318 // or an overloaded operator, then set the pure flag (isVirtual will already 8319 // return true). 8320 if (const CXXRecordDecl *Parent = 8321 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8322 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8323 NewFD->setPure(true); 8324 8325 // C++ [class.union]p2 8326 // A union can have member functions, but not virtual functions. 8327 if (isVirtual && Parent->isUnion()) 8328 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8329 } 8330 8331 SetNestedNameSpecifier(NewFD, D); 8332 isMemberSpecialization = false; 8333 isFunctionTemplateSpecialization = false; 8334 if (D.isInvalidType()) 8335 NewFD->setInvalidDecl(); 8336 8337 // Match up the template parameter lists with the scope specifier, then 8338 // determine whether we have a template or a template specialization. 8339 bool Invalid = false; 8340 if (TemplateParameterList *TemplateParams = 8341 MatchTemplateParametersToScopeSpecifier( 8342 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8343 D.getCXXScopeSpec(), 8344 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8345 ? D.getName().TemplateId 8346 : nullptr, 8347 TemplateParamLists, isFriend, isMemberSpecialization, 8348 Invalid)) { 8349 if (TemplateParams->size() > 0) { 8350 // This is a function template 8351 8352 // Check that we can declare a template here. 8353 if (CheckTemplateDeclScope(S, TemplateParams)) 8354 NewFD->setInvalidDecl(); 8355 8356 // A destructor cannot be a template. 8357 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8358 Diag(NewFD->getLocation(), diag::err_destructor_template); 8359 NewFD->setInvalidDecl(); 8360 } 8361 8362 // If we're adding a template to a dependent context, we may need to 8363 // rebuilding some of the types used within the template parameter list, 8364 // now that we know what the current instantiation is. 8365 if (DC->isDependentContext()) { 8366 ContextRAII SavedContext(*this, DC); 8367 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8368 Invalid = true; 8369 } 8370 8371 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8372 NewFD->getLocation(), 8373 Name, TemplateParams, 8374 NewFD); 8375 FunctionTemplate->setLexicalDeclContext(CurContext); 8376 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8377 8378 // For source fidelity, store the other template param lists. 8379 if (TemplateParamLists.size() > 1) { 8380 NewFD->setTemplateParameterListsInfo(Context, 8381 TemplateParamLists.drop_back(1)); 8382 } 8383 } else { 8384 // This is a function template specialization. 8385 isFunctionTemplateSpecialization = true; 8386 // For source fidelity, store all the template param lists. 8387 if (TemplateParamLists.size() > 0) 8388 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8389 8390 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8391 if (isFriend) { 8392 // We want to remove the "template<>", found here. 8393 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8394 8395 // If we remove the template<> and the name is not a 8396 // template-id, we're actually silently creating a problem: 8397 // the friend declaration will refer to an untemplated decl, 8398 // and clearly the user wants a template specialization. So 8399 // we need to insert '<>' after the name. 8400 SourceLocation InsertLoc; 8401 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8402 InsertLoc = D.getName().getSourceRange().getEnd(); 8403 InsertLoc = getLocForEndOfToken(InsertLoc); 8404 } 8405 8406 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8407 << Name << RemoveRange 8408 << FixItHint::CreateRemoval(RemoveRange) 8409 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8410 } 8411 } 8412 } 8413 else { 8414 // All template param lists were matched against the scope specifier: 8415 // this is NOT (an explicit specialization of) a template. 8416 if (TemplateParamLists.size() > 0) 8417 // For source fidelity, store all the template param lists. 8418 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8419 } 8420 8421 if (Invalid) { 8422 NewFD->setInvalidDecl(); 8423 if (FunctionTemplate) 8424 FunctionTemplate->setInvalidDecl(); 8425 } 8426 8427 // C++ [dcl.fct.spec]p5: 8428 // The virtual specifier shall only be used in declarations of 8429 // nonstatic class member functions that appear within a 8430 // member-specification of a class declaration; see 10.3. 8431 // 8432 if (isVirtual && !NewFD->isInvalidDecl()) { 8433 if (!isVirtualOkay) { 8434 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8435 diag::err_virtual_non_function); 8436 } else if (!CurContext->isRecord()) { 8437 // 'virtual' was specified outside of the class. 8438 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8439 diag::err_virtual_out_of_class) 8440 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8441 } else if (NewFD->getDescribedFunctionTemplate()) { 8442 // C++ [temp.mem]p3: 8443 // A member function template shall not be virtual. 8444 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8445 diag::err_virtual_member_function_template) 8446 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8447 } else { 8448 // Okay: Add virtual to the method. 8449 NewFD->setVirtualAsWritten(true); 8450 } 8451 8452 if (getLangOpts().CPlusPlus14 && 8453 NewFD->getReturnType()->isUndeducedType()) 8454 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8455 } 8456 8457 if (getLangOpts().CPlusPlus14 && 8458 (NewFD->isDependentContext() || 8459 (isFriend && CurContext->isDependentContext())) && 8460 NewFD->getReturnType()->isUndeducedType()) { 8461 // If the function template is referenced directly (for instance, as a 8462 // member of the current instantiation), pretend it has a dependent type. 8463 // This is not really justified by the standard, but is the only sane 8464 // thing to do. 8465 // FIXME: For a friend function, we have not marked the function as being 8466 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8467 const FunctionProtoType *FPT = 8468 NewFD->getType()->castAs<FunctionProtoType>(); 8469 QualType Result = 8470 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8471 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8472 FPT->getExtProtoInfo())); 8473 } 8474 8475 // C++ [dcl.fct.spec]p3: 8476 // The inline specifier shall not appear on a block scope function 8477 // declaration. 8478 if (isInline && !NewFD->isInvalidDecl()) { 8479 if (CurContext->isFunctionOrMethod()) { 8480 // 'inline' is not allowed on block scope function declaration. 8481 Diag(D.getDeclSpec().getInlineSpecLoc(), 8482 diag::err_inline_declaration_block_scope) << Name 8483 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8484 } 8485 } 8486 8487 // C++ [dcl.fct.spec]p6: 8488 // The explicit specifier shall be used only in the declaration of a 8489 // constructor or conversion function within its class definition; 8490 // see 12.3.1 and 12.3.2. 8491 if (isExplicit && !NewFD->isInvalidDecl() && 8492 !isa<CXXDeductionGuideDecl>(NewFD)) { 8493 if (!CurContext->isRecord()) { 8494 // 'explicit' was specified outside of the class. 8495 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8496 diag::err_explicit_out_of_class) 8497 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8498 } else if (!isa<CXXConstructorDecl>(NewFD) && 8499 !isa<CXXConversionDecl>(NewFD)) { 8500 // 'explicit' was specified on a function that wasn't a constructor 8501 // or conversion function. 8502 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8503 diag::err_explicit_non_ctor_or_conv_function) 8504 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8505 } 8506 } 8507 8508 if (isConstexpr) { 8509 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8510 // are implicitly inline. 8511 NewFD->setImplicitlyInline(); 8512 8513 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8514 // be either constructors or to return a literal type. Therefore, 8515 // destructors cannot be declared constexpr. 8516 if (isa<CXXDestructorDecl>(NewFD)) 8517 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8518 } 8519 8520 // If __module_private__ was specified, mark the function accordingly. 8521 if (D.getDeclSpec().isModulePrivateSpecified()) { 8522 if (isFunctionTemplateSpecialization) { 8523 SourceLocation ModulePrivateLoc 8524 = D.getDeclSpec().getModulePrivateSpecLoc(); 8525 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8526 << 0 8527 << FixItHint::CreateRemoval(ModulePrivateLoc); 8528 } else { 8529 NewFD->setModulePrivate(); 8530 if (FunctionTemplate) 8531 FunctionTemplate->setModulePrivate(); 8532 } 8533 } 8534 8535 if (isFriend) { 8536 if (FunctionTemplate) { 8537 FunctionTemplate->setObjectOfFriendDecl(); 8538 FunctionTemplate->setAccess(AS_public); 8539 } 8540 NewFD->setObjectOfFriendDecl(); 8541 NewFD->setAccess(AS_public); 8542 } 8543 8544 // If a function is defined as defaulted or deleted, mark it as such now. 8545 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8546 // definition kind to FDK_Definition. 8547 switch (D.getFunctionDefinitionKind()) { 8548 case FDK_Declaration: 8549 case FDK_Definition: 8550 break; 8551 8552 case FDK_Defaulted: 8553 NewFD->setDefaulted(); 8554 break; 8555 8556 case FDK_Deleted: 8557 NewFD->setDeletedAsWritten(); 8558 break; 8559 } 8560 8561 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8562 D.isFunctionDefinition()) { 8563 // C++ [class.mfct]p2: 8564 // A member function may be defined (8.4) in its class definition, in 8565 // which case it is an inline member function (7.1.2) 8566 NewFD->setImplicitlyInline(); 8567 } 8568 8569 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8570 !CurContext->isRecord()) { 8571 // C++ [class.static]p1: 8572 // A data or function member of a class may be declared static 8573 // in a class definition, in which case it is a static member of 8574 // the class. 8575 8576 // Complain about the 'static' specifier if it's on an out-of-line 8577 // member function definition. 8578 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8579 diag::err_static_out_of_line) 8580 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8581 } 8582 8583 // C++11 [except.spec]p15: 8584 // A deallocation function with no exception-specification is treated 8585 // as if it were specified with noexcept(true). 8586 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8587 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8588 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8589 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8590 NewFD->setType(Context.getFunctionType( 8591 FPT->getReturnType(), FPT->getParamTypes(), 8592 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8593 } 8594 8595 // Filter out previous declarations that don't match the scope. 8596 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8597 D.getCXXScopeSpec().isNotEmpty() || 8598 isMemberSpecialization || 8599 isFunctionTemplateSpecialization); 8600 8601 // Handle GNU asm-label extension (encoded as an attribute). 8602 if (Expr *E = (Expr*) D.getAsmLabel()) { 8603 // The parser guarantees this is a string. 8604 StringLiteral *SE = cast<StringLiteral>(E); 8605 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8606 SE->getString(), 0)); 8607 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8608 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8609 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8610 if (I != ExtnameUndeclaredIdentifiers.end()) { 8611 if (isDeclExternC(NewFD)) { 8612 NewFD->addAttr(I->second); 8613 ExtnameUndeclaredIdentifiers.erase(I); 8614 } else 8615 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8616 << /*Variable*/0 << NewFD; 8617 } 8618 } 8619 8620 // Copy the parameter declarations from the declarator D to the function 8621 // declaration NewFD, if they are available. First scavenge them into Params. 8622 SmallVector<ParmVarDecl*, 16> Params; 8623 unsigned FTIIdx; 8624 if (D.isFunctionDeclarator(FTIIdx)) { 8625 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8626 8627 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8628 // function that takes no arguments, not a function that takes a 8629 // single void argument. 8630 // We let through "const void" here because Sema::GetTypeForDeclarator 8631 // already checks for that case. 8632 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8633 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8634 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8635 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8636 Param->setDeclContext(NewFD); 8637 Params.push_back(Param); 8638 8639 if (Param->isInvalidDecl()) 8640 NewFD->setInvalidDecl(); 8641 } 8642 } 8643 8644 if (!getLangOpts().CPlusPlus) { 8645 // In C, find all the tag declarations from the prototype and move them 8646 // into the function DeclContext. Remove them from the surrounding tag 8647 // injection context of the function, which is typically but not always 8648 // the TU. 8649 DeclContext *PrototypeTagContext = 8650 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8651 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8652 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8653 8654 // We don't want to reparent enumerators. Look at their parent enum 8655 // instead. 8656 if (!TD) { 8657 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8658 TD = cast<EnumDecl>(ECD->getDeclContext()); 8659 } 8660 if (!TD) 8661 continue; 8662 DeclContext *TagDC = TD->getLexicalDeclContext(); 8663 if (!TagDC->containsDecl(TD)) 8664 continue; 8665 TagDC->removeDecl(TD); 8666 TD->setDeclContext(NewFD); 8667 NewFD->addDecl(TD); 8668 8669 // Preserve the lexical DeclContext if it is not the surrounding tag 8670 // injection context of the FD. In this example, the semantic context of 8671 // E will be f and the lexical context will be S, while both the 8672 // semantic and lexical contexts of S will be f: 8673 // void f(struct S { enum E { a } f; } s); 8674 if (TagDC != PrototypeTagContext) 8675 TD->setLexicalDeclContext(TagDC); 8676 } 8677 } 8678 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8679 // When we're declaring a function with a typedef, typeof, etc as in the 8680 // following example, we'll need to synthesize (unnamed) 8681 // parameters for use in the declaration. 8682 // 8683 // @code 8684 // typedef void fn(int); 8685 // fn f; 8686 // @endcode 8687 8688 // Synthesize a parameter for each argument type. 8689 for (const auto &AI : FT->param_types()) { 8690 ParmVarDecl *Param = 8691 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8692 Param->setScopeInfo(0, Params.size()); 8693 Params.push_back(Param); 8694 } 8695 } else { 8696 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8697 "Should not need args for typedef of non-prototype fn"); 8698 } 8699 8700 // Finally, we know we have the right number of parameters, install them. 8701 NewFD->setParams(Params); 8702 8703 if (D.getDeclSpec().isNoreturnSpecified()) 8704 NewFD->addAttr( 8705 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8706 Context, 0)); 8707 8708 // Functions returning a variably modified type violate C99 6.7.5.2p2 8709 // because all functions have linkage. 8710 if (!NewFD->isInvalidDecl() && 8711 NewFD->getReturnType()->isVariablyModifiedType()) { 8712 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8713 NewFD->setInvalidDecl(); 8714 } 8715 8716 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8717 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8718 !NewFD->hasAttr<SectionAttr>()) { 8719 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8720 PragmaClangTextSection.SectionName, 8721 PragmaClangTextSection.PragmaLocation)); 8722 } 8723 8724 // Apply an implicit SectionAttr from class declspec or from 8725 // #pragma code_seg if active. 8726 if (!NewFD->hasAttr<SectionAttr>()) { 8727 if (Attr *SAttr = getImplicitSectionAttrForFunction(NewFD, 8728 D.isFunctionDefinition())) { 8729 NewFD->addAttr(SAttr); 8730 if (UnifySection(cast<SectionAttr>(SAttr)->getName(), 8731 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8732 ASTContext::PSF_Read, 8733 NewFD)) 8734 NewFD->dropAttr<SectionAttr>(); 8735 } 8736 } 8737 8738 // Handle attributes. 8739 ProcessDeclAttributes(S, NewFD, D); 8740 8741 if (getLangOpts().OpenCL) { 8742 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8743 // type declaration will generate a compilation error. 8744 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8745 if (AddressSpace != LangAS::Default) { 8746 Diag(NewFD->getLocation(), 8747 diag::err_opencl_return_value_with_address_space); 8748 NewFD->setInvalidDecl(); 8749 } 8750 } 8751 8752 if (!getLangOpts().CPlusPlus) { 8753 // Perform semantic checking on the function declaration. 8754 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8755 CheckMain(NewFD, D.getDeclSpec()); 8756 8757 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8758 CheckMSVCRTEntryPoint(NewFD); 8759 8760 if (!NewFD->isInvalidDecl()) 8761 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8762 isMemberSpecialization)); 8763 else if (!Previous.empty()) 8764 // Recover gracefully from an invalid redeclaration. 8765 D.setRedeclaration(true); 8766 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8767 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8768 "previous declaration set still overloaded"); 8769 8770 // Diagnose no-prototype function declarations with calling conventions that 8771 // don't support variadic calls. Only do this in C and do it after merging 8772 // possibly prototyped redeclarations. 8773 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8774 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8775 CallingConv CC = FT->getExtInfo().getCC(); 8776 if (!supportsVariadicCall(CC)) { 8777 // Windows system headers sometimes accidentally use stdcall without 8778 // (void) parameters, so we relax this to a warning. 8779 int DiagID = 8780 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8781 Diag(NewFD->getLocation(), DiagID) 8782 << FunctionType::getNameForCallConv(CC); 8783 } 8784 } 8785 } else { 8786 // C++11 [replacement.functions]p3: 8787 // The program's definitions shall not be specified as inline. 8788 // 8789 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8790 // 8791 // Suppress the diagnostic if the function is __attribute__((used)), since 8792 // that forces an external definition to be emitted. 8793 if (D.getDeclSpec().isInlineSpecified() && 8794 NewFD->isReplaceableGlobalAllocationFunction() && 8795 !NewFD->hasAttr<UsedAttr>()) 8796 Diag(D.getDeclSpec().getInlineSpecLoc(), 8797 diag::ext_operator_new_delete_declared_inline) 8798 << NewFD->getDeclName(); 8799 8800 // If the declarator is a template-id, translate the parser's template 8801 // argument list into our AST format. 8802 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8803 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8804 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8805 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8806 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8807 TemplateId->NumArgs); 8808 translateTemplateArguments(TemplateArgsPtr, 8809 TemplateArgs); 8810 8811 HasExplicitTemplateArgs = true; 8812 8813 if (NewFD->isInvalidDecl()) { 8814 HasExplicitTemplateArgs = false; 8815 } else if (FunctionTemplate) { 8816 // Function template with explicit template arguments. 8817 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8818 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8819 8820 HasExplicitTemplateArgs = false; 8821 } else { 8822 assert((isFunctionTemplateSpecialization || 8823 D.getDeclSpec().isFriendSpecified()) && 8824 "should have a 'template<>' for this decl"); 8825 // "friend void foo<>(int);" is an implicit specialization decl. 8826 isFunctionTemplateSpecialization = true; 8827 } 8828 } else if (isFriend && isFunctionTemplateSpecialization) { 8829 // This combination is only possible in a recovery case; the user 8830 // wrote something like: 8831 // template <> friend void foo(int); 8832 // which we're recovering from as if the user had written: 8833 // friend void foo<>(int); 8834 // Go ahead and fake up a template id. 8835 HasExplicitTemplateArgs = true; 8836 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8837 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8838 } 8839 8840 // We do not add HD attributes to specializations here because 8841 // they may have different constexpr-ness compared to their 8842 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8843 // may end up with different effective targets. Instead, a 8844 // specialization inherits its target attributes from its template 8845 // in the CheckFunctionTemplateSpecialization() call below. 8846 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8847 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8848 8849 // If it's a friend (and only if it's a friend), it's possible 8850 // that either the specialized function type or the specialized 8851 // template is dependent, and therefore matching will fail. In 8852 // this case, don't check the specialization yet. 8853 bool InstantiationDependent = false; 8854 if (isFunctionTemplateSpecialization && isFriend && 8855 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8856 TemplateSpecializationType::anyDependentTemplateArguments( 8857 TemplateArgs, 8858 InstantiationDependent))) { 8859 assert(HasExplicitTemplateArgs && 8860 "friend function specialization without template args"); 8861 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8862 Previous)) 8863 NewFD->setInvalidDecl(); 8864 } else if (isFunctionTemplateSpecialization) { 8865 if (CurContext->isDependentContext() && CurContext->isRecord() 8866 && !isFriend) { 8867 isDependentClassScopeExplicitSpecialization = true; 8868 } else if (!NewFD->isInvalidDecl() && 8869 CheckFunctionTemplateSpecialization( 8870 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8871 Previous)) 8872 NewFD->setInvalidDecl(); 8873 8874 // C++ [dcl.stc]p1: 8875 // A storage-class-specifier shall not be specified in an explicit 8876 // specialization (14.7.3) 8877 FunctionTemplateSpecializationInfo *Info = 8878 NewFD->getTemplateSpecializationInfo(); 8879 if (Info && SC != SC_None) { 8880 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8881 Diag(NewFD->getLocation(), 8882 diag::err_explicit_specialization_inconsistent_storage_class) 8883 << SC 8884 << FixItHint::CreateRemoval( 8885 D.getDeclSpec().getStorageClassSpecLoc()); 8886 8887 else 8888 Diag(NewFD->getLocation(), 8889 diag::ext_explicit_specialization_storage_class) 8890 << FixItHint::CreateRemoval( 8891 D.getDeclSpec().getStorageClassSpecLoc()); 8892 } 8893 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8894 if (CheckMemberSpecialization(NewFD, Previous)) 8895 NewFD->setInvalidDecl(); 8896 } 8897 8898 // Perform semantic checking on the function declaration. 8899 if (!isDependentClassScopeExplicitSpecialization) { 8900 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8901 CheckMain(NewFD, D.getDeclSpec()); 8902 8903 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8904 CheckMSVCRTEntryPoint(NewFD); 8905 8906 if (!NewFD->isInvalidDecl()) 8907 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8908 isMemberSpecialization)); 8909 else if (!Previous.empty()) 8910 // Recover gracefully from an invalid redeclaration. 8911 D.setRedeclaration(true); 8912 } 8913 8914 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8915 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8916 "previous declaration set still overloaded"); 8917 8918 NamedDecl *PrincipalDecl = (FunctionTemplate 8919 ? cast<NamedDecl>(FunctionTemplate) 8920 : NewFD); 8921 8922 if (isFriend && NewFD->getPreviousDecl()) { 8923 AccessSpecifier Access = AS_public; 8924 if (!NewFD->isInvalidDecl()) 8925 Access = NewFD->getPreviousDecl()->getAccess(); 8926 8927 NewFD->setAccess(Access); 8928 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8929 } 8930 8931 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8932 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8933 PrincipalDecl->setNonMemberOperator(); 8934 8935 // If we have a function template, check the template parameter 8936 // list. This will check and merge default template arguments. 8937 if (FunctionTemplate) { 8938 FunctionTemplateDecl *PrevTemplate = 8939 FunctionTemplate->getPreviousDecl(); 8940 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8941 PrevTemplate ? PrevTemplate->getTemplateParameters() 8942 : nullptr, 8943 D.getDeclSpec().isFriendSpecified() 8944 ? (D.isFunctionDefinition() 8945 ? TPC_FriendFunctionTemplateDefinition 8946 : TPC_FriendFunctionTemplate) 8947 : (D.getCXXScopeSpec().isSet() && 8948 DC && DC->isRecord() && 8949 DC->isDependentContext()) 8950 ? TPC_ClassTemplateMember 8951 : TPC_FunctionTemplate); 8952 } 8953 8954 if (NewFD->isInvalidDecl()) { 8955 // Ignore all the rest of this. 8956 } else if (!D.isRedeclaration()) { 8957 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8958 AddToScope }; 8959 // Fake up an access specifier if it's supposed to be a class member. 8960 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8961 NewFD->setAccess(AS_public); 8962 8963 // Qualified decls generally require a previous declaration. 8964 if (D.getCXXScopeSpec().isSet()) { 8965 // ...with the major exception of templated-scope or 8966 // dependent-scope friend declarations. 8967 8968 // TODO: we currently also suppress this check in dependent 8969 // contexts because (1) the parameter depth will be off when 8970 // matching friend templates and (2) we might actually be 8971 // selecting a friend based on a dependent factor. But there 8972 // are situations where these conditions don't apply and we 8973 // can actually do this check immediately. 8974 if (isFriend && 8975 (TemplateParamLists.size() || 8976 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8977 CurContext->isDependentContext())) { 8978 // ignore these 8979 } else { 8980 // The user tried to provide an out-of-line definition for a 8981 // function that is a member of a class or namespace, but there 8982 // was no such member function declared (C++ [class.mfct]p2, 8983 // C++ [namespace.memdef]p2). For example: 8984 // 8985 // class X { 8986 // void f() const; 8987 // }; 8988 // 8989 // void X::f() { } // ill-formed 8990 // 8991 // Complain about this problem, and attempt to suggest close 8992 // matches (e.g., those that differ only in cv-qualifiers and 8993 // whether the parameter types are references). 8994 8995 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8996 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8997 AddToScope = ExtraArgs.AddToScope; 8998 return Result; 8999 } 9000 } 9001 9002 // Unqualified local friend declarations are required to resolve 9003 // to something. 9004 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9005 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9006 *this, Previous, NewFD, ExtraArgs, true, S)) { 9007 AddToScope = ExtraArgs.AddToScope; 9008 return Result; 9009 } 9010 } 9011 } else if (!D.isFunctionDefinition() && 9012 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9013 !isFriend && !isFunctionTemplateSpecialization && 9014 !isMemberSpecialization) { 9015 // An out-of-line member function declaration must also be a 9016 // definition (C++ [class.mfct]p2). 9017 // Note that this is not the case for explicit specializations of 9018 // function templates or member functions of class templates, per 9019 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9020 // extension for compatibility with old SWIG code which likes to 9021 // generate them. 9022 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9023 << D.getCXXScopeSpec().getRange(); 9024 } 9025 } 9026 9027 ProcessPragmaWeak(S, NewFD); 9028 checkAttributesAfterMerging(*this, *NewFD); 9029 9030 AddKnownFunctionAttributes(NewFD); 9031 9032 if (NewFD->hasAttr<OverloadableAttr>() && 9033 !NewFD->getType()->getAs<FunctionProtoType>()) { 9034 Diag(NewFD->getLocation(), 9035 diag::err_attribute_overloadable_no_prototype) 9036 << NewFD; 9037 9038 // Turn this into a variadic function with no parameters. 9039 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9040 FunctionProtoType::ExtProtoInfo EPI( 9041 Context.getDefaultCallingConvention(true, false)); 9042 EPI.Variadic = true; 9043 EPI.ExtInfo = FT->getExtInfo(); 9044 9045 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9046 NewFD->setType(R); 9047 } 9048 9049 // If there's a #pragma GCC visibility in scope, and this isn't a class 9050 // member, set the visibility of this function. 9051 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9052 AddPushedVisibilityAttribute(NewFD); 9053 9054 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9055 // marking the function. 9056 AddCFAuditedAttribute(NewFD); 9057 9058 // If this is a function definition, check if we have to apply optnone due to 9059 // a pragma. 9060 if(D.isFunctionDefinition()) 9061 AddRangeBasedOptnone(NewFD); 9062 9063 // If this is the first declaration of an extern C variable, update 9064 // the map of such variables. 9065 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9066 isIncompleteDeclExternC(*this, NewFD)) 9067 RegisterLocallyScopedExternCDecl(NewFD, S); 9068 9069 // Set this FunctionDecl's range up to the right paren. 9070 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9071 9072 if (D.isRedeclaration() && !Previous.empty()) { 9073 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9074 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9075 isMemberSpecialization || 9076 isFunctionTemplateSpecialization, 9077 D.isFunctionDefinition()); 9078 } 9079 9080 if (getLangOpts().CUDA) { 9081 IdentifierInfo *II = NewFD->getIdentifier(); 9082 if (II && 9083 II->isStr(getLangOpts().HIP ? "hipConfigureCall" 9084 : "cudaConfigureCall") && 9085 !NewFD->isInvalidDecl() && 9086 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9087 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9088 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9089 Context.setcudaConfigureCallDecl(NewFD); 9090 } 9091 9092 // Variadic functions, other than a *declaration* of printf, are not allowed 9093 // in device-side CUDA code, unless someone passed 9094 // -fcuda-allow-variadic-functions. 9095 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9096 (NewFD->hasAttr<CUDADeviceAttr>() || 9097 NewFD->hasAttr<CUDAGlobalAttr>()) && 9098 !(II && II->isStr("printf") && NewFD->isExternC() && 9099 !D.isFunctionDefinition())) { 9100 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9101 } 9102 } 9103 9104 MarkUnusedFileScopedDecl(NewFD); 9105 9106 if (getLangOpts().CPlusPlus) { 9107 if (FunctionTemplate) { 9108 if (NewFD->isInvalidDecl()) 9109 FunctionTemplate->setInvalidDecl(); 9110 return FunctionTemplate; 9111 } 9112 9113 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9114 CompleteMemberSpecialization(NewFD, Previous); 9115 } 9116 9117 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9118 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9119 if ((getLangOpts().OpenCLVersion >= 120) 9120 && (SC == SC_Static)) { 9121 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9122 D.setInvalidType(); 9123 } 9124 9125 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9126 if (!NewFD->getReturnType()->isVoidType()) { 9127 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9128 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9129 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9130 : FixItHint()); 9131 D.setInvalidType(); 9132 } 9133 9134 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9135 for (auto Param : NewFD->parameters()) 9136 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9137 } 9138 for (const ParmVarDecl *Param : NewFD->parameters()) { 9139 QualType PT = Param->getType(); 9140 9141 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9142 // types. 9143 if (getLangOpts().OpenCLVersion >= 200) { 9144 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9145 QualType ElemTy = PipeTy->getElementType(); 9146 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9147 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9148 D.setInvalidType(); 9149 } 9150 } 9151 } 9152 } 9153 9154 // Here we have an function template explicit specialization at class scope. 9155 // The actual specialization will be postponed to template instatiation 9156 // time via the ClassScopeFunctionSpecializationDecl node. 9157 if (isDependentClassScopeExplicitSpecialization) { 9158 ClassScopeFunctionSpecializationDecl *NewSpec = 9159 ClassScopeFunctionSpecializationDecl::Create( 9160 Context, CurContext, NewFD->getLocation(), 9161 cast<CXXMethodDecl>(NewFD), 9162 HasExplicitTemplateArgs, TemplateArgs); 9163 CurContext->addDecl(NewSpec); 9164 AddToScope = false; 9165 } 9166 9167 // Diagnose availability attributes. Availability cannot be used on functions 9168 // that are run during load/unload. 9169 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9170 if (NewFD->hasAttr<ConstructorAttr>()) { 9171 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9172 << 1; 9173 NewFD->dropAttr<AvailabilityAttr>(); 9174 } 9175 if (NewFD->hasAttr<DestructorAttr>()) { 9176 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9177 << 2; 9178 NewFD->dropAttr<AvailabilityAttr>(); 9179 } 9180 } 9181 9182 return NewFD; 9183 } 9184 9185 /// Return a SectionAttr from a containing class. The Microsoft docs say 9186 /// when __declspec(code_seg) "is applied to a class, all member functions of 9187 /// the class and nested classes -- this includes compiler-generated special 9188 /// member functions -- are put in the specified segment." 9189 /// The actual behavior is a little more complicated. The Microsoft compiler 9190 /// won't check outer classes if there is an active value from #pragma code_seg. 9191 /// The section is always applied from the direct parent but only from outer 9192 /// classes when the #pragma code_seg stack is empty. See: 9193 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9194 /// available since MS has removed the page. 9195 static Attr *getImplicitSectionAttrFromClass(Sema &S, const FunctionDecl *FD) { 9196 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9197 if (!Method) 9198 return nullptr; 9199 const CXXRecordDecl *Parent = Method->getParent(); 9200 if (const auto *SAttr = Parent->getAttr<SectionAttr>()) { 9201 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9202 NewAttr->setImplicit(true); 9203 return NewAttr; 9204 } 9205 9206 // The Microsoft compiler won't check outer classes for the section 9207 // when the #pragma code_seg stack is active. 9208 if (S.CodeSegStack.CurrentValue) 9209 return nullptr; 9210 9211 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9212 if (const auto *SAttr = Parent->getAttr<SectionAttr>()) { 9213 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9214 NewAttr->setImplicit(true); 9215 return NewAttr; 9216 } 9217 } 9218 return nullptr; 9219 } 9220 9221 /// \brief Returns an implicit SectionAttr for a function. 9222 /// 9223 /// \param FD Function being declared. 9224 /// \param IsDefinition Whether it is a definition or just a declarartion. 9225 /// \returns A SectionAttr to apply to the function or nullptr if no 9226 /// attribute should be added. 9227 /// 9228 /// First tries to find a SectionAttr on a containing class (from 9229 /// a __declspec(code_seg)). If not found on the class, and if the function is 9230 /// also a definition it will use the current #pragma code_seg value. 9231 Attr *Sema::getImplicitSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition) { 9232 if (Attr *A = getImplicitSectionAttrFromClass(*this, FD)) 9233 return A; 9234 if (IsDefinition && CodeSegStack.CurrentValue) { 9235 return SectionAttr::CreateImplicit(getASTContext(), 9236 SectionAttr::Declspec_allocate, 9237 CodeSegStack.CurrentValue->getString(), 9238 CodeSegStack.CurrentPragmaLocation); 9239 } 9240 return nullptr; 9241 } 9242 9243 /// Checks if the new declaration declared in dependent context must be 9244 /// put in the same redeclaration chain as the specified declaration. 9245 /// 9246 /// \param D Declaration that is checked. 9247 /// \param PrevDecl Previous declaration found with proper lookup method for the 9248 /// same declaration name. 9249 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9250 /// belongs to. 9251 /// 9252 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9253 // Any declarations should be put into redeclaration chains except for 9254 // friend declaration in a dependent context that names a function in 9255 // namespace scope. 9256 // 9257 // This allows to compile code like: 9258 // 9259 // void func(); 9260 // template<typename T> class C1 { friend void func() { } }; 9261 // template<typename T> class C2 { friend void func() { } }; 9262 // 9263 // This code snippet is a valid code unless both templates are instantiated. 9264 return !(D->getLexicalDeclContext()->isDependentContext() && 9265 D->getDeclContext()->isFileContext() && 9266 D->getFriendObjectKind() != Decl::FOK_None); 9267 } 9268 9269 /// Check the target attribute of the function for MultiVersion 9270 /// validity. 9271 /// 9272 /// Returns true if there was an error, false otherwise. 9273 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9274 const auto *TA = FD->getAttr<TargetAttr>(); 9275 assert(TA && "MultiVersion Candidate requires a target attribute"); 9276 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9277 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9278 enum ErrType { Feature = 0, Architecture = 1 }; 9279 9280 if (!ParseInfo.Architecture.empty() && 9281 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9282 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9283 << Architecture << ParseInfo.Architecture; 9284 return true; 9285 } 9286 9287 for (const auto &Feat : ParseInfo.Features) { 9288 auto BareFeat = StringRef{Feat}.substr(1); 9289 if (Feat[0] == '-') { 9290 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9291 << Feature << ("no-" + BareFeat).str(); 9292 return true; 9293 } 9294 9295 if (!TargetInfo.validateCpuSupports(BareFeat) || 9296 !TargetInfo.isValidFeatureName(BareFeat)) { 9297 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9298 << Feature << BareFeat; 9299 return true; 9300 } 9301 } 9302 return false; 9303 } 9304 9305 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9306 const FunctionDecl *NewFD, 9307 bool CausesMV) { 9308 enum DoesntSupport { 9309 FuncTemplates = 0, 9310 VirtFuncs = 1, 9311 DeducedReturn = 2, 9312 Constructors = 3, 9313 Destructors = 4, 9314 DeletedFuncs = 5, 9315 DefaultedFuncs = 6 9316 }; 9317 enum Different { 9318 CallingConv = 0, 9319 ReturnType = 1, 9320 ConstexprSpec = 2, 9321 InlineSpec = 3, 9322 StorageClass = 4, 9323 Linkage = 5 9324 }; 9325 9326 // For now, disallow all other attributes. These should be opt-in, but 9327 // an analysis of all of them is a future FIXME. 9328 if (CausesMV && OldFD && 9329 std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) { 9330 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs); 9331 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9332 return true; 9333 } 9334 9335 if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1) 9336 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs); 9337 9338 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9339 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9340 << FuncTemplates; 9341 9342 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9343 if (NewCXXFD->isVirtual()) 9344 return S.Diag(NewCXXFD->getLocation(), 9345 diag::err_multiversion_doesnt_support) 9346 << VirtFuncs; 9347 9348 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9349 return S.Diag(NewCXXCtor->getLocation(), 9350 diag::err_multiversion_doesnt_support) 9351 << Constructors; 9352 9353 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9354 return S.Diag(NewCXXDtor->getLocation(), 9355 diag::err_multiversion_doesnt_support) 9356 << Destructors; 9357 } 9358 9359 if (NewFD->isDeleted()) 9360 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9361 << DeletedFuncs; 9362 9363 if (NewFD->isDefaulted()) 9364 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9365 << DefaultedFuncs; 9366 9367 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9368 const auto *NewType = cast<FunctionType>(NewQType); 9369 QualType NewReturnType = NewType->getReturnType(); 9370 9371 if (NewReturnType->isUndeducedType()) 9372 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9373 << DeducedReturn; 9374 9375 // Only allow transition to MultiVersion if it hasn't been used. 9376 if (OldFD && CausesMV && OldFD->isUsed(false)) 9377 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9378 9379 // Ensure the return type is identical. 9380 if (OldFD) { 9381 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9382 const auto *OldType = cast<FunctionType>(OldQType); 9383 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9384 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9385 9386 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9387 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9388 << CallingConv; 9389 9390 QualType OldReturnType = OldType->getReturnType(); 9391 9392 if (OldReturnType != NewReturnType) 9393 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9394 << ReturnType; 9395 9396 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9397 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9398 << ConstexprSpec; 9399 9400 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9401 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9402 << InlineSpec; 9403 9404 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9405 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9406 << StorageClass; 9407 9408 if (OldFD->isExternC() != NewFD->isExternC()) 9409 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9410 << Linkage; 9411 9412 if (S.CheckEquivalentExceptionSpec( 9413 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9414 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9415 return true; 9416 } 9417 return false; 9418 } 9419 9420 /// Check the validity of a mulitversion function declaration. 9421 /// Also sets the multiversion'ness' of the function itself. 9422 /// 9423 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9424 /// 9425 /// Returns true if there was an error, false otherwise. 9426 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9427 bool &Redeclaration, NamedDecl *&OldDecl, 9428 bool &MergeTypeWithPrevious, 9429 LookupResult &Previous) { 9430 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9431 if (NewFD->isMain()) { 9432 if (NewTA && NewTA->isDefaultVersion()) { 9433 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9434 NewFD->setInvalidDecl(); 9435 return true; 9436 } 9437 return false; 9438 } 9439 9440 // If there is no matching previous decl, only 'default' can 9441 // cause MultiVersioning. 9442 if (!OldDecl) { 9443 if (NewTA && NewTA->isDefaultVersion()) { 9444 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 9445 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9446 NewFD->setInvalidDecl(); 9447 return true; 9448 } 9449 if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) { 9450 NewFD->setInvalidDecl(); 9451 return true; 9452 } 9453 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9454 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9455 NewFD->setInvalidDecl(); 9456 return true; 9457 } 9458 9459 NewFD->setIsMultiVersion(); 9460 } 9461 return false; 9462 } 9463 9464 if (OldDecl->getDeclContext()->getRedeclContext() != 9465 NewFD->getDeclContext()->getRedeclContext()) 9466 return false; 9467 9468 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9469 // Unresolved 'using' statements (the other way OldDecl can be not a function) 9470 // likely cannot cause a problem here. 9471 if (!OldFD) 9472 return false; 9473 9474 if (!OldFD->isMultiVersion() && !NewTA) 9475 return false; 9476 9477 if (OldFD->isMultiVersion() && !NewTA) { 9478 S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl); 9479 NewFD->setInvalidDecl(); 9480 return true; 9481 } 9482 9483 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9484 // Sort order doesn't matter, it just needs to be consistent. 9485 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end()); 9486 9487 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9488 if (!OldFD->isMultiVersion()) { 9489 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9490 // to change, this is a simple redeclaration. 9491 if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()) 9492 return false; 9493 9494 // Otherwise, this decl causes MultiVersioning. 9495 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9496 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9497 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9498 NewFD->setInvalidDecl(); 9499 return true; 9500 } 9501 9502 if (!OldFD->getType()->getAs<FunctionProtoType>()) { 9503 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9504 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9505 NewFD->setInvalidDecl(); 9506 return true; 9507 } 9508 9509 if (CheckMultiVersionValue(S, NewFD)) { 9510 NewFD->setInvalidDecl(); 9511 return true; 9512 } 9513 9514 if (CheckMultiVersionValue(S, OldFD)) { 9515 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9516 NewFD->setInvalidDecl(); 9517 return true; 9518 } 9519 9520 TargetAttr::ParsedTargetAttr OldParsed = 9521 OldTA->parse(std::less<std::string>()); 9522 9523 if (OldParsed == NewParsed) { 9524 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9525 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9526 NewFD->setInvalidDecl(); 9527 return true; 9528 } 9529 9530 for (const auto *FD : OldFD->redecls()) { 9531 const auto *CurTA = FD->getAttr<TargetAttr>(); 9532 if (!CurTA || CurTA->isInherited()) { 9533 S.Diag(FD->getLocation(), diag::err_target_required_in_redecl); 9534 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9535 NewFD->setInvalidDecl(); 9536 return true; 9537 } 9538 } 9539 9540 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) { 9541 NewFD->setInvalidDecl(); 9542 return true; 9543 } 9544 9545 OldFD->setIsMultiVersion(); 9546 NewFD->setIsMultiVersion(); 9547 Redeclaration = false; 9548 MergeTypeWithPrevious = false; 9549 OldDecl = nullptr; 9550 Previous.clear(); 9551 return false; 9552 } 9553 9554 bool UseMemberUsingDeclRules = 9555 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9556 9557 // Next, check ALL non-overloads to see if this is a redeclaration of a 9558 // previous member of the MultiVersion set. 9559 for (NamedDecl *ND : Previous) { 9560 FunctionDecl *CurFD = ND->getAsFunction(); 9561 if (!CurFD) 9562 continue; 9563 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9564 continue; 9565 9566 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9567 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9568 NewFD->setIsMultiVersion(); 9569 Redeclaration = true; 9570 OldDecl = ND; 9571 return false; 9572 } 9573 9574 TargetAttr::ParsedTargetAttr CurParsed = 9575 CurTA->parse(std::less<std::string>()); 9576 9577 if (CurParsed == NewParsed) { 9578 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9579 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9580 NewFD->setInvalidDecl(); 9581 return true; 9582 } 9583 } 9584 9585 // Else, this is simply a non-redecl case. 9586 if (CheckMultiVersionValue(S, NewFD)) { 9587 NewFD->setInvalidDecl(); 9588 return true; 9589 } 9590 9591 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) { 9592 NewFD->setInvalidDecl(); 9593 return true; 9594 } 9595 9596 NewFD->setIsMultiVersion(); 9597 Redeclaration = false; 9598 MergeTypeWithPrevious = false; 9599 OldDecl = nullptr; 9600 Previous.clear(); 9601 return false; 9602 } 9603 9604 /// Perform semantic checking of a new function declaration. 9605 /// 9606 /// Performs semantic analysis of the new function declaration 9607 /// NewFD. This routine performs all semantic checking that does not 9608 /// require the actual declarator involved in the declaration, and is 9609 /// used both for the declaration of functions as they are parsed 9610 /// (called via ActOnDeclarator) and for the declaration of functions 9611 /// that have been instantiated via C++ template instantiation (called 9612 /// via InstantiateDecl). 9613 /// 9614 /// \param IsMemberSpecialization whether this new function declaration is 9615 /// a member specialization (that replaces any definition provided by the 9616 /// previous declaration). 9617 /// 9618 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9619 /// 9620 /// \returns true if the function declaration is a redeclaration. 9621 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9622 LookupResult &Previous, 9623 bool IsMemberSpecialization) { 9624 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9625 "Variably modified return types are not handled here"); 9626 9627 // Determine whether the type of this function should be merged with 9628 // a previous visible declaration. This never happens for functions in C++, 9629 // and always happens in C if the previous declaration was visible. 9630 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9631 !Previous.isShadowed(); 9632 9633 bool Redeclaration = false; 9634 NamedDecl *OldDecl = nullptr; 9635 bool MayNeedOverloadableChecks = false; 9636 9637 // Merge or overload the declaration with an existing declaration of 9638 // the same name, if appropriate. 9639 if (!Previous.empty()) { 9640 // Determine whether NewFD is an overload of PrevDecl or 9641 // a declaration that requires merging. If it's an overload, 9642 // there's no more work to do here; we'll just add the new 9643 // function to the scope. 9644 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9645 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9646 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9647 Redeclaration = true; 9648 OldDecl = Candidate; 9649 } 9650 } else { 9651 MayNeedOverloadableChecks = true; 9652 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9653 /*NewIsUsingDecl*/ false)) { 9654 case Ovl_Match: 9655 Redeclaration = true; 9656 break; 9657 9658 case Ovl_NonFunction: 9659 Redeclaration = true; 9660 break; 9661 9662 case Ovl_Overload: 9663 Redeclaration = false; 9664 break; 9665 } 9666 } 9667 } 9668 9669 // Check for a previous extern "C" declaration with this name. 9670 if (!Redeclaration && 9671 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9672 if (!Previous.empty()) { 9673 // This is an extern "C" declaration with the same name as a previous 9674 // declaration, and thus redeclares that entity... 9675 Redeclaration = true; 9676 OldDecl = Previous.getFoundDecl(); 9677 MergeTypeWithPrevious = false; 9678 9679 // ... except in the presence of __attribute__((overloadable)). 9680 if (OldDecl->hasAttr<OverloadableAttr>() || 9681 NewFD->hasAttr<OverloadableAttr>()) { 9682 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9683 MayNeedOverloadableChecks = true; 9684 Redeclaration = false; 9685 OldDecl = nullptr; 9686 } 9687 } 9688 } 9689 } 9690 9691 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 9692 MergeTypeWithPrevious, Previous)) 9693 return Redeclaration; 9694 9695 // C++11 [dcl.constexpr]p8: 9696 // A constexpr specifier for a non-static member function that is not 9697 // a constructor declares that member function to be const. 9698 // 9699 // This needs to be delayed until we know whether this is an out-of-line 9700 // definition of a static member function. 9701 // 9702 // This rule is not present in C++1y, so we produce a backwards 9703 // compatibility warning whenever it happens in C++11. 9704 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9705 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9706 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9707 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9708 CXXMethodDecl *OldMD = nullptr; 9709 if (OldDecl) 9710 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9711 if (!OldMD || !OldMD->isStatic()) { 9712 const FunctionProtoType *FPT = 9713 MD->getType()->castAs<FunctionProtoType>(); 9714 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9715 EPI.TypeQuals |= Qualifiers::Const; 9716 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9717 FPT->getParamTypes(), EPI)); 9718 9719 // Warn that we did this, if we're not performing template instantiation. 9720 // In that case, we'll have warned already when the template was defined. 9721 if (!inTemplateInstantiation()) { 9722 SourceLocation AddConstLoc; 9723 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9724 .IgnoreParens().getAs<FunctionTypeLoc>()) 9725 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9726 9727 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9728 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9729 } 9730 } 9731 } 9732 9733 if (Redeclaration) { 9734 // NewFD and OldDecl represent declarations that need to be 9735 // merged. 9736 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9737 NewFD->setInvalidDecl(); 9738 return Redeclaration; 9739 } 9740 9741 Previous.clear(); 9742 Previous.addDecl(OldDecl); 9743 9744 if (FunctionTemplateDecl *OldTemplateDecl = 9745 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9746 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 9747 NewFD->setPreviousDeclaration(OldFD); 9748 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9749 FunctionTemplateDecl *NewTemplateDecl 9750 = NewFD->getDescribedFunctionTemplate(); 9751 assert(NewTemplateDecl && "Template/non-template mismatch"); 9752 if (NewFD->isCXXClassMember()) { 9753 NewFD->setAccess(OldTemplateDecl->getAccess()); 9754 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9755 } 9756 9757 // If this is an explicit specialization of a member that is a function 9758 // template, mark it as a member specialization. 9759 if (IsMemberSpecialization && 9760 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9761 NewTemplateDecl->setMemberSpecialization(); 9762 assert(OldTemplateDecl->isMemberSpecialization()); 9763 // Explicit specializations of a member template do not inherit deleted 9764 // status from the parent member template that they are specializing. 9765 if (OldFD->isDeleted()) { 9766 // FIXME: This assert will not hold in the presence of modules. 9767 assert(OldFD->getCanonicalDecl() == OldFD); 9768 // FIXME: We need an update record for this AST mutation. 9769 OldFD->setDeletedAsWritten(false); 9770 } 9771 } 9772 9773 } else { 9774 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9775 auto *OldFD = cast<FunctionDecl>(OldDecl); 9776 // This needs to happen first so that 'inline' propagates. 9777 NewFD->setPreviousDeclaration(OldFD); 9778 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9779 if (NewFD->isCXXClassMember()) 9780 NewFD->setAccess(OldFD->getAccess()); 9781 } 9782 } 9783 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9784 !NewFD->getAttr<OverloadableAttr>()) { 9785 assert((Previous.empty() || 9786 llvm::any_of(Previous, 9787 [](const NamedDecl *ND) { 9788 return ND->hasAttr<OverloadableAttr>(); 9789 })) && 9790 "Non-redecls shouldn't happen without overloadable present"); 9791 9792 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9793 const auto *FD = dyn_cast<FunctionDecl>(ND); 9794 return FD && !FD->hasAttr<OverloadableAttr>(); 9795 }); 9796 9797 if (OtherUnmarkedIter != Previous.end()) { 9798 Diag(NewFD->getLocation(), 9799 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9800 Diag((*OtherUnmarkedIter)->getLocation(), 9801 diag::note_attribute_overloadable_prev_overload) 9802 << false; 9803 9804 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9805 } 9806 } 9807 9808 // Semantic checking for this function declaration (in isolation). 9809 9810 if (getLangOpts().CPlusPlus) { 9811 // C++-specific checks. 9812 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9813 CheckConstructor(Constructor); 9814 } else if (CXXDestructorDecl *Destructor = 9815 dyn_cast<CXXDestructorDecl>(NewFD)) { 9816 CXXRecordDecl *Record = Destructor->getParent(); 9817 QualType ClassType = Context.getTypeDeclType(Record); 9818 9819 // FIXME: Shouldn't we be able to perform this check even when the class 9820 // type is dependent? Both gcc and edg can handle that. 9821 if (!ClassType->isDependentType()) { 9822 DeclarationName Name 9823 = Context.DeclarationNames.getCXXDestructorName( 9824 Context.getCanonicalType(ClassType)); 9825 if (NewFD->getDeclName() != Name) { 9826 Diag(NewFD->getLocation(), diag::err_destructor_name); 9827 NewFD->setInvalidDecl(); 9828 return Redeclaration; 9829 } 9830 } 9831 } else if (CXXConversionDecl *Conversion 9832 = dyn_cast<CXXConversionDecl>(NewFD)) { 9833 ActOnConversionDeclarator(Conversion); 9834 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9835 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9836 CheckDeductionGuideTemplate(TD); 9837 9838 // A deduction guide is not on the list of entities that can be 9839 // explicitly specialized. 9840 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9841 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9842 << /*explicit specialization*/ 1; 9843 } 9844 9845 // Find any virtual functions that this function overrides. 9846 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9847 if (!Method->isFunctionTemplateSpecialization() && 9848 !Method->getDescribedFunctionTemplate() && 9849 Method->isCanonicalDecl()) { 9850 if (AddOverriddenMethods(Method->getParent(), Method)) { 9851 // If the function was marked as "static", we have a problem. 9852 if (NewFD->getStorageClass() == SC_Static) { 9853 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9854 } 9855 } 9856 } 9857 9858 if (Method->isStatic()) 9859 checkThisInStaticMemberFunctionType(Method); 9860 } 9861 9862 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9863 if (NewFD->isOverloadedOperator() && 9864 CheckOverloadedOperatorDeclaration(NewFD)) { 9865 NewFD->setInvalidDecl(); 9866 return Redeclaration; 9867 } 9868 9869 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9870 if (NewFD->getLiteralIdentifier() && 9871 CheckLiteralOperatorDeclaration(NewFD)) { 9872 NewFD->setInvalidDecl(); 9873 return Redeclaration; 9874 } 9875 9876 // In C++, check default arguments now that we have merged decls. Unless 9877 // the lexical context is the class, because in this case this is done 9878 // during delayed parsing anyway. 9879 if (!CurContext->isRecord()) 9880 CheckCXXDefaultArguments(NewFD); 9881 9882 // If this function declares a builtin function, check the type of this 9883 // declaration against the expected type for the builtin. 9884 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9885 ASTContext::GetBuiltinTypeError Error; 9886 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9887 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9888 // If the type of the builtin differs only in its exception 9889 // specification, that's OK. 9890 // FIXME: If the types do differ in this way, it would be better to 9891 // retain the 'noexcept' form of the type. 9892 if (!T.isNull() && 9893 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9894 NewFD->getType())) 9895 // The type of this function differs from the type of the builtin, 9896 // so forget about the builtin entirely. 9897 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9898 } 9899 9900 // If this function is declared as being extern "C", then check to see if 9901 // the function returns a UDT (class, struct, or union type) that is not C 9902 // compatible, and if it does, warn the user. 9903 // But, issue any diagnostic on the first declaration only. 9904 if (Previous.empty() && NewFD->isExternC()) { 9905 QualType R = NewFD->getReturnType(); 9906 if (R->isIncompleteType() && !R->isVoidType()) 9907 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9908 << NewFD << R; 9909 else if (!R.isPODType(Context) && !R->isVoidType() && 9910 !R->isObjCObjectPointerType()) 9911 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9912 } 9913 9914 // C++1z [dcl.fct]p6: 9915 // [...] whether the function has a non-throwing exception-specification 9916 // [is] part of the function type 9917 // 9918 // This results in an ABI break between C++14 and C++17 for functions whose 9919 // declared type includes an exception-specification in a parameter or 9920 // return type. (Exception specifications on the function itself are OK in 9921 // most cases, and exception specifications are not permitted in most other 9922 // contexts where they could make it into a mangling.) 9923 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 9924 auto HasNoexcept = [&](QualType T) -> bool { 9925 // Strip off declarator chunks that could be between us and a function 9926 // type. We don't need to look far, exception specifications are very 9927 // restricted prior to C++17. 9928 if (auto *RT = T->getAs<ReferenceType>()) 9929 T = RT->getPointeeType(); 9930 else if (T->isAnyPointerType()) 9931 T = T->getPointeeType(); 9932 else if (auto *MPT = T->getAs<MemberPointerType>()) 9933 T = MPT->getPointeeType(); 9934 if (auto *FPT = T->getAs<FunctionProtoType>()) 9935 if (FPT->isNothrow()) 9936 return true; 9937 return false; 9938 }; 9939 9940 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9941 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9942 for (QualType T : FPT->param_types()) 9943 AnyNoexcept |= HasNoexcept(T); 9944 if (AnyNoexcept) 9945 Diag(NewFD->getLocation(), 9946 diag::warn_cxx17_compat_exception_spec_in_signature) 9947 << NewFD; 9948 } 9949 9950 if (!Redeclaration && LangOpts.CUDA) 9951 checkCUDATargetOverload(NewFD, Previous); 9952 } 9953 return Redeclaration; 9954 } 9955 9956 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9957 // C++11 [basic.start.main]p3: 9958 // A program that [...] declares main to be inline, static or 9959 // constexpr is ill-formed. 9960 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9961 // appear in a declaration of main. 9962 // static main is not an error under C99, but we should warn about it. 9963 // We accept _Noreturn main as an extension. 9964 if (FD->getStorageClass() == SC_Static) 9965 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9966 ? diag::err_static_main : diag::warn_static_main) 9967 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9968 if (FD->isInlineSpecified()) 9969 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9970 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9971 if (DS.isNoreturnSpecified()) { 9972 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9973 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9974 Diag(NoreturnLoc, diag::ext_noreturn_main); 9975 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9976 << FixItHint::CreateRemoval(NoreturnRange); 9977 } 9978 if (FD->isConstexpr()) { 9979 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9980 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9981 FD->setConstexpr(false); 9982 } 9983 9984 if (getLangOpts().OpenCL) { 9985 Diag(FD->getLocation(), diag::err_opencl_no_main) 9986 << FD->hasAttr<OpenCLKernelAttr>(); 9987 FD->setInvalidDecl(); 9988 return; 9989 } 9990 9991 QualType T = FD->getType(); 9992 assert(T->isFunctionType() && "function decl is not of function type"); 9993 const FunctionType* FT = T->castAs<FunctionType>(); 9994 9995 // Set default calling convention for main() 9996 if (FT->getCallConv() != CC_C) { 9997 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 9998 FD->setType(QualType(FT, 0)); 9999 T = Context.getCanonicalType(FD->getType()); 10000 } 10001 10002 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10003 // In C with GNU extensions we allow main() to have non-integer return 10004 // type, but we should warn about the extension, and we disable the 10005 // implicit-return-zero rule. 10006 10007 // GCC in C mode accepts qualified 'int'. 10008 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10009 FD->setHasImplicitReturnZero(true); 10010 else { 10011 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10012 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10013 if (RTRange.isValid()) 10014 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10015 << FixItHint::CreateReplacement(RTRange, "int"); 10016 } 10017 } else { 10018 // In C and C++, main magically returns 0 if you fall off the end; 10019 // set the flag which tells us that. 10020 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10021 10022 // All the standards say that main() should return 'int'. 10023 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10024 FD->setHasImplicitReturnZero(true); 10025 else { 10026 // Otherwise, this is just a flat-out error. 10027 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10028 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10029 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10030 : FixItHint()); 10031 FD->setInvalidDecl(true); 10032 } 10033 } 10034 10035 // Treat protoless main() as nullary. 10036 if (isa<FunctionNoProtoType>(FT)) return; 10037 10038 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10039 unsigned nparams = FTP->getNumParams(); 10040 assert(FD->getNumParams() == nparams); 10041 10042 bool HasExtraParameters = (nparams > 3); 10043 10044 if (FTP->isVariadic()) { 10045 Diag(FD->getLocation(), diag::ext_variadic_main); 10046 // FIXME: if we had information about the location of the ellipsis, we 10047 // could add a FixIt hint to remove it as a parameter. 10048 } 10049 10050 // Darwin passes an undocumented fourth argument of type char**. If 10051 // other platforms start sprouting these, the logic below will start 10052 // getting shifty. 10053 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10054 HasExtraParameters = false; 10055 10056 if (HasExtraParameters) { 10057 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10058 FD->setInvalidDecl(true); 10059 nparams = 3; 10060 } 10061 10062 // FIXME: a lot of the following diagnostics would be improved 10063 // if we had some location information about types. 10064 10065 QualType CharPP = 10066 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10067 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10068 10069 for (unsigned i = 0; i < nparams; ++i) { 10070 QualType AT = FTP->getParamType(i); 10071 10072 bool mismatch = true; 10073 10074 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10075 mismatch = false; 10076 else if (Expected[i] == CharPP) { 10077 // As an extension, the following forms are okay: 10078 // char const ** 10079 // char const * const * 10080 // char * const * 10081 10082 QualifierCollector qs; 10083 const PointerType* PT; 10084 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10085 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10086 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10087 Context.CharTy)) { 10088 qs.removeConst(); 10089 mismatch = !qs.empty(); 10090 } 10091 } 10092 10093 if (mismatch) { 10094 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10095 // TODO: suggest replacing given type with expected type 10096 FD->setInvalidDecl(true); 10097 } 10098 } 10099 10100 if (nparams == 1 && !FD->isInvalidDecl()) { 10101 Diag(FD->getLocation(), diag::warn_main_one_arg); 10102 } 10103 10104 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10105 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10106 FD->setInvalidDecl(); 10107 } 10108 } 10109 10110 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10111 QualType T = FD->getType(); 10112 assert(T->isFunctionType() && "function decl is not of function type"); 10113 const FunctionType *FT = T->castAs<FunctionType>(); 10114 10115 // Set an implicit return of 'zero' if the function can return some integral, 10116 // enumeration, pointer or nullptr type. 10117 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10118 FT->getReturnType()->isAnyPointerType() || 10119 FT->getReturnType()->isNullPtrType()) 10120 // DllMain is exempt because a return value of zero means it failed. 10121 if (FD->getName() != "DllMain") 10122 FD->setHasImplicitReturnZero(true); 10123 10124 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10125 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10126 FD->setInvalidDecl(); 10127 } 10128 } 10129 10130 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10131 // FIXME: Need strict checking. In C89, we need to check for 10132 // any assignment, increment, decrement, function-calls, or 10133 // commas outside of a sizeof. In C99, it's the same list, 10134 // except that the aforementioned are allowed in unevaluated 10135 // expressions. Everything else falls under the 10136 // "may accept other forms of constant expressions" exception. 10137 // (We never end up here for C++, so the constant expression 10138 // rules there don't matter.) 10139 const Expr *Culprit; 10140 if (Init->isConstantInitializer(Context, false, &Culprit)) 10141 return false; 10142 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10143 << Culprit->getSourceRange(); 10144 return true; 10145 } 10146 10147 namespace { 10148 // Visits an initialization expression to see if OrigDecl is evaluated in 10149 // its own initialization and throws a warning if it does. 10150 class SelfReferenceChecker 10151 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10152 Sema &S; 10153 Decl *OrigDecl; 10154 bool isRecordType; 10155 bool isPODType; 10156 bool isReferenceType; 10157 10158 bool isInitList; 10159 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10160 10161 public: 10162 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10163 10164 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10165 S(S), OrigDecl(OrigDecl) { 10166 isPODType = false; 10167 isRecordType = false; 10168 isReferenceType = false; 10169 isInitList = false; 10170 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10171 isPODType = VD->getType().isPODType(S.Context); 10172 isRecordType = VD->getType()->isRecordType(); 10173 isReferenceType = VD->getType()->isReferenceType(); 10174 } 10175 } 10176 10177 // For most expressions, just call the visitor. For initializer lists, 10178 // track the index of the field being initialized since fields are 10179 // initialized in order allowing use of previously initialized fields. 10180 void CheckExpr(Expr *E) { 10181 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10182 if (!InitList) { 10183 Visit(E); 10184 return; 10185 } 10186 10187 // Track and increment the index here. 10188 isInitList = true; 10189 InitFieldIndex.push_back(0); 10190 for (auto Child : InitList->children()) { 10191 CheckExpr(cast<Expr>(Child)); 10192 ++InitFieldIndex.back(); 10193 } 10194 InitFieldIndex.pop_back(); 10195 } 10196 10197 // Returns true if MemberExpr is checked and no further checking is needed. 10198 // Returns false if additional checking is required. 10199 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10200 llvm::SmallVector<FieldDecl*, 4> Fields; 10201 Expr *Base = E; 10202 bool ReferenceField = false; 10203 10204 // Get the field memebers used. 10205 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10206 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10207 if (!FD) 10208 return false; 10209 Fields.push_back(FD); 10210 if (FD->getType()->isReferenceType()) 10211 ReferenceField = true; 10212 Base = ME->getBase()->IgnoreParenImpCasts(); 10213 } 10214 10215 // Keep checking only if the base Decl is the same. 10216 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10217 if (!DRE || DRE->getDecl() != OrigDecl) 10218 return false; 10219 10220 // A reference field can be bound to an unininitialized field. 10221 if (CheckReference && !ReferenceField) 10222 return true; 10223 10224 // Convert FieldDecls to their index number. 10225 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10226 for (const FieldDecl *I : llvm::reverse(Fields)) 10227 UsedFieldIndex.push_back(I->getFieldIndex()); 10228 10229 // See if a warning is needed by checking the first difference in index 10230 // numbers. If field being used has index less than the field being 10231 // initialized, then the use is safe. 10232 for (auto UsedIter = UsedFieldIndex.begin(), 10233 UsedEnd = UsedFieldIndex.end(), 10234 OrigIter = InitFieldIndex.begin(), 10235 OrigEnd = InitFieldIndex.end(); 10236 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10237 if (*UsedIter < *OrigIter) 10238 return true; 10239 if (*UsedIter > *OrigIter) 10240 break; 10241 } 10242 10243 // TODO: Add a different warning which will print the field names. 10244 HandleDeclRefExpr(DRE); 10245 return true; 10246 } 10247 10248 // For most expressions, the cast is directly above the DeclRefExpr. 10249 // For conditional operators, the cast can be outside the conditional 10250 // operator if both expressions are DeclRefExpr's. 10251 void HandleValue(Expr *E) { 10252 E = E->IgnoreParens(); 10253 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10254 HandleDeclRefExpr(DRE); 10255 return; 10256 } 10257 10258 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10259 Visit(CO->getCond()); 10260 HandleValue(CO->getTrueExpr()); 10261 HandleValue(CO->getFalseExpr()); 10262 return; 10263 } 10264 10265 if (BinaryConditionalOperator *BCO = 10266 dyn_cast<BinaryConditionalOperator>(E)) { 10267 Visit(BCO->getCond()); 10268 HandleValue(BCO->getFalseExpr()); 10269 return; 10270 } 10271 10272 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10273 HandleValue(OVE->getSourceExpr()); 10274 return; 10275 } 10276 10277 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10278 if (BO->getOpcode() == BO_Comma) { 10279 Visit(BO->getLHS()); 10280 HandleValue(BO->getRHS()); 10281 return; 10282 } 10283 } 10284 10285 if (isa<MemberExpr>(E)) { 10286 if (isInitList) { 10287 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10288 false /*CheckReference*/)) 10289 return; 10290 } 10291 10292 Expr *Base = E->IgnoreParenImpCasts(); 10293 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10294 // Check for static member variables and don't warn on them. 10295 if (!isa<FieldDecl>(ME->getMemberDecl())) 10296 return; 10297 Base = ME->getBase()->IgnoreParenImpCasts(); 10298 } 10299 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10300 HandleDeclRefExpr(DRE); 10301 return; 10302 } 10303 10304 Visit(E); 10305 } 10306 10307 // Reference types not handled in HandleValue are handled here since all 10308 // uses of references are bad, not just r-value uses. 10309 void VisitDeclRefExpr(DeclRefExpr *E) { 10310 if (isReferenceType) 10311 HandleDeclRefExpr(E); 10312 } 10313 10314 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10315 if (E->getCastKind() == CK_LValueToRValue) { 10316 HandleValue(E->getSubExpr()); 10317 return; 10318 } 10319 10320 Inherited::VisitImplicitCastExpr(E); 10321 } 10322 10323 void VisitMemberExpr(MemberExpr *E) { 10324 if (isInitList) { 10325 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10326 return; 10327 } 10328 10329 // Don't warn on arrays since they can be treated as pointers. 10330 if (E->getType()->canDecayToPointerType()) return; 10331 10332 // Warn when a non-static method call is followed by non-static member 10333 // field accesses, which is followed by a DeclRefExpr. 10334 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10335 bool Warn = (MD && !MD->isStatic()); 10336 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10337 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10338 if (!isa<FieldDecl>(ME->getMemberDecl())) 10339 Warn = false; 10340 Base = ME->getBase()->IgnoreParenImpCasts(); 10341 } 10342 10343 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10344 if (Warn) 10345 HandleDeclRefExpr(DRE); 10346 return; 10347 } 10348 10349 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10350 // Visit that expression. 10351 Visit(Base); 10352 } 10353 10354 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10355 Expr *Callee = E->getCallee(); 10356 10357 if (isa<UnresolvedLookupExpr>(Callee)) 10358 return Inherited::VisitCXXOperatorCallExpr(E); 10359 10360 Visit(Callee); 10361 for (auto Arg: E->arguments()) 10362 HandleValue(Arg->IgnoreParenImpCasts()); 10363 } 10364 10365 void VisitUnaryOperator(UnaryOperator *E) { 10366 // For POD record types, addresses of its own members are well-defined. 10367 if (E->getOpcode() == UO_AddrOf && isRecordType && 10368 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10369 if (!isPODType) 10370 HandleValue(E->getSubExpr()); 10371 return; 10372 } 10373 10374 if (E->isIncrementDecrementOp()) { 10375 HandleValue(E->getSubExpr()); 10376 return; 10377 } 10378 10379 Inherited::VisitUnaryOperator(E); 10380 } 10381 10382 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10383 10384 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10385 if (E->getConstructor()->isCopyConstructor()) { 10386 Expr *ArgExpr = E->getArg(0); 10387 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10388 if (ILE->getNumInits() == 1) 10389 ArgExpr = ILE->getInit(0); 10390 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10391 if (ICE->getCastKind() == CK_NoOp) 10392 ArgExpr = ICE->getSubExpr(); 10393 HandleValue(ArgExpr); 10394 return; 10395 } 10396 Inherited::VisitCXXConstructExpr(E); 10397 } 10398 10399 void VisitCallExpr(CallExpr *E) { 10400 // Treat std::move as a use. 10401 if (E->isCallToStdMove()) { 10402 HandleValue(E->getArg(0)); 10403 return; 10404 } 10405 10406 Inherited::VisitCallExpr(E); 10407 } 10408 10409 void VisitBinaryOperator(BinaryOperator *E) { 10410 if (E->isCompoundAssignmentOp()) { 10411 HandleValue(E->getLHS()); 10412 Visit(E->getRHS()); 10413 return; 10414 } 10415 10416 Inherited::VisitBinaryOperator(E); 10417 } 10418 10419 // A custom visitor for BinaryConditionalOperator is needed because the 10420 // regular visitor would check the condition and true expression separately 10421 // but both point to the same place giving duplicate diagnostics. 10422 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10423 Visit(E->getCond()); 10424 Visit(E->getFalseExpr()); 10425 } 10426 10427 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10428 Decl* ReferenceDecl = DRE->getDecl(); 10429 if (OrigDecl != ReferenceDecl) return; 10430 unsigned diag; 10431 if (isReferenceType) { 10432 diag = diag::warn_uninit_self_reference_in_reference_init; 10433 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10434 diag = diag::warn_static_self_reference_in_init; 10435 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10436 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10437 DRE->getDecl()->getType()->isRecordType()) { 10438 diag = diag::warn_uninit_self_reference_in_init; 10439 } else { 10440 // Local variables will be handled by the CFG analysis. 10441 return; 10442 } 10443 10444 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10445 S.PDiag(diag) 10446 << DRE->getDecl() 10447 << OrigDecl->getLocation() 10448 << DRE->getSourceRange()); 10449 } 10450 }; 10451 10452 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10453 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10454 bool DirectInit) { 10455 // Parameters arguments are occassionially constructed with itself, 10456 // for instance, in recursive functions. Skip them. 10457 if (isa<ParmVarDecl>(OrigDecl)) 10458 return; 10459 10460 E = E->IgnoreParens(); 10461 10462 // Skip checking T a = a where T is not a record or reference type. 10463 // Doing so is a way to silence uninitialized warnings. 10464 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10465 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10466 if (ICE->getCastKind() == CK_LValueToRValue) 10467 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10468 if (DRE->getDecl() == OrigDecl) 10469 return; 10470 10471 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10472 } 10473 } // end anonymous namespace 10474 10475 namespace { 10476 // Simple wrapper to add the name of a variable or (if no variable is 10477 // available) a DeclarationName into a diagnostic. 10478 struct VarDeclOrName { 10479 VarDecl *VDecl; 10480 DeclarationName Name; 10481 10482 friend const Sema::SemaDiagnosticBuilder & 10483 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10484 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10485 } 10486 }; 10487 } // end anonymous namespace 10488 10489 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10490 DeclarationName Name, QualType Type, 10491 TypeSourceInfo *TSI, 10492 SourceRange Range, bool DirectInit, 10493 Expr *Init) { 10494 bool IsInitCapture = !VDecl; 10495 assert((!VDecl || !VDecl->isInitCapture()) && 10496 "init captures are expected to be deduced prior to initialization"); 10497 10498 VarDeclOrName VN{VDecl, Name}; 10499 10500 DeducedType *Deduced = Type->getContainedDeducedType(); 10501 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10502 10503 // C++11 [dcl.spec.auto]p3 10504 if (!Init) { 10505 assert(VDecl && "no init for init capture deduction?"); 10506 10507 // Except for class argument deduction, and then for an initializing 10508 // declaration only, i.e. no static at class scope or extern. 10509 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10510 VDecl->hasExternalStorage() || 10511 VDecl->isStaticDataMember()) { 10512 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10513 << VDecl->getDeclName() << Type; 10514 return QualType(); 10515 } 10516 } 10517 10518 ArrayRef<Expr*> DeduceInits; 10519 if (Init) 10520 DeduceInits = Init; 10521 10522 if (DirectInit) { 10523 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10524 DeduceInits = PL->exprs(); 10525 } 10526 10527 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10528 assert(VDecl && "non-auto type for init capture deduction?"); 10529 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10530 InitializationKind Kind = InitializationKind::CreateForInit( 10531 VDecl->getLocation(), DirectInit, Init); 10532 // FIXME: Initialization should not be taking a mutable list of inits. 10533 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10534 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10535 InitsCopy); 10536 } 10537 10538 if (DirectInit) { 10539 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10540 DeduceInits = IL->inits(); 10541 } 10542 10543 // Deduction only works if we have exactly one source expression. 10544 if (DeduceInits.empty()) { 10545 // It isn't possible to write this directly, but it is possible to 10546 // end up in this situation with "auto x(some_pack...);" 10547 Diag(Init->getLocStart(), IsInitCapture 10548 ? diag::err_init_capture_no_expression 10549 : diag::err_auto_var_init_no_expression) 10550 << VN << Type << Range; 10551 return QualType(); 10552 } 10553 10554 if (DeduceInits.size() > 1) { 10555 Diag(DeduceInits[1]->getLocStart(), 10556 IsInitCapture ? diag::err_init_capture_multiple_expressions 10557 : diag::err_auto_var_init_multiple_expressions) 10558 << VN << Type << Range; 10559 return QualType(); 10560 } 10561 10562 Expr *DeduceInit = DeduceInits[0]; 10563 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10564 Diag(Init->getLocStart(), IsInitCapture 10565 ? diag::err_init_capture_paren_braces 10566 : diag::err_auto_var_init_paren_braces) 10567 << isa<InitListExpr>(Init) << VN << Type << Range; 10568 return QualType(); 10569 } 10570 10571 // Expressions default to 'id' when we're in a debugger. 10572 bool DefaultedAnyToId = false; 10573 if (getLangOpts().DebuggerCastResultToId && 10574 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10575 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10576 if (Result.isInvalid()) { 10577 return QualType(); 10578 } 10579 Init = Result.get(); 10580 DefaultedAnyToId = true; 10581 } 10582 10583 // C++ [dcl.decomp]p1: 10584 // If the assignment-expression [...] has array type A and no ref-qualifier 10585 // is present, e has type cv A 10586 if (VDecl && isa<DecompositionDecl>(VDecl) && 10587 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10588 DeduceInit->getType()->isConstantArrayType()) 10589 return Context.getQualifiedType(DeduceInit->getType(), 10590 Type.getQualifiers()); 10591 10592 QualType DeducedType; 10593 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10594 if (!IsInitCapture) 10595 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10596 else if (isa<InitListExpr>(Init)) 10597 Diag(Range.getBegin(), 10598 diag::err_init_capture_deduction_failure_from_init_list) 10599 << VN 10600 << (DeduceInit->getType().isNull() ? TSI->getType() 10601 : DeduceInit->getType()) 10602 << DeduceInit->getSourceRange(); 10603 else 10604 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10605 << VN << TSI->getType() 10606 << (DeduceInit->getType().isNull() ? TSI->getType() 10607 : DeduceInit->getType()) 10608 << DeduceInit->getSourceRange(); 10609 } 10610 10611 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10612 // 'id' instead of a specific object type prevents most of our usual 10613 // checks. 10614 // We only want to warn outside of template instantiations, though: 10615 // inside a template, the 'id' could have come from a parameter. 10616 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10617 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10618 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10619 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10620 } 10621 10622 return DeducedType; 10623 } 10624 10625 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10626 Expr *Init) { 10627 QualType DeducedType = deduceVarTypeFromInitializer( 10628 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10629 VDecl->getSourceRange(), DirectInit, Init); 10630 if (DeducedType.isNull()) { 10631 VDecl->setInvalidDecl(); 10632 return true; 10633 } 10634 10635 VDecl->setType(DeducedType); 10636 assert(VDecl->isLinkageValid()); 10637 10638 // In ARC, infer lifetime. 10639 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10640 VDecl->setInvalidDecl(); 10641 10642 // If this is a redeclaration, check that the type we just deduced matches 10643 // the previously declared type. 10644 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10645 // We never need to merge the type, because we cannot form an incomplete 10646 // array of auto, nor deduce such a type. 10647 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10648 } 10649 10650 // Check the deduced type is valid for a variable declaration. 10651 CheckVariableDeclarationType(VDecl); 10652 return VDecl->isInvalidDecl(); 10653 } 10654 10655 /// AddInitializerToDecl - Adds the initializer Init to the 10656 /// declaration dcl. If DirectInit is true, this is C++ direct 10657 /// initialization rather than copy initialization. 10658 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10659 // If there is no declaration, there was an error parsing it. Just ignore 10660 // the initializer. 10661 if (!RealDecl || RealDecl->isInvalidDecl()) { 10662 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10663 return; 10664 } 10665 10666 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10667 // Pure-specifiers are handled in ActOnPureSpecifier. 10668 Diag(Method->getLocation(), diag::err_member_function_initialization) 10669 << Method->getDeclName() << Init->getSourceRange(); 10670 Method->setInvalidDecl(); 10671 return; 10672 } 10673 10674 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10675 if (!VDecl) { 10676 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10677 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10678 RealDecl->setInvalidDecl(); 10679 return; 10680 } 10681 10682 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10683 if (VDecl->getType()->isUndeducedType()) { 10684 // Attempt typo correction early so that the type of the init expression can 10685 // be deduced based on the chosen correction if the original init contains a 10686 // TypoExpr. 10687 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10688 if (!Res.isUsable()) { 10689 RealDecl->setInvalidDecl(); 10690 return; 10691 } 10692 Init = Res.get(); 10693 10694 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10695 return; 10696 } 10697 10698 // dllimport cannot be used on variable definitions. 10699 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10700 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10701 VDecl->setInvalidDecl(); 10702 return; 10703 } 10704 10705 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10706 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10707 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10708 VDecl->setInvalidDecl(); 10709 return; 10710 } 10711 10712 if (!VDecl->getType()->isDependentType()) { 10713 // A definition must end up with a complete type, which means it must be 10714 // complete with the restriction that an array type might be completed by 10715 // the initializer; note that later code assumes this restriction. 10716 QualType BaseDeclType = VDecl->getType(); 10717 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10718 BaseDeclType = Array->getElementType(); 10719 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10720 diag::err_typecheck_decl_incomplete_type)) { 10721 RealDecl->setInvalidDecl(); 10722 return; 10723 } 10724 10725 // The variable can not have an abstract class type. 10726 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10727 diag::err_abstract_type_in_decl, 10728 AbstractVariableType)) 10729 VDecl->setInvalidDecl(); 10730 } 10731 10732 // If adding the initializer will turn this declaration into a definition, 10733 // and we already have a definition for this variable, diagnose or otherwise 10734 // handle the situation. 10735 VarDecl *Def; 10736 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10737 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10738 !VDecl->isThisDeclarationADemotedDefinition() && 10739 checkVarDeclRedefinition(Def, VDecl)) 10740 return; 10741 10742 if (getLangOpts().CPlusPlus) { 10743 // C++ [class.static.data]p4 10744 // If a static data member is of const integral or const 10745 // enumeration type, its declaration in the class definition can 10746 // specify a constant-initializer which shall be an integral 10747 // constant expression (5.19). In that case, the member can appear 10748 // in integral constant expressions. The member shall still be 10749 // defined in a namespace scope if it is used in the program and the 10750 // namespace scope definition shall not contain an initializer. 10751 // 10752 // We already performed a redefinition check above, but for static 10753 // data members we also need to check whether there was an in-class 10754 // declaration with an initializer. 10755 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10756 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10757 << VDecl->getDeclName(); 10758 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10759 diag::note_previous_initializer) 10760 << 0; 10761 return; 10762 } 10763 10764 if (VDecl->hasLocalStorage()) 10765 setFunctionHasBranchProtectedScope(); 10766 10767 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10768 VDecl->setInvalidDecl(); 10769 return; 10770 } 10771 } 10772 10773 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10774 // a kernel function cannot be initialized." 10775 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10776 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10777 VDecl->setInvalidDecl(); 10778 return; 10779 } 10780 10781 // Get the decls type and save a reference for later, since 10782 // CheckInitializerTypes may change it. 10783 QualType DclT = VDecl->getType(), SavT = DclT; 10784 10785 // Expressions default to 'id' when we're in a debugger 10786 // and we are assigning it to a variable of Objective-C pointer type. 10787 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10788 Init->getType() == Context.UnknownAnyTy) { 10789 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10790 if (Result.isInvalid()) { 10791 VDecl->setInvalidDecl(); 10792 return; 10793 } 10794 Init = Result.get(); 10795 } 10796 10797 // Perform the initialization. 10798 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10799 if (!VDecl->isInvalidDecl()) { 10800 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10801 InitializationKind Kind = InitializationKind::CreateForInit( 10802 VDecl->getLocation(), DirectInit, Init); 10803 10804 MultiExprArg Args = Init; 10805 if (CXXDirectInit) 10806 Args = MultiExprArg(CXXDirectInit->getExprs(), 10807 CXXDirectInit->getNumExprs()); 10808 10809 // Try to correct any TypoExprs in the initialization arguments. 10810 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10811 ExprResult Res = CorrectDelayedTyposInExpr( 10812 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10813 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10814 return Init.Failed() ? ExprError() : E; 10815 }); 10816 if (Res.isInvalid()) { 10817 VDecl->setInvalidDecl(); 10818 } else if (Res.get() != Args[Idx]) { 10819 Args[Idx] = Res.get(); 10820 } 10821 } 10822 if (VDecl->isInvalidDecl()) 10823 return; 10824 10825 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10826 /*TopLevelOfInitList=*/false, 10827 /*TreatUnavailableAsInvalid=*/false); 10828 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10829 if (Result.isInvalid()) { 10830 VDecl->setInvalidDecl(); 10831 return; 10832 } 10833 10834 Init = Result.getAs<Expr>(); 10835 } 10836 10837 // Check for self-references within variable initializers. 10838 // Variables declared within a function/method body (except for references) 10839 // are handled by a dataflow analysis. 10840 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10841 VDecl->getType()->isReferenceType()) { 10842 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10843 } 10844 10845 // If the type changed, it means we had an incomplete type that was 10846 // completed by the initializer. For example: 10847 // int ary[] = { 1, 3, 5 }; 10848 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10849 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10850 VDecl->setType(DclT); 10851 10852 if (!VDecl->isInvalidDecl()) { 10853 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10854 10855 if (VDecl->hasAttr<BlocksAttr>()) 10856 checkRetainCycles(VDecl, Init); 10857 10858 // It is safe to assign a weak reference into a strong variable. 10859 // Although this code can still have problems: 10860 // id x = self.weakProp; 10861 // id y = self.weakProp; 10862 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10863 // paths through the function. This should be revisited if 10864 // -Wrepeated-use-of-weak is made flow-sensitive. 10865 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10866 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10867 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10868 Init->getLocStart())) 10869 getCurFunction()->markSafeWeakUse(Init); 10870 } 10871 10872 // The initialization is usually a full-expression. 10873 // 10874 // FIXME: If this is a braced initialization of an aggregate, it is not 10875 // an expression, and each individual field initializer is a separate 10876 // full-expression. For instance, in: 10877 // 10878 // struct Temp { ~Temp(); }; 10879 // struct S { S(Temp); }; 10880 // struct T { S a, b; } t = { Temp(), Temp() } 10881 // 10882 // we should destroy the first Temp before constructing the second. 10883 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10884 false, 10885 VDecl->isConstexpr()); 10886 if (Result.isInvalid()) { 10887 VDecl->setInvalidDecl(); 10888 return; 10889 } 10890 Init = Result.get(); 10891 10892 // Attach the initializer to the decl. 10893 VDecl->setInit(Init); 10894 10895 if (VDecl->isLocalVarDecl()) { 10896 // Don't check the initializer if the declaration is malformed. 10897 if (VDecl->isInvalidDecl()) { 10898 // do nothing 10899 10900 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10901 // This is true even in OpenCL C++. 10902 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10903 CheckForConstantInitializer(Init, DclT); 10904 10905 // Otherwise, C++ does not restrict the initializer. 10906 } else if (getLangOpts().CPlusPlus) { 10907 // do nothing 10908 10909 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10910 // static storage duration shall be constant expressions or string literals. 10911 } else if (VDecl->getStorageClass() == SC_Static) { 10912 CheckForConstantInitializer(Init, DclT); 10913 10914 // C89 is stricter than C99 for aggregate initializers. 10915 // C89 6.5.7p3: All the expressions [...] in an initializer list 10916 // for an object that has aggregate or union type shall be 10917 // constant expressions. 10918 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10919 isa<InitListExpr>(Init)) { 10920 const Expr *Culprit; 10921 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10922 Diag(Culprit->getExprLoc(), 10923 diag::ext_aggregate_init_not_constant) 10924 << Culprit->getSourceRange(); 10925 } 10926 } 10927 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10928 VDecl->getLexicalDeclContext()->isRecord()) { 10929 // This is an in-class initialization for a static data member, e.g., 10930 // 10931 // struct S { 10932 // static const int value = 17; 10933 // }; 10934 10935 // C++ [class.mem]p4: 10936 // A member-declarator can contain a constant-initializer only 10937 // if it declares a static member (9.4) of const integral or 10938 // const enumeration type, see 9.4.2. 10939 // 10940 // C++11 [class.static.data]p3: 10941 // If a non-volatile non-inline const static data member is of integral 10942 // or enumeration type, its declaration in the class definition can 10943 // specify a brace-or-equal-initializer in which every initializer-clause 10944 // that is an assignment-expression is a constant expression. A static 10945 // data member of literal type can be declared in the class definition 10946 // with the constexpr specifier; if so, its declaration shall specify a 10947 // brace-or-equal-initializer in which every initializer-clause that is 10948 // an assignment-expression is a constant expression. 10949 10950 // Do nothing on dependent types. 10951 if (DclT->isDependentType()) { 10952 10953 // Allow any 'static constexpr' members, whether or not they are of literal 10954 // type. We separately check that every constexpr variable is of literal 10955 // type. 10956 } else if (VDecl->isConstexpr()) { 10957 10958 // Require constness. 10959 } else if (!DclT.isConstQualified()) { 10960 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10961 << Init->getSourceRange(); 10962 VDecl->setInvalidDecl(); 10963 10964 // We allow integer constant expressions in all cases. 10965 } else if (DclT->isIntegralOrEnumerationType()) { 10966 // Check whether the expression is a constant expression. 10967 SourceLocation Loc; 10968 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10969 // In C++11, a non-constexpr const static data member with an 10970 // in-class initializer cannot be volatile. 10971 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10972 else if (Init->isValueDependent()) 10973 ; // Nothing to check. 10974 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10975 ; // Ok, it's an ICE! 10976 else if (Init->isEvaluatable(Context)) { 10977 // If we can constant fold the initializer through heroics, accept it, 10978 // but report this as a use of an extension for -pedantic. 10979 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10980 << Init->getSourceRange(); 10981 } else { 10982 // Otherwise, this is some crazy unknown case. Report the issue at the 10983 // location provided by the isIntegerConstantExpr failed check. 10984 Diag(Loc, diag::err_in_class_initializer_non_constant) 10985 << Init->getSourceRange(); 10986 VDecl->setInvalidDecl(); 10987 } 10988 10989 // We allow foldable floating-point constants as an extension. 10990 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10991 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10992 // it anyway and provide a fixit to add the 'constexpr'. 10993 if (getLangOpts().CPlusPlus11) { 10994 Diag(VDecl->getLocation(), 10995 diag::ext_in_class_initializer_float_type_cxx11) 10996 << DclT << Init->getSourceRange(); 10997 Diag(VDecl->getLocStart(), 10998 diag::note_in_class_initializer_float_type_cxx11) 10999 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 11000 } else { 11001 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 11002 << DclT << Init->getSourceRange(); 11003 11004 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 11005 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 11006 << Init->getSourceRange(); 11007 VDecl->setInvalidDecl(); 11008 } 11009 } 11010 11011 // Suggest adding 'constexpr' in C++11 for literal types. 11012 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 11013 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 11014 << DclT << Init->getSourceRange() 11015 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 11016 VDecl->setConstexpr(true); 11017 11018 } else { 11019 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 11020 << DclT << Init->getSourceRange(); 11021 VDecl->setInvalidDecl(); 11022 } 11023 } else if (VDecl->isFileVarDecl()) { 11024 // In C, extern is typically used to avoid tentative definitions when 11025 // declaring variables in headers, but adding an intializer makes it a 11026 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 11027 // In C++, extern is often used to give implictly static const variables 11028 // external linkage, so don't warn in that case. If selectany is present, 11029 // this might be header code intended for C and C++ inclusion, so apply the 11030 // C++ rules. 11031 if (VDecl->getStorageClass() == SC_Extern && 11032 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 11033 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 11034 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 11035 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 11036 Diag(VDecl->getLocation(), diag::warn_extern_init); 11037 11038 // C99 6.7.8p4. All file scoped initializers need to be constant. 11039 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 11040 CheckForConstantInitializer(Init, DclT); 11041 } 11042 11043 // We will represent direct-initialization similarly to copy-initialization: 11044 // int x(1); -as-> int x = 1; 11045 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 11046 // 11047 // Clients that want to distinguish between the two forms, can check for 11048 // direct initializer using VarDecl::getInitStyle(). 11049 // A major benefit is that clients that don't particularly care about which 11050 // exactly form was it (like the CodeGen) can handle both cases without 11051 // special case code. 11052 11053 // C++ 8.5p11: 11054 // The form of initialization (using parentheses or '=') is generally 11055 // insignificant, but does matter when the entity being initialized has a 11056 // class type. 11057 if (CXXDirectInit) { 11058 assert(DirectInit && "Call-style initializer must be direct init."); 11059 VDecl->setInitStyle(VarDecl::CallInit); 11060 } else if (DirectInit) { 11061 // This must be list-initialization. No other way is direct-initialization. 11062 VDecl->setInitStyle(VarDecl::ListInit); 11063 } 11064 11065 CheckCompleteVariableDeclaration(VDecl); 11066 } 11067 11068 /// ActOnInitializerError - Given that there was an error parsing an 11069 /// initializer for the given declaration, try to return to some form 11070 /// of sanity. 11071 void Sema::ActOnInitializerError(Decl *D) { 11072 // Our main concern here is re-establishing invariants like "a 11073 // variable's type is either dependent or complete". 11074 if (!D || D->isInvalidDecl()) return; 11075 11076 VarDecl *VD = dyn_cast<VarDecl>(D); 11077 if (!VD) return; 11078 11079 // Bindings are not usable if we can't make sense of the initializer. 11080 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11081 for (auto *BD : DD->bindings()) 11082 BD->setInvalidDecl(); 11083 11084 // Auto types are meaningless if we can't make sense of the initializer. 11085 if (ParsingInitForAutoVars.count(D)) { 11086 D->setInvalidDecl(); 11087 return; 11088 } 11089 11090 QualType Ty = VD->getType(); 11091 if (Ty->isDependentType()) return; 11092 11093 // Require a complete type. 11094 if (RequireCompleteType(VD->getLocation(), 11095 Context.getBaseElementType(Ty), 11096 diag::err_typecheck_decl_incomplete_type)) { 11097 VD->setInvalidDecl(); 11098 return; 11099 } 11100 11101 // Require a non-abstract type. 11102 if (RequireNonAbstractType(VD->getLocation(), Ty, 11103 diag::err_abstract_type_in_decl, 11104 AbstractVariableType)) { 11105 VD->setInvalidDecl(); 11106 return; 11107 } 11108 11109 // Don't bother complaining about constructors or destructors, 11110 // though. 11111 } 11112 11113 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11114 // If there is no declaration, there was an error parsing it. Just ignore it. 11115 if (!RealDecl) 11116 return; 11117 11118 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11119 QualType Type = Var->getType(); 11120 11121 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11122 if (isa<DecompositionDecl>(RealDecl)) { 11123 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11124 Var->setInvalidDecl(); 11125 return; 11126 } 11127 11128 if (Type->isUndeducedType() && 11129 DeduceVariableDeclarationType(Var, false, nullptr)) 11130 return; 11131 11132 // C++11 [class.static.data]p3: A static data member can be declared with 11133 // the constexpr specifier; if so, its declaration shall specify 11134 // a brace-or-equal-initializer. 11135 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11136 // the definition of a variable [...] or the declaration of a static data 11137 // member. 11138 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11139 !Var->isThisDeclarationADemotedDefinition()) { 11140 if (Var->isStaticDataMember()) { 11141 // C++1z removes the relevant rule; the in-class declaration is always 11142 // a definition there. 11143 if (!getLangOpts().CPlusPlus17) { 11144 Diag(Var->getLocation(), 11145 diag::err_constexpr_static_mem_var_requires_init) 11146 << Var->getDeclName(); 11147 Var->setInvalidDecl(); 11148 return; 11149 } 11150 } else { 11151 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11152 Var->setInvalidDecl(); 11153 return; 11154 } 11155 } 11156 11157 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11158 // be initialized. 11159 if (!Var->isInvalidDecl() && 11160 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11161 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11162 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11163 Var->setInvalidDecl(); 11164 return; 11165 } 11166 11167 switch (Var->isThisDeclarationADefinition()) { 11168 case VarDecl::Definition: 11169 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11170 break; 11171 11172 // We have an out-of-line definition of a static data member 11173 // that has an in-class initializer, so we type-check this like 11174 // a declaration. 11175 // 11176 LLVM_FALLTHROUGH; 11177 11178 case VarDecl::DeclarationOnly: 11179 // It's only a declaration. 11180 11181 // Block scope. C99 6.7p7: If an identifier for an object is 11182 // declared with no linkage (C99 6.2.2p6), the type for the 11183 // object shall be complete. 11184 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11185 !Var->hasLinkage() && !Var->isInvalidDecl() && 11186 RequireCompleteType(Var->getLocation(), Type, 11187 diag::err_typecheck_decl_incomplete_type)) 11188 Var->setInvalidDecl(); 11189 11190 // Make sure that the type is not abstract. 11191 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11192 RequireNonAbstractType(Var->getLocation(), Type, 11193 diag::err_abstract_type_in_decl, 11194 AbstractVariableType)) 11195 Var->setInvalidDecl(); 11196 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11197 Var->getStorageClass() == SC_PrivateExtern) { 11198 Diag(Var->getLocation(), diag::warn_private_extern); 11199 Diag(Var->getLocation(), diag::note_private_extern); 11200 } 11201 11202 return; 11203 11204 case VarDecl::TentativeDefinition: 11205 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11206 // object that has file scope without an initializer, and without a 11207 // storage-class specifier or with the storage-class specifier "static", 11208 // constitutes a tentative definition. Note: A tentative definition with 11209 // external linkage is valid (C99 6.2.2p5). 11210 if (!Var->isInvalidDecl()) { 11211 if (const IncompleteArrayType *ArrayT 11212 = Context.getAsIncompleteArrayType(Type)) { 11213 if (RequireCompleteType(Var->getLocation(), 11214 ArrayT->getElementType(), 11215 diag::err_illegal_decl_array_incomplete_type)) 11216 Var->setInvalidDecl(); 11217 } else if (Var->getStorageClass() == SC_Static) { 11218 // C99 6.9.2p3: If the declaration of an identifier for an object is 11219 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11220 // declared type shall not be an incomplete type. 11221 // NOTE: code such as the following 11222 // static struct s; 11223 // struct s { int a; }; 11224 // is accepted by gcc. Hence here we issue a warning instead of 11225 // an error and we do not invalidate the static declaration. 11226 // NOTE: to avoid multiple warnings, only check the first declaration. 11227 if (Var->isFirstDecl()) 11228 RequireCompleteType(Var->getLocation(), Type, 11229 diag::ext_typecheck_decl_incomplete_type); 11230 } 11231 } 11232 11233 // Record the tentative definition; we're done. 11234 if (!Var->isInvalidDecl()) 11235 TentativeDefinitions.push_back(Var); 11236 return; 11237 } 11238 11239 // Provide a specific diagnostic for uninitialized variable 11240 // definitions with incomplete array type. 11241 if (Type->isIncompleteArrayType()) { 11242 Diag(Var->getLocation(), 11243 diag::err_typecheck_incomplete_array_needs_initializer); 11244 Var->setInvalidDecl(); 11245 return; 11246 } 11247 11248 // Provide a specific diagnostic for uninitialized variable 11249 // definitions with reference type. 11250 if (Type->isReferenceType()) { 11251 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11252 << Var->getDeclName() 11253 << SourceRange(Var->getLocation(), Var->getLocation()); 11254 Var->setInvalidDecl(); 11255 return; 11256 } 11257 11258 // Do not attempt to type-check the default initializer for a 11259 // variable with dependent type. 11260 if (Type->isDependentType()) 11261 return; 11262 11263 if (Var->isInvalidDecl()) 11264 return; 11265 11266 if (!Var->hasAttr<AliasAttr>()) { 11267 if (RequireCompleteType(Var->getLocation(), 11268 Context.getBaseElementType(Type), 11269 diag::err_typecheck_decl_incomplete_type)) { 11270 Var->setInvalidDecl(); 11271 return; 11272 } 11273 } else { 11274 return; 11275 } 11276 11277 // The variable can not have an abstract class type. 11278 if (RequireNonAbstractType(Var->getLocation(), Type, 11279 diag::err_abstract_type_in_decl, 11280 AbstractVariableType)) { 11281 Var->setInvalidDecl(); 11282 return; 11283 } 11284 11285 // Check for jumps past the implicit initializer. C++0x 11286 // clarifies that this applies to a "variable with automatic 11287 // storage duration", not a "local variable". 11288 // C++11 [stmt.dcl]p3 11289 // A program that jumps from a point where a variable with automatic 11290 // storage duration is not in scope to a point where it is in scope is 11291 // ill-formed unless the variable has scalar type, class type with a 11292 // trivial default constructor and a trivial destructor, a cv-qualified 11293 // version of one of these types, or an array of one of the preceding 11294 // types and is declared without an initializer. 11295 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11296 if (const RecordType *Record 11297 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11298 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11299 // Mark the function (if we're in one) for further checking even if the 11300 // looser rules of C++11 do not require such checks, so that we can 11301 // diagnose incompatibilities with C++98. 11302 if (!CXXRecord->isPOD()) 11303 setFunctionHasBranchProtectedScope(); 11304 } 11305 } 11306 11307 // C++03 [dcl.init]p9: 11308 // If no initializer is specified for an object, and the 11309 // object is of (possibly cv-qualified) non-POD class type (or 11310 // array thereof), the object shall be default-initialized; if 11311 // the object is of const-qualified type, the underlying class 11312 // type shall have a user-declared default 11313 // constructor. Otherwise, if no initializer is specified for 11314 // a non- static object, the object and its subobjects, if 11315 // any, have an indeterminate initial value); if the object 11316 // or any of its subobjects are of const-qualified type, the 11317 // program is ill-formed. 11318 // C++0x [dcl.init]p11: 11319 // If no initializer is specified for an object, the object is 11320 // default-initialized; [...]. 11321 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11322 InitializationKind Kind 11323 = InitializationKind::CreateDefault(Var->getLocation()); 11324 11325 InitializationSequence InitSeq(*this, Entity, Kind, None); 11326 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11327 if (Init.isInvalid()) 11328 Var->setInvalidDecl(); 11329 else if (Init.get()) { 11330 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11331 // This is important for template substitution. 11332 Var->setInitStyle(VarDecl::CallInit); 11333 } 11334 11335 CheckCompleteVariableDeclaration(Var); 11336 } 11337 } 11338 11339 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11340 // If there is no declaration, there was an error parsing it. Ignore it. 11341 if (!D) 11342 return; 11343 11344 VarDecl *VD = dyn_cast<VarDecl>(D); 11345 if (!VD) { 11346 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11347 D->setInvalidDecl(); 11348 return; 11349 } 11350 11351 VD->setCXXForRangeDecl(true); 11352 11353 // for-range-declaration cannot be given a storage class specifier. 11354 int Error = -1; 11355 switch (VD->getStorageClass()) { 11356 case SC_None: 11357 break; 11358 case SC_Extern: 11359 Error = 0; 11360 break; 11361 case SC_Static: 11362 Error = 1; 11363 break; 11364 case SC_PrivateExtern: 11365 Error = 2; 11366 break; 11367 case SC_Auto: 11368 Error = 3; 11369 break; 11370 case SC_Register: 11371 Error = 4; 11372 break; 11373 } 11374 if (Error != -1) { 11375 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11376 << VD->getDeclName() << Error; 11377 D->setInvalidDecl(); 11378 } 11379 } 11380 11381 StmtResult 11382 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11383 IdentifierInfo *Ident, 11384 ParsedAttributes &Attrs, 11385 SourceLocation AttrEnd) { 11386 // C++1y [stmt.iter]p1: 11387 // A range-based for statement of the form 11388 // for ( for-range-identifier : for-range-initializer ) statement 11389 // is equivalent to 11390 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11391 DeclSpec DS(Attrs.getPool().getFactory()); 11392 11393 const char *PrevSpec; 11394 unsigned DiagID; 11395 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11396 getPrintingPolicy()); 11397 11398 Declarator D(DS, DeclaratorContext::ForContext); 11399 D.SetIdentifier(Ident, IdentLoc); 11400 D.takeAttributes(Attrs, AttrEnd); 11401 11402 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11403 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 11404 EmptyAttrs, IdentLoc); 11405 Decl *Var = ActOnDeclarator(S, D); 11406 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11407 FinalizeDeclaration(Var); 11408 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11409 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11410 } 11411 11412 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11413 if (var->isInvalidDecl()) return; 11414 11415 if (getLangOpts().OpenCL) { 11416 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11417 // initialiser 11418 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11419 !var->hasInit()) { 11420 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11421 << 1 /*Init*/; 11422 var->setInvalidDecl(); 11423 return; 11424 } 11425 } 11426 11427 // In Objective-C, don't allow jumps past the implicit initialization of a 11428 // local retaining variable. 11429 if (getLangOpts().ObjC1 && 11430 var->hasLocalStorage()) { 11431 switch (var->getType().getObjCLifetime()) { 11432 case Qualifiers::OCL_None: 11433 case Qualifiers::OCL_ExplicitNone: 11434 case Qualifiers::OCL_Autoreleasing: 11435 break; 11436 11437 case Qualifiers::OCL_Weak: 11438 case Qualifiers::OCL_Strong: 11439 setFunctionHasBranchProtectedScope(); 11440 break; 11441 } 11442 } 11443 11444 if (var->hasLocalStorage() && 11445 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11446 setFunctionHasBranchProtectedScope(); 11447 11448 // Warn about externally-visible variables being defined without a 11449 // prior declaration. We only want to do this for global 11450 // declarations, but we also specifically need to avoid doing it for 11451 // class members because the linkage of an anonymous class can 11452 // change if it's later given a typedef name. 11453 if (var->isThisDeclarationADefinition() && 11454 var->getDeclContext()->getRedeclContext()->isFileContext() && 11455 var->isExternallyVisible() && var->hasLinkage() && 11456 !var->isInline() && !var->getDescribedVarTemplate() && 11457 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11458 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11459 var->getLocation())) { 11460 // Find a previous declaration that's not a definition. 11461 VarDecl *prev = var->getPreviousDecl(); 11462 while (prev && prev->isThisDeclarationADefinition()) 11463 prev = prev->getPreviousDecl(); 11464 11465 if (!prev) 11466 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11467 } 11468 11469 // Cache the result of checking for constant initialization. 11470 Optional<bool> CacheHasConstInit; 11471 const Expr *CacheCulprit; 11472 auto checkConstInit = [&]() mutable { 11473 if (!CacheHasConstInit) 11474 CacheHasConstInit = var->getInit()->isConstantInitializer( 11475 Context, var->getType()->isReferenceType(), &CacheCulprit); 11476 return *CacheHasConstInit; 11477 }; 11478 11479 if (var->getTLSKind() == VarDecl::TLS_Static) { 11480 if (var->getType().isDestructedType()) { 11481 // GNU C++98 edits for __thread, [basic.start.term]p3: 11482 // The type of an object with thread storage duration shall not 11483 // have a non-trivial destructor. 11484 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11485 if (getLangOpts().CPlusPlus11) 11486 Diag(var->getLocation(), diag::note_use_thread_local); 11487 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11488 if (!checkConstInit()) { 11489 // GNU C++98 edits for __thread, [basic.start.init]p4: 11490 // An object of thread storage duration shall not require dynamic 11491 // initialization. 11492 // FIXME: Need strict checking here. 11493 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11494 << CacheCulprit->getSourceRange(); 11495 if (getLangOpts().CPlusPlus11) 11496 Diag(var->getLocation(), diag::note_use_thread_local); 11497 } 11498 } 11499 } 11500 11501 // Apply section attributes and pragmas to global variables. 11502 bool GlobalStorage = var->hasGlobalStorage(); 11503 if (GlobalStorage && var->isThisDeclarationADefinition() && 11504 !inTemplateInstantiation()) { 11505 PragmaStack<StringLiteral *> *Stack = nullptr; 11506 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11507 if (var->getType().isConstQualified()) 11508 Stack = &ConstSegStack; 11509 else if (!var->getInit()) { 11510 Stack = &BSSSegStack; 11511 SectionFlags |= ASTContext::PSF_Write; 11512 } else { 11513 Stack = &DataSegStack; 11514 SectionFlags |= ASTContext::PSF_Write; 11515 } 11516 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11517 var->addAttr(SectionAttr::CreateImplicit( 11518 Context, SectionAttr::Declspec_allocate, 11519 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11520 } 11521 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11522 if (UnifySection(SA->getName(), SectionFlags, var)) 11523 var->dropAttr<SectionAttr>(); 11524 11525 // Apply the init_seg attribute if this has an initializer. If the 11526 // initializer turns out to not be dynamic, we'll end up ignoring this 11527 // attribute. 11528 if (CurInitSeg && var->getInit()) 11529 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11530 CurInitSegLoc)); 11531 } 11532 11533 // All the following checks are C++ only. 11534 if (!getLangOpts().CPlusPlus) { 11535 // If this variable must be emitted, add it as an initializer for the 11536 // current module. 11537 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11538 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11539 return; 11540 } 11541 11542 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11543 CheckCompleteDecompositionDeclaration(DD); 11544 11545 QualType type = var->getType(); 11546 if (type->isDependentType()) return; 11547 11548 // __block variables might require us to capture a copy-initializer. 11549 if (var->hasAttr<BlocksAttr>()) { 11550 // It's currently invalid to ever have a __block variable with an 11551 // array type; should we diagnose that here? 11552 11553 // Regardless, we don't want to ignore array nesting when 11554 // constructing this copy. 11555 if (type->isStructureOrClassType()) { 11556 EnterExpressionEvaluationContext scope( 11557 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11558 SourceLocation poi = var->getLocation(); 11559 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11560 ExprResult result 11561 = PerformMoveOrCopyInitialization( 11562 InitializedEntity::InitializeBlock(poi, type, false), 11563 var, var->getType(), varRef, /*AllowNRVO=*/true); 11564 if (!result.isInvalid()) { 11565 result = MaybeCreateExprWithCleanups(result); 11566 Expr *init = result.getAs<Expr>(); 11567 Context.setBlockVarCopyInits(var, init); 11568 } 11569 } 11570 } 11571 11572 Expr *Init = var->getInit(); 11573 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11574 QualType baseType = Context.getBaseElementType(type); 11575 11576 if (Init && !Init->isValueDependent()) { 11577 if (var->isConstexpr()) { 11578 SmallVector<PartialDiagnosticAt, 8> Notes; 11579 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11580 SourceLocation DiagLoc = var->getLocation(); 11581 // If the note doesn't add any useful information other than a source 11582 // location, fold it into the primary diagnostic. 11583 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11584 diag::note_invalid_subexpr_in_const_expr) { 11585 DiagLoc = Notes[0].first; 11586 Notes.clear(); 11587 } 11588 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11589 << var << Init->getSourceRange(); 11590 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11591 Diag(Notes[I].first, Notes[I].second); 11592 } 11593 } else if (var->isUsableInConstantExpressions(Context)) { 11594 // Check whether the initializer of a const variable of integral or 11595 // enumeration type is an ICE now, since we can't tell whether it was 11596 // initialized by a constant expression if we check later. 11597 var->checkInitIsICE(); 11598 } 11599 11600 // Don't emit further diagnostics about constexpr globals since they 11601 // were just diagnosed. 11602 if (!var->isConstexpr() && GlobalStorage && 11603 var->hasAttr<RequireConstantInitAttr>()) { 11604 // FIXME: Need strict checking in C++03 here. 11605 bool DiagErr = getLangOpts().CPlusPlus11 11606 ? !var->checkInitIsICE() : !checkConstInit(); 11607 if (DiagErr) { 11608 auto attr = var->getAttr<RequireConstantInitAttr>(); 11609 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11610 << Init->getSourceRange(); 11611 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11612 << attr->getRange(); 11613 if (getLangOpts().CPlusPlus11) { 11614 APValue Value; 11615 SmallVector<PartialDiagnosticAt, 8> Notes; 11616 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11617 for (auto &it : Notes) 11618 Diag(it.first, it.second); 11619 } else { 11620 Diag(CacheCulprit->getExprLoc(), 11621 diag::note_invalid_subexpr_in_const_expr) 11622 << CacheCulprit->getSourceRange(); 11623 } 11624 } 11625 } 11626 else if (!var->isConstexpr() && IsGlobal && 11627 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11628 var->getLocation())) { 11629 // Warn about globals which don't have a constant initializer. Don't 11630 // warn about globals with a non-trivial destructor because we already 11631 // warned about them. 11632 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11633 if (!(RD && !RD->hasTrivialDestructor())) { 11634 if (!checkConstInit()) 11635 Diag(var->getLocation(), diag::warn_global_constructor) 11636 << Init->getSourceRange(); 11637 } 11638 } 11639 } 11640 11641 // Require the destructor. 11642 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11643 FinalizeVarWithDestructor(var, recordType); 11644 11645 // If this variable must be emitted, add it as an initializer for the current 11646 // module. 11647 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11648 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11649 } 11650 11651 /// Determines if a variable's alignment is dependent. 11652 static bool hasDependentAlignment(VarDecl *VD) { 11653 if (VD->getType()->isDependentType()) 11654 return true; 11655 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11656 if (I->isAlignmentDependent()) 11657 return true; 11658 return false; 11659 } 11660 11661 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11662 /// any semantic actions necessary after any initializer has been attached. 11663 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11664 // Note that we are no longer parsing the initializer for this declaration. 11665 ParsingInitForAutoVars.erase(ThisDecl); 11666 11667 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11668 if (!VD) 11669 return; 11670 11671 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11672 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11673 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11674 if (PragmaClangBSSSection.Valid) 11675 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11676 PragmaClangBSSSection.SectionName, 11677 PragmaClangBSSSection.PragmaLocation)); 11678 if (PragmaClangDataSection.Valid) 11679 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11680 PragmaClangDataSection.SectionName, 11681 PragmaClangDataSection.PragmaLocation)); 11682 if (PragmaClangRodataSection.Valid) 11683 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11684 PragmaClangRodataSection.SectionName, 11685 PragmaClangRodataSection.PragmaLocation)); 11686 } 11687 11688 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11689 for (auto *BD : DD->bindings()) { 11690 FinalizeDeclaration(BD); 11691 } 11692 } 11693 11694 checkAttributesAfterMerging(*this, *VD); 11695 11696 // Perform TLS alignment check here after attributes attached to the variable 11697 // which may affect the alignment have been processed. Only perform the check 11698 // if the target has a maximum TLS alignment (zero means no constraints). 11699 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11700 // Protect the check so that it's not performed on dependent types and 11701 // dependent alignments (we can't determine the alignment in that case). 11702 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11703 !VD->isInvalidDecl()) { 11704 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11705 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11706 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11707 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11708 << (unsigned)MaxAlignChars.getQuantity(); 11709 } 11710 } 11711 } 11712 11713 if (VD->isStaticLocal()) { 11714 if (FunctionDecl *FD = 11715 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11716 // Static locals inherit dll attributes from their function. 11717 if (Attr *A = getDLLAttr(FD)) { 11718 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11719 NewAttr->setInherited(true); 11720 VD->addAttr(NewAttr); 11721 } 11722 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11723 // function, only __shared__ variables may be declared with 11724 // static storage class. 11725 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11726 CUDADiagIfDeviceCode(VD->getLocation(), 11727 diag::err_device_static_local_var) 11728 << CurrentCUDATarget()) 11729 VD->setInvalidDecl(); 11730 } 11731 } 11732 11733 // Perform check for initializers of device-side global variables. 11734 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11735 // 7.5). We must also apply the same checks to all __shared__ 11736 // variables whether they are local or not. CUDA also allows 11737 // constant initializers for __constant__ and __device__ variables. 11738 if (getLangOpts().CUDA) { 11739 const Expr *Init = VD->getInit(); 11740 if (Init && VD->hasGlobalStorage()) { 11741 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11742 VD->hasAttr<CUDASharedAttr>()) { 11743 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11744 bool AllowedInit = false; 11745 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11746 AllowedInit = 11747 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11748 // We'll allow constant initializers even if it's a non-empty 11749 // constructor according to CUDA rules. This deviates from NVCC, 11750 // but allows us to handle things like constexpr constructors. 11751 if (!AllowedInit && 11752 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11753 AllowedInit = VD->getInit()->isConstantInitializer( 11754 Context, VD->getType()->isReferenceType()); 11755 11756 // Also make sure that destructor, if there is one, is empty. 11757 if (AllowedInit) 11758 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11759 AllowedInit = 11760 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11761 11762 if (!AllowedInit) { 11763 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11764 ? diag::err_shared_var_init 11765 : diag::err_dynamic_var_init) 11766 << Init->getSourceRange(); 11767 VD->setInvalidDecl(); 11768 } 11769 } else { 11770 // This is a host-side global variable. Check that the initializer is 11771 // callable from the host side. 11772 const FunctionDecl *InitFn = nullptr; 11773 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11774 InitFn = CE->getConstructor(); 11775 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11776 InitFn = CE->getDirectCallee(); 11777 } 11778 if (InitFn) { 11779 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11780 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11781 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11782 << InitFnTarget << InitFn; 11783 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11784 VD->setInvalidDecl(); 11785 } 11786 } 11787 } 11788 } 11789 } 11790 11791 // Grab the dllimport or dllexport attribute off of the VarDecl. 11792 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11793 11794 // Imported static data members cannot be defined out-of-line. 11795 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11796 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11797 VD->isThisDeclarationADefinition()) { 11798 // We allow definitions of dllimport class template static data members 11799 // with a warning. 11800 CXXRecordDecl *Context = 11801 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11802 bool IsClassTemplateMember = 11803 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11804 Context->getDescribedClassTemplate(); 11805 11806 Diag(VD->getLocation(), 11807 IsClassTemplateMember 11808 ? diag::warn_attribute_dllimport_static_field_definition 11809 : diag::err_attribute_dllimport_static_field_definition); 11810 Diag(IA->getLocation(), diag::note_attribute); 11811 if (!IsClassTemplateMember) 11812 VD->setInvalidDecl(); 11813 } 11814 } 11815 11816 // dllimport/dllexport variables cannot be thread local, their TLS index 11817 // isn't exported with the variable. 11818 if (DLLAttr && VD->getTLSKind()) { 11819 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11820 if (F && getDLLAttr(F)) { 11821 assert(VD->isStaticLocal()); 11822 // But if this is a static local in a dlimport/dllexport function, the 11823 // function will never be inlined, which means the var would never be 11824 // imported, so having it marked import/export is safe. 11825 } else { 11826 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11827 << DLLAttr; 11828 VD->setInvalidDecl(); 11829 } 11830 } 11831 11832 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11833 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11834 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11835 VD->dropAttr<UsedAttr>(); 11836 } 11837 } 11838 11839 const DeclContext *DC = VD->getDeclContext(); 11840 // If there's a #pragma GCC visibility in scope, and this isn't a class 11841 // member, set the visibility of this variable. 11842 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11843 AddPushedVisibilityAttribute(VD); 11844 11845 // FIXME: Warn on unused var template partial specializations. 11846 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11847 MarkUnusedFileScopedDecl(VD); 11848 11849 // Now we have parsed the initializer and can update the table of magic 11850 // tag values. 11851 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11852 !VD->getType()->isIntegralOrEnumerationType()) 11853 return; 11854 11855 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11856 const Expr *MagicValueExpr = VD->getInit(); 11857 if (!MagicValueExpr) { 11858 continue; 11859 } 11860 llvm::APSInt MagicValueInt; 11861 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11862 Diag(I->getRange().getBegin(), 11863 diag::err_type_tag_for_datatype_not_ice) 11864 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11865 continue; 11866 } 11867 if (MagicValueInt.getActiveBits() > 64) { 11868 Diag(I->getRange().getBegin(), 11869 diag::err_type_tag_for_datatype_too_large) 11870 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11871 continue; 11872 } 11873 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11874 RegisterTypeTagForDatatype(I->getArgumentKind(), 11875 MagicValue, 11876 I->getMatchingCType(), 11877 I->getLayoutCompatible(), 11878 I->getMustBeNull()); 11879 } 11880 } 11881 11882 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11883 auto *VD = dyn_cast<VarDecl>(DD); 11884 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11885 } 11886 11887 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11888 ArrayRef<Decl *> Group) { 11889 SmallVector<Decl*, 8> Decls; 11890 11891 if (DS.isTypeSpecOwned()) 11892 Decls.push_back(DS.getRepAsDecl()); 11893 11894 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11895 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11896 bool DiagnosedMultipleDecomps = false; 11897 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11898 bool DiagnosedNonDeducedAuto = false; 11899 11900 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11901 if (Decl *D = Group[i]) { 11902 // For declarators, there are some additional syntactic-ish checks we need 11903 // to perform. 11904 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11905 if (!FirstDeclaratorInGroup) 11906 FirstDeclaratorInGroup = DD; 11907 if (!FirstDecompDeclaratorInGroup) 11908 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11909 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11910 !hasDeducedAuto(DD)) 11911 FirstNonDeducedAutoInGroup = DD; 11912 11913 if (FirstDeclaratorInGroup != DD) { 11914 // A decomposition declaration cannot be combined with any other 11915 // declaration in the same group. 11916 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11917 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11918 diag::err_decomp_decl_not_alone) 11919 << FirstDeclaratorInGroup->getSourceRange() 11920 << DD->getSourceRange(); 11921 DiagnosedMultipleDecomps = true; 11922 } 11923 11924 // A declarator that uses 'auto' in any way other than to declare a 11925 // variable with a deduced type cannot be combined with any other 11926 // declarator in the same group. 11927 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11928 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11929 diag::err_auto_non_deduced_not_alone) 11930 << FirstNonDeducedAutoInGroup->getType() 11931 ->hasAutoForTrailingReturnType() 11932 << FirstDeclaratorInGroup->getSourceRange() 11933 << DD->getSourceRange(); 11934 DiagnosedNonDeducedAuto = true; 11935 } 11936 } 11937 } 11938 11939 Decls.push_back(D); 11940 } 11941 } 11942 11943 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11944 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11945 handleTagNumbering(Tag, S); 11946 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11947 getLangOpts().CPlusPlus) 11948 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11949 } 11950 } 11951 11952 return BuildDeclaratorGroup(Decls); 11953 } 11954 11955 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11956 /// group, performing any necessary semantic checking. 11957 Sema::DeclGroupPtrTy 11958 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11959 // C++14 [dcl.spec.auto]p7: (DR1347) 11960 // If the type that replaces the placeholder type is not the same in each 11961 // deduction, the program is ill-formed. 11962 if (Group.size() > 1) { 11963 QualType Deduced; 11964 VarDecl *DeducedDecl = nullptr; 11965 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11966 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11967 if (!D || D->isInvalidDecl()) 11968 break; 11969 DeducedType *DT = D->getType()->getContainedDeducedType(); 11970 if (!DT || DT->getDeducedType().isNull()) 11971 continue; 11972 if (Deduced.isNull()) { 11973 Deduced = DT->getDeducedType(); 11974 DeducedDecl = D; 11975 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11976 auto *AT = dyn_cast<AutoType>(DT); 11977 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11978 diag::err_auto_different_deductions) 11979 << (AT ? (unsigned)AT->getKeyword() : 3) 11980 << Deduced << DeducedDecl->getDeclName() 11981 << DT->getDeducedType() << D->getDeclName() 11982 << DeducedDecl->getInit()->getSourceRange() 11983 << D->getInit()->getSourceRange(); 11984 D->setInvalidDecl(); 11985 break; 11986 } 11987 } 11988 } 11989 11990 ActOnDocumentableDecls(Group); 11991 11992 return DeclGroupPtrTy::make( 11993 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11994 } 11995 11996 void Sema::ActOnDocumentableDecl(Decl *D) { 11997 ActOnDocumentableDecls(D); 11998 } 11999 12000 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 12001 // Don't parse the comment if Doxygen diagnostics are ignored. 12002 if (Group.empty() || !Group[0]) 12003 return; 12004 12005 if (Diags.isIgnored(diag::warn_doc_param_not_found, 12006 Group[0]->getLocation()) && 12007 Diags.isIgnored(diag::warn_unknown_comment_command_name, 12008 Group[0]->getLocation())) 12009 return; 12010 12011 if (Group.size() >= 2) { 12012 // This is a decl group. Normally it will contain only declarations 12013 // produced from declarator list. But in case we have any definitions or 12014 // additional declaration references: 12015 // 'typedef struct S {} S;' 12016 // 'typedef struct S *S;' 12017 // 'struct S *pS;' 12018 // FinalizeDeclaratorGroup adds these as separate declarations. 12019 Decl *MaybeTagDecl = Group[0]; 12020 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 12021 Group = Group.slice(1); 12022 } 12023 } 12024 12025 // See if there are any new comments that are not attached to a decl. 12026 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 12027 if (!Comments.empty() && 12028 !Comments.back()->isAttached()) { 12029 // There is at least one comment that not attached to a decl. 12030 // Maybe it should be attached to one of these decls? 12031 // 12032 // Note that this way we pick up not only comments that precede the 12033 // declaration, but also comments that *follow* the declaration -- thanks to 12034 // the lookahead in the lexer: we've consumed the semicolon and looked 12035 // ahead through comments. 12036 for (unsigned i = 0, e = Group.size(); i != e; ++i) 12037 Context.getCommentForDecl(Group[i], &PP); 12038 } 12039 } 12040 12041 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 12042 /// to introduce parameters into function prototype scope. 12043 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 12044 const DeclSpec &DS = D.getDeclSpec(); 12045 12046 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 12047 12048 // C++03 [dcl.stc]p2 also permits 'auto'. 12049 StorageClass SC = SC_None; 12050 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 12051 SC = SC_Register; 12052 // In C++11, the 'register' storage class specifier is deprecated. 12053 // In C++17, it is not allowed, but we tolerate it as an extension. 12054 if (getLangOpts().CPlusPlus11) { 12055 Diag(DS.getStorageClassSpecLoc(), 12056 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 12057 : diag::warn_deprecated_register) 12058 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12059 } 12060 } else if (getLangOpts().CPlusPlus && 12061 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 12062 SC = SC_Auto; 12063 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 12064 Diag(DS.getStorageClassSpecLoc(), 12065 diag::err_invalid_storage_class_in_func_decl); 12066 D.getMutableDeclSpec().ClearStorageClassSpecs(); 12067 } 12068 12069 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12070 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12071 << DeclSpec::getSpecifierName(TSCS); 12072 if (DS.isInlineSpecified()) 12073 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12074 << getLangOpts().CPlusPlus17; 12075 if (DS.isConstexprSpecified()) 12076 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12077 << 0; 12078 12079 DiagnoseFunctionSpecifiers(DS); 12080 12081 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12082 QualType parmDeclType = TInfo->getType(); 12083 12084 if (getLangOpts().CPlusPlus) { 12085 // Check that there are no default arguments inside the type of this 12086 // parameter. 12087 CheckExtraCXXDefaultArguments(D); 12088 12089 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12090 if (D.getCXXScopeSpec().isSet()) { 12091 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12092 << D.getCXXScopeSpec().getRange(); 12093 D.getCXXScopeSpec().clear(); 12094 } 12095 } 12096 12097 // Ensure we have a valid name 12098 IdentifierInfo *II = nullptr; 12099 if (D.hasName()) { 12100 II = D.getIdentifier(); 12101 if (!II) { 12102 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12103 << GetNameForDeclarator(D).getName(); 12104 D.setInvalidType(true); 12105 } 12106 } 12107 12108 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12109 if (II) { 12110 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12111 ForVisibleRedeclaration); 12112 LookupName(R, S); 12113 if (R.isSingleResult()) { 12114 NamedDecl *PrevDecl = R.getFoundDecl(); 12115 if (PrevDecl->isTemplateParameter()) { 12116 // Maybe we will complain about the shadowed template parameter. 12117 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12118 // Just pretend that we didn't see the previous declaration. 12119 PrevDecl = nullptr; 12120 } else if (S->isDeclScope(PrevDecl)) { 12121 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12122 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12123 12124 // Recover by removing the name 12125 II = nullptr; 12126 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12127 D.setInvalidType(true); 12128 } 12129 } 12130 } 12131 12132 // Temporarily put parameter variables in the translation unit, not 12133 // the enclosing context. This prevents them from accidentally 12134 // looking like class members in C++. 12135 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 12136 D.getLocStart(), 12137 D.getIdentifierLoc(), II, 12138 parmDeclType, TInfo, 12139 SC); 12140 12141 if (D.isInvalidType()) 12142 New->setInvalidDecl(); 12143 12144 assert(S->isFunctionPrototypeScope()); 12145 assert(S->getFunctionPrototypeDepth() >= 1); 12146 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12147 S->getNextFunctionPrototypeIndex()); 12148 12149 // Add the parameter declaration into this scope. 12150 S->AddDecl(New); 12151 if (II) 12152 IdResolver.AddDecl(New); 12153 12154 ProcessDeclAttributes(S, New, D); 12155 12156 if (D.getDeclSpec().isModulePrivateSpecified()) 12157 Diag(New->getLocation(), diag::err_module_private_local) 12158 << 1 << New->getDeclName() 12159 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12160 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12161 12162 if (New->hasAttr<BlocksAttr>()) { 12163 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12164 } 12165 return New; 12166 } 12167 12168 /// Synthesizes a variable for a parameter arising from a 12169 /// typedef. 12170 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12171 SourceLocation Loc, 12172 QualType T) { 12173 /* FIXME: setting StartLoc == Loc. 12174 Would it be worth to modify callers so as to provide proper source 12175 location for the unnamed parameters, embedding the parameter's type? */ 12176 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12177 T, Context.getTrivialTypeSourceInfo(T, Loc), 12178 SC_None, nullptr); 12179 Param->setImplicit(); 12180 return Param; 12181 } 12182 12183 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12184 // Don't diagnose unused-parameter errors in template instantiations; we 12185 // will already have done so in the template itself. 12186 if (inTemplateInstantiation()) 12187 return; 12188 12189 for (const ParmVarDecl *Parameter : Parameters) { 12190 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12191 !Parameter->hasAttr<UnusedAttr>()) { 12192 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12193 << Parameter->getDeclName(); 12194 } 12195 } 12196 } 12197 12198 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12199 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12200 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12201 return; 12202 12203 // Warn if the return value is pass-by-value and larger than the specified 12204 // threshold. 12205 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12206 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12207 if (Size > LangOpts.NumLargeByValueCopy) 12208 Diag(D->getLocation(), diag::warn_return_value_size) 12209 << D->getDeclName() << Size; 12210 } 12211 12212 // Warn if any parameter is pass-by-value and larger than the specified 12213 // threshold. 12214 for (const ParmVarDecl *Parameter : Parameters) { 12215 QualType T = Parameter->getType(); 12216 if (T->isDependentType() || !T.isPODType(Context)) 12217 continue; 12218 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12219 if (Size > LangOpts.NumLargeByValueCopy) 12220 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12221 << Parameter->getDeclName() << Size; 12222 } 12223 } 12224 12225 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12226 SourceLocation NameLoc, IdentifierInfo *Name, 12227 QualType T, TypeSourceInfo *TSInfo, 12228 StorageClass SC) { 12229 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12230 if (getLangOpts().ObjCAutoRefCount && 12231 T.getObjCLifetime() == Qualifiers::OCL_None && 12232 T->isObjCLifetimeType()) { 12233 12234 Qualifiers::ObjCLifetime lifetime; 12235 12236 // Special cases for arrays: 12237 // - if it's const, use __unsafe_unretained 12238 // - otherwise, it's an error 12239 if (T->isArrayType()) { 12240 if (!T.isConstQualified()) { 12241 DelayedDiagnostics.add( 12242 sema::DelayedDiagnostic::makeForbiddenType( 12243 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12244 } 12245 lifetime = Qualifiers::OCL_ExplicitNone; 12246 } else { 12247 lifetime = T->getObjCARCImplicitLifetime(); 12248 } 12249 T = Context.getLifetimeQualifiedType(T, lifetime); 12250 } 12251 12252 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12253 Context.getAdjustedParameterType(T), 12254 TSInfo, SC, nullptr); 12255 12256 // Parameters can not be abstract class types. 12257 // For record types, this is done by the AbstractClassUsageDiagnoser once 12258 // the class has been completely parsed. 12259 if (!CurContext->isRecord() && 12260 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12261 AbstractParamType)) 12262 New->setInvalidDecl(); 12263 12264 // Parameter declarators cannot be interface types. All ObjC objects are 12265 // passed by reference. 12266 if (T->isObjCObjectType()) { 12267 SourceLocation TypeEndLoc = 12268 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 12269 Diag(NameLoc, 12270 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12271 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12272 T = Context.getObjCObjectPointerType(T); 12273 New->setType(T); 12274 } 12275 12276 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12277 // duration shall not be qualified by an address-space qualifier." 12278 // Since all parameters have automatic store duration, they can not have 12279 // an address space. 12280 if (T.getAddressSpace() != LangAS::Default && 12281 // OpenCL allows function arguments declared to be an array of a type 12282 // to be qualified with an address space. 12283 !(getLangOpts().OpenCL && 12284 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12285 Diag(NameLoc, diag::err_arg_with_address_space); 12286 New->setInvalidDecl(); 12287 } 12288 12289 return New; 12290 } 12291 12292 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12293 SourceLocation LocAfterDecls) { 12294 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12295 12296 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12297 // for a K&R function. 12298 if (!FTI.hasPrototype) { 12299 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12300 --i; 12301 if (FTI.Params[i].Param == nullptr) { 12302 SmallString<256> Code; 12303 llvm::raw_svector_ostream(Code) 12304 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12305 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12306 << FTI.Params[i].Ident 12307 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12308 12309 // Implicitly declare the argument as type 'int' for lack of a better 12310 // type. 12311 AttributeFactory attrs; 12312 DeclSpec DS(attrs); 12313 const char* PrevSpec; // unused 12314 unsigned DiagID; // unused 12315 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12316 DiagID, Context.getPrintingPolicy()); 12317 // Use the identifier location for the type source range. 12318 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12319 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12320 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12321 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12322 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12323 } 12324 } 12325 } 12326 } 12327 12328 Decl * 12329 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12330 MultiTemplateParamsArg TemplateParameterLists, 12331 SkipBodyInfo *SkipBody) { 12332 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12333 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12334 Scope *ParentScope = FnBodyScope->getParent(); 12335 12336 D.setFunctionDefinitionKind(FDK_Definition); 12337 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12338 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12339 } 12340 12341 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12342 Consumer.HandleInlineFunctionDefinition(D); 12343 } 12344 12345 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12346 const FunctionDecl*& PossibleZeroParamPrototype) { 12347 // Don't warn about invalid declarations. 12348 if (FD->isInvalidDecl()) 12349 return false; 12350 12351 // Or declarations that aren't global. 12352 if (!FD->isGlobal()) 12353 return false; 12354 12355 // Don't warn about C++ member functions. 12356 if (isa<CXXMethodDecl>(FD)) 12357 return false; 12358 12359 // Don't warn about 'main'. 12360 if (FD->isMain()) 12361 return false; 12362 12363 // Don't warn about inline functions. 12364 if (FD->isInlined()) 12365 return false; 12366 12367 // Don't warn about function templates. 12368 if (FD->getDescribedFunctionTemplate()) 12369 return false; 12370 12371 // Don't warn about function template specializations. 12372 if (FD->isFunctionTemplateSpecialization()) 12373 return false; 12374 12375 // Don't warn for OpenCL kernels. 12376 if (FD->hasAttr<OpenCLKernelAttr>()) 12377 return false; 12378 12379 // Don't warn on explicitly deleted functions. 12380 if (FD->isDeleted()) 12381 return false; 12382 12383 bool MissingPrototype = true; 12384 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12385 Prev; Prev = Prev->getPreviousDecl()) { 12386 // Ignore any declarations that occur in function or method 12387 // scope, because they aren't visible from the header. 12388 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12389 continue; 12390 12391 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12392 if (FD->getNumParams() == 0) 12393 PossibleZeroParamPrototype = Prev; 12394 break; 12395 } 12396 12397 return MissingPrototype; 12398 } 12399 12400 void 12401 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12402 const FunctionDecl *EffectiveDefinition, 12403 SkipBodyInfo *SkipBody) { 12404 const FunctionDecl *Definition = EffectiveDefinition; 12405 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12406 // If this is a friend function defined in a class template, it does not 12407 // have a body until it is used, nevertheless it is a definition, see 12408 // [temp.inst]p2: 12409 // 12410 // ... for the purpose of determining whether an instantiated redeclaration 12411 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12412 // corresponds to a definition in the template is considered to be a 12413 // definition. 12414 // 12415 // The following code must produce redefinition error: 12416 // 12417 // template<typename T> struct C20 { friend void func_20() {} }; 12418 // C20<int> c20i; 12419 // void func_20() {} 12420 // 12421 for (auto I : FD->redecls()) { 12422 if (I != FD && !I->isInvalidDecl() && 12423 I->getFriendObjectKind() != Decl::FOK_None) { 12424 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12425 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12426 // A merged copy of the same function, instantiated as a member of 12427 // the same class, is OK. 12428 if (declaresSameEntity(OrigFD, Original) && 12429 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12430 cast<Decl>(FD->getLexicalDeclContext()))) 12431 continue; 12432 } 12433 12434 if (Original->isThisDeclarationADefinition()) { 12435 Definition = I; 12436 break; 12437 } 12438 } 12439 } 12440 } 12441 } 12442 if (!Definition) 12443 return; 12444 12445 if (canRedefineFunction(Definition, getLangOpts())) 12446 return; 12447 12448 // Don't emit an error when this is redefinition of a typo-corrected 12449 // definition. 12450 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12451 return; 12452 12453 // If we don't have a visible definition of the function, and it's inline or 12454 // a template, skip the new definition. 12455 if (SkipBody && !hasVisibleDefinition(Definition) && 12456 (Definition->getFormalLinkage() == InternalLinkage || 12457 Definition->isInlined() || 12458 Definition->getDescribedFunctionTemplate() || 12459 Definition->getNumTemplateParameterLists())) { 12460 SkipBody->ShouldSkip = true; 12461 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12462 makeMergedDefinitionVisible(TD); 12463 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12464 return; 12465 } 12466 12467 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12468 Definition->getStorageClass() == SC_Extern) 12469 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12470 << FD->getDeclName() << getLangOpts().CPlusPlus; 12471 else 12472 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12473 12474 Diag(Definition->getLocation(), diag::note_previous_definition); 12475 FD->setInvalidDecl(); 12476 } 12477 12478 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12479 Sema &S) { 12480 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12481 12482 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12483 LSI->CallOperator = CallOperator; 12484 LSI->Lambda = LambdaClass; 12485 LSI->ReturnType = CallOperator->getReturnType(); 12486 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12487 12488 if (LCD == LCD_None) 12489 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12490 else if (LCD == LCD_ByCopy) 12491 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12492 else if (LCD == LCD_ByRef) 12493 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12494 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12495 12496 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12497 LSI->Mutable = !CallOperator->isConst(); 12498 12499 // Add the captures to the LSI so they can be noted as already 12500 // captured within tryCaptureVar. 12501 auto I = LambdaClass->field_begin(); 12502 for (const auto &C : LambdaClass->captures()) { 12503 if (C.capturesVariable()) { 12504 VarDecl *VD = C.getCapturedVar(); 12505 if (VD->isInitCapture()) 12506 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12507 QualType CaptureType = VD->getType(); 12508 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12509 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12510 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12511 /*EllipsisLoc*/C.isPackExpansion() 12512 ? C.getEllipsisLoc() : SourceLocation(), 12513 CaptureType, /*Expr*/ nullptr); 12514 12515 } else if (C.capturesThis()) { 12516 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12517 /*Expr*/ nullptr, 12518 C.getCaptureKind() == LCK_StarThis); 12519 } else { 12520 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12521 } 12522 ++I; 12523 } 12524 } 12525 12526 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12527 SkipBodyInfo *SkipBody) { 12528 if (!D) { 12529 // Parsing the function declaration failed in some way. Push on a fake scope 12530 // anyway so we can try to parse the function body. 12531 PushFunctionScope(); 12532 return D; 12533 } 12534 12535 FunctionDecl *FD = nullptr; 12536 12537 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12538 FD = FunTmpl->getTemplatedDecl(); 12539 else 12540 FD = cast<FunctionDecl>(D); 12541 12542 // Check for defining attributes before the check for redefinition. 12543 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12544 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12545 FD->dropAttr<AliasAttr>(); 12546 FD->setInvalidDecl(); 12547 } 12548 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12549 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12550 FD->dropAttr<IFuncAttr>(); 12551 FD->setInvalidDecl(); 12552 } 12553 12554 // See if this is a redefinition. If 'will have body' is already set, then 12555 // these checks were already performed when it was set. 12556 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12557 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12558 12559 // If we're skipping the body, we're done. Don't enter the scope. 12560 if (SkipBody && SkipBody->ShouldSkip) 12561 return D; 12562 } 12563 12564 // Mark this function as "will have a body eventually". This lets users to 12565 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12566 // this function. 12567 FD->setWillHaveBody(); 12568 12569 // If we are instantiating a generic lambda call operator, push 12570 // a LambdaScopeInfo onto the function stack. But use the information 12571 // that's already been calculated (ActOnLambdaExpr) to prime the current 12572 // LambdaScopeInfo. 12573 // When the template operator is being specialized, the LambdaScopeInfo, 12574 // has to be properly restored so that tryCaptureVariable doesn't try 12575 // and capture any new variables. In addition when calculating potential 12576 // captures during transformation of nested lambdas, it is necessary to 12577 // have the LSI properly restored. 12578 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12579 assert(inTemplateInstantiation() && 12580 "There should be an active template instantiation on the stack " 12581 "when instantiating a generic lambda!"); 12582 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12583 } else { 12584 // Enter a new function scope 12585 PushFunctionScope(); 12586 } 12587 12588 // Builtin functions cannot be defined. 12589 if (unsigned BuiltinID = FD->getBuiltinID()) { 12590 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12591 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12592 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12593 FD->setInvalidDecl(); 12594 } 12595 } 12596 12597 // The return type of a function definition must be complete 12598 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12599 QualType ResultType = FD->getReturnType(); 12600 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12601 !FD->isInvalidDecl() && 12602 RequireCompleteType(FD->getLocation(), ResultType, 12603 diag::err_func_def_incomplete_result)) 12604 FD->setInvalidDecl(); 12605 12606 if (FnBodyScope) 12607 PushDeclContext(FnBodyScope, FD); 12608 12609 // Check the validity of our function parameters 12610 CheckParmsForFunctionDef(FD->parameters(), 12611 /*CheckParameterNames=*/true); 12612 12613 // Add non-parameter declarations already in the function to the current 12614 // scope. 12615 if (FnBodyScope) { 12616 for (Decl *NPD : FD->decls()) { 12617 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12618 if (!NonParmDecl) 12619 continue; 12620 assert(!isa<ParmVarDecl>(NonParmDecl) && 12621 "parameters should not be in newly created FD yet"); 12622 12623 // If the decl has a name, make it accessible in the current scope. 12624 if (NonParmDecl->getDeclName()) 12625 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12626 12627 // Similarly, dive into enums and fish their constants out, making them 12628 // accessible in this scope. 12629 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12630 for (auto *EI : ED->enumerators()) 12631 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12632 } 12633 } 12634 } 12635 12636 // Introduce our parameters into the function scope 12637 for (auto Param : FD->parameters()) { 12638 Param->setOwningFunction(FD); 12639 12640 // If this has an identifier, add it to the scope stack. 12641 if (Param->getIdentifier() && FnBodyScope) { 12642 CheckShadow(FnBodyScope, Param); 12643 12644 PushOnScopeChains(Param, FnBodyScope); 12645 } 12646 } 12647 12648 // Ensure that the function's exception specification is instantiated. 12649 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12650 ResolveExceptionSpec(D->getLocation(), FPT); 12651 12652 // dllimport cannot be applied to non-inline function definitions. 12653 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12654 !FD->isTemplateInstantiation()) { 12655 assert(!FD->hasAttr<DLLExportAttr>()); 12656 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12657 FD->setInvalidDecl(); 12658 return D; 12659 } 12660 // We want to attach documentation to original Decl (which might be 12661 // a function template). 12662 ActOnDocumentableDecl(D); 12663 if (getCurLexicalContext()->isObjCContainer() && 12664 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12665 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12666 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12667 12668 return D; 12669 } 12670 12671 /// Given the set of return statements within a function body, 12672 /// compute the variables that are subject to the named return value 12673 /// optimization. 12674 /// 12675 /// Each of the variables that is subject to the named return value 12676 /// optimization will be marked as NRVO variables in the AST, and any 12677 /// return statement that has a marked NRVO variable as its NRVO candidate can 12678 /// use the named return value optimization. 12679 /// 12680 /// This function applies a very simplistic algorithm for NRVO: if every return 12681 /// statement in the scope of a variable has the same NRVO candidate, that 12682 /// candidate is an NRVO variable. 12683 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12684 ReturnStmt **Returns = Scope->Returns.data(); 12685 12686 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12687 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12688 if (!NRVOCandidate->isNRVOVariable()) 12689 Returns[I]->setNRVOCandidate(nullptr); 12690 } 12691 } 12692 } 12693 12694 bool Sema::canDelayFunctionBody(const Declarator &D) { 12695 // We can't delay parsing the body of a constexpr function template (yet). 12696 if (D.getDeclSpec().isConstexprSpecified()) 12697 return false; 12698 12699 // We can't delay parsing the body of a function template with a deduced 12700 // return type (yet). 12701 if (D.getDeclSpec().hasAutoTypeSpec()) { 12702 // If the placeholder introduces a non-deduced trailing return type, 12703 // we can still delay parsing it. 12704 if (D.getNumTypeObjects()) { 12705 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12706 if (Outer.Kind == DeclaratorChunk::Function && 12707 Outer.Fun.hasTrailingReturnType()) { 12708 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12709 return Ty.isNull() || !Ty->isUndeducedType(); 12710 } 12711 } 12712 return false; 12713 } 12714 12715 return true; 12716 } 12717 12718 bool Sema::canSkipFunctionBody(Decl *D) { 12719 // We cannot skip the body of a function (or function template) which is 12720 // constexpr, since we may need to evaluate its body in order to parse the 12721 // rest of the file. 12722 // We cannot skip the body of a function with an undeduced return type, 12723 // because any callers of that function need to know the type. 12724 if (const FunctionDecl *FD = D->getAsFunction()) 12725 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12726 return false; 12727 return Consumer.shouldSkipFunctionBody(D); 12728 } 12729 12730 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12731 if (!Decl) 12732 return nullptr; 12733 if (FunctionDecl *FD = Decl->getAsFunction()) 12734 FD->setHasSkippedBody(); 12735 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 12736 MD->setHasSkippedBody(); 12737 return Decl; 12738 } 12739 12740 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12741 return ActOnFinishFunctionBody(D, BodyArg, false); 12742 } 12743 12744 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12745 bool IsInstantiation) { 12746 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12747 12748 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12749 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12750 12751 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12752 CheckCompletedCoroutineBody(FD, Body); 12753 12754 if (FD) { 12755 FD->setBody(Body); 12756 FD->setWillHaveBody(false); 12757 12758 if (getLangOpts().CPlusPlus14) { 12759 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12760 FD->getReturnType()->isUndeducedType()) { 12761 // If the function has a deduced result type but contains no 'return' 12762 // statements, the result type as written must be exactly 'auto', and 12763 // the deduced result type is 'void'. 12764 if (!FD->getReturnType()->getAs<AutoType>()) { 12765 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12766 << FD->getReturnType(); 12767 FD->setInvalidDecl(); 12768 } else { 12769 // Substitute 'void' for the 'auto' in the type. 12770 TypeLoc ResultType = getReturnTypeLoc(FD); 12771 Context.adjustDeducedFunctionResultType( 12772 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12773 } 12774 } 12775 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12776 // In C++11, we don't use 'auto' deduction rules for lambda call 12777 // operators because we don't support return type deduction. 12778 auto *LSI = getCurLambda(); 12779 if (LSI->HasImplicitReturnType) { 12780 deduceClosureReturnType(*LSI); 12781 12782 // C++11 [expr.prim.lambda]p4: 12783 // [...] if there are no return statements in the compound-statement 12784 // [the deduced type is] the type void 12785 QualType RetType = 12786 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12787 12788 // Update the return type to the deduced type. 12789 const FunctionProtoType *Proto = 12790 FD->getType()->getAs<FunctionProtoType>(); 12791 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12792 Proto->getExtProtoInfo())); 12793 } 12794 } 12795 12796 // If the function implicitly returns zero (like 'main') or is naked, 12797 // don't complain about missing return statements. 12798 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12799 WP.disableCheckFallThrough(); 12800 12801 // MSVC permits the use of pure specifier (=0) on function definition, 12802 // defined at class scope, warn about this non-standard construct. 12803 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12804 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12805 12806 if (!FD->isInvalidDecl()) { 12807 // Don't diagnose unused parameters of defaulted or deleted functions. 12808 if (!FD->isDeleted() && !FD->isDefaulted()) 12809 DiagnoseUnusedParameters(FD->parameters()); 12810 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12811 FD->getReturnType(), FD); 12812 12813 // If this is a structor, we need a vtable. 12814 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12815 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12816 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12817 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12818 12819 // Try to apply the named return value optimization. We have to check 12820 // if we can do this here because lambdas keep return statements around 12821 // to deduce an implicit return type. 12822 if (FD->getReturnType()->isRecordType() && 12823 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 12824 computeNRVO(Body, getCurFunction()); 12825 } 12826 12827 // GNU warning -Wmissing-prototypes: 12828 // Warn if a global function is defined without a previous 12829 // prototype declaration. This warning is issued even if the 12830 // definition itself provides a prototype. The aim is to detect 12831 // global functions that fail to be declared in header files. 12832 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12833 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12834 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12835 12836 if (PossibleZeroParamPrototype) { 12837 // We found a declaration that is not a prototype, 12838 // but that could be a zero-parameter prototype 12839 if (TypeSourceInfo *TI = 12840 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12841 TypeLoc TL = TI->getTypeLoc(); 12842 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12843 Diag(PossibleZeroParamPrototype->getLocation(), 12844 diag::note_declaration_not_a_prototype) 12845 << PossibleZeroParamPrototype 12846 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12847 } 12848 } 12849 12850 // GNU warning -Wstrict-prototypes 12851 // Warn if K&R function is defined without a previous declaration. 12852 // This warning is issued only if the definition itself does not provide 12853 // a prototype. Only K&R definitions do not provide a prototype. 12854 // An empty list in a function declarator that is part of a definition 12855 // of that function specifies that the function has no parameters 12856 // (C99 6.7.5.3p14) 12857 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12858 !LangOpts.CPlusPlus) { 12859 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12860 TypeLoc TL = TI->getTypeLoc(); 12861 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12862 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12863 } 12864 } 12865 12866 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12867 const CXXMethodDecl *KeyFunction; 12868 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12869 MD->isVirtual() && 12870 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12871 MD == KeyFunction->getCanonicalDecl()) { 12872 // Update the key-function state if necessary for this ABI. 12873 if (FD->isInlined() && 12874 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12875 Context.setNonKeyFunction(MD); 12876 12877 // If the newly-chosen key function is already defined, then we 12878 // need to mark the vtable as used retroactively. 12879 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12880 const FunctionDecl *Definition; 12881 if (KeyFunction && KeyFunction->isDefined(Definition)) 12882 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12883 } else { 12884 // We just defined they key function; mark the vtable as used. 12885 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12886 } 12887 } 12888 } 12889 12890 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12891 "Function parsing confused"); 12892 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12893 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12894 MD->setBody(Body); 12895 if (!MD->isInvalidDecl()) { 12896 DiagnoseUnusedParameters(MD->parameters()); 12897 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12898 MD->getReturnType(), MD); 12899 12900 if (Body) 12901 computeNRVO(Body, getCurFunction()); 12902 } 12903 if (getCurFunction()->ObjCShouldCallSuper) { 12904 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12905 << MD->getSelector().getAsString(); 12906 getCurFunction()->ObjCShouldCallSuper = false; 12907 } 12908 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12909 const ObjCMethodDecl *InitMethod = nullptr; 12910 bool isDesignated = 12911 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12912 assert(isDesignated && InitMethod); 12913 (void)isDesignated; 12914 12915 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12916 auto IFace = MD->getClassInterface(); 12917 if (!IFace) 12918 return false; 12919 auto SuperD = IFace->getSuperClass(); 12920 if (!SuperD) 12921 return false; 12922 return SuperD->getIdentifier() == 12923 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12924 }; 12925 // Don't issue this warning for unavailable inits or direct subclasses 12926 // of NSObject. 12927 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12928 Diag(MD->getLocation(), 12929 diag::warn_objc_designated_init_missing_super_call); 12930 Diag(InitMethod->getLocation(), 12931 diag::note_objc_designated_init_marked_here); 12932 } 12933 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12934 } 12935 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12936 // Don't issue this warning for unavaialable inits. 12937 if (!MD->isUnavailable()) 12938 Diag(MD->getLocation(), 12939 diag::warn_objc_secondary_init_missing_init_call); 12940 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12941 } 12942 } else { 12943 // Parsing the function declaration failed in some way. Pop the fake scope 12944 // we pushed on. 12945 PopFunctionScopeInfo(ActivePolicy, dcl); 12946 return nullptr; 12947 } 12948 12949 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12950 DiagnoseUnguardedAvailabilityViolations(dcl); 12951 12952 assert(!getCurFunction()->ObjCShouldCallSuper && 12953 "This should only be set for ObjC methods, which should have been " 12954 "handled in the block above."); 12955 12956 // Verify and clean out per-function state. 12957 if (Body && (!FD || !FD->isDefaulted())) { 12958 // C++ constructors that have function-try-blocks can't have return 12959 // statements in the handlers of that block. (C++ [except.handle]p14) 12960 // Verify this. 12961 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12962 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12963 12964 // Verify that gotos and switch cases don't jump into scopes illegally. 12965 if (getCurFunction()->NeedsScopeChecking() && 12966 !PP.isCodeCompletionEnabled()) 12967 DiagnoseInvalidJumps(Body); 12968 12969 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12970 if (!Destructor->getParent()->isDependentType()) 12971 CheckDestructor(Destructor); 12972 12973 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12974 Destructor->getParent()); 12975 } 12976 12977 // If any errors have occurred, clear out any temporaries that may have 12978 // been leftover. This ensures that these temporaries won't be picked up for 12979 // deletion in some later function. 12980 if (getDiagnostics().hasErrorOccurred() || 12981 getDiagnostics().getSuppressAllDiagnostics()) { 12982 DiscardCleanupsInEvaluationContext(); 12983 } 12984 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12985 !isa<FunctionTemplateDecl>(dcl)) { 12986 // Since the body is valid, issue any analysis-based warnings that are 12987 // enabled. 12988 ActivePolicy = &WP; 12989 } 12990 12991 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12992 (!CheckConstexprFunctionDecl(FD) || 12993 !CheckConstexprFunctionBody(FD, Body))) 12994 FD->setInvalidDecl(); 12995 12996 if (FD && FD->hasAttr<NakedAttr>()) { 12997 for (const Stmt *S : Body->children()) { 12998 // Allow local register variables without initializer as they don't 12999 // require prologue. 13000 bool RegisterVariables = false; 13001 if (auto *DS = dyn_cast<DeclStmt>(S)) { 13002 for (const auto *Decl : DS->decls()) { 13003 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 13004 RegisterVariables = 13005 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 13006 if (!RegisterVariables) 13007 break; 13008 } 13009 } 13010 } 13011 if (RegisterVariables) 13012 continue; 13013 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 13014 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 13015 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 13016 FD->setInvalidDecl(); 13017 break; 13018 } 13019 } 13020 } 13021 13022 assert(ExprCleanupObjects.size() == 13023 ExprEvalContexts.back().NumCleanupObjects && 13024 "Leftover temporaries in function"); 13025 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 13026 assert(MaybeODRUseExprs.empty() && 13027 "Leftover expressions for odr-use checking"); 13028 } 13029 13030 if (!IsInstantiation) 13031 PopDeclContext(); 13032 13033 PopFunctionScopeInfo(ActivePolicy, dcl); 13034 // If any errors have occurred, clear out any temporaries that may have 13035 // been leftover. This ensures that these temporaries won't be picked up for 13036 // deletion in some later function. 13037 if (getDiagnostics().hasErrorOccurred()) { 13038 DiscardCleanupsInEvaluationContext(); 13039 } 13040 13041 return dcl; 13042 } 13043 13044 /// When we finish delayed parsing of an attribute, we must attach it to the 13045 /// relevant Decl. 13046 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 13047 ParsedAttributes &Attrs) { 13048 // Always attach attributes to the underlying decl. 13049 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 13050 D = TD->getTemplatedDecl(); 13051 ProcessDeclAttributeList(S, D, Attrs.getList()); 13052 13053 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 13054 if (Method->isStatic()) 13055 checkThisInStaticMemberFunctionAttributes(Method); 13056 } 13057 13058 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 13059 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 13060 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 13061 IdentifierInfo &II, Scope *S) { 13062 // Find the scope in which the identifier is injected and the corresponding 13063 // DeclContext. 13064 // FIXME: C89 does not say what happens if there is no enclosing block scope. 13065 // In that case, we inject the declaration into the translation unit scope 13066 // instead. 13067 Scope *BlockScope = S; 13068 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 13069 BlockScope = BlockScope->getParent(); 13070 13071 Scope *ContextScope = BlockScope; 13072 while (!ContextScope->getEntity()) 13073 ContextScope = ContextScope->getParent(); 13074 ContextRAII SavedContext(*this, ContextScope->getEntity()); 13075 13076 // Before we produce a declaration for an implicitly defined 13077 // function, see whether there was a locally-scoped declaration of 13078 // this name as a function or variable. If so, use that 13079 // (non-visible) declaration, and complain about it. 13080 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 13081 if (ExternCPrev) { 13082 // We still need to inject the function into the enclosing block scope so 13083 // that later (non-call) uses can see it. 13084 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13085 13086 // C89 footnote 38: 13087 // If in fact it is not defined as having type "function returning int", 13088 // the behavior is undefined. 13089 if (!isa<FunctionDecl>(ExternCPrev) || 13090 !Context.typesAreCompatible( 13091 cast<FunctionDecl>(ExternCPrev)->getType(), 13092 Context.getFunctionNoProtoType(Context.IntTy))) { 13093 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13094 << ExternCPrev << !getLangOpts().C99; 13095 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13096 return ExternCPrev; 13097 } 13098 } 13099 13100 // Extension in C99. Legal in C90, but warn about it. 13101 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13102 unsigned diag_id; 13103 if (II.getName().startswith("__builtin_")) 13104 diag_id = diag::warn_builtin_unknown; 13105 else if (getLangOpts().C99 || getLangOpts().OpenCL) 13106 diag_id = diag::ext_implicit_function_decl; 13107 else 13108 diag_id = diag::warn_implicit_function_decl; 13109 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL; 13110 13111 // If we found a prior declaration of this function, don't bother building 13112 // another one. We've already pushed that one into scope, so there's nothing 13113 // more to do. 13114 if (ExternCPrev) 13115 return ExternCPrev; 13116 13117 // Because typo correction is expensive, only do it if the implicit 13118 // function declaration is going to be treated as an error. 13119 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13120 TypoCorrection Corrected; 13121 if (S && 13122 (Corrected = CorrectTypo( 13123 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 13124 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 13125 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13126 /*ErrorRecovery*/false); 13127 } 13128 13129 // Set a Declarator for the implicit definition: int foo(); 13130 const char *Dummy; 13131 AttributeFactory attrFactory; 13132 DeclSpec DS(attrFactory); 13133 unsigned DiagID; 13134 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13135 Context.getPrintingPolicy()); 13136 (void)Error; // Silence warning. 13137 assert(!Error && "Error setting up implicit decl!"); 13138 SourceLocation NoLoc; 13139 Declarator D(DS, DeclaratorContext::BlockContext); 13140 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13141 /*IsAmbiguous=*/false, 13142 /*LParenLoc=*/NoLoc, 13143 /*Params=*/nullptr, 13144 /*NumParams=*/0, 13145 /*EllipsisLoc=*/NoLoc, 13146 /*RParenLoc=*/NoLoc, 13147 /*TypeQuals=*/0, 13148 /*RefQualifierIsLvalueRef=*/true, 13149 /*RefQualifierLoc=*/NoLoc, 13150 /*ConstQualifierLoc=*/NoLoc, 13151 /*VolatileQualifierLoc=*/NoLoc, 13152 /*RestrictQualifierLoc=*/NoLoc, 13153 /*MutableLoc=*/NoLoc, 13154 EST_None, 13155 /*ESpecRange=*/SourceRange(), 13156 /*Exceptions=*/nullptr, 13157 /*ExceptionRanges=*/nullptr, 13158 /*NumExceptions=*/0, 13159 /*NoexceptExpr=*/nullptr, 13160 /*ExceptionSpecTokens=*/nullptr, 13161 /*DeclsInPrototype=*/None, 13162 Loc, Loc, D), 13163 DS.getAttributes(), 13164 SourceLocation()); 13165 D.SetIdentifier(&II, Loc); 13166 13167 // Insert this function into the enclosing block scope. 13168 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13169 FD->setImplicit(); 13170 13171 AddKnownFunctionAttributes(FD); 13172 13173 return FD; 13174 } 13175 13176 /// Adds any function attributes that we know a priori based on 13177 /// the declaration of this function. 13178 /// 13179 /// These attributes can apply both to implicitly-declared builtins 13180 /// (like __builtin___printf_chk) or to library-declared functions 13181 /// like NSLog or printf. 13182 /// 13183 /// We need to check for duplicate attributes both here and where user-written 13184 /// attributes are applied to declarations. 13185 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13186 if (FD->isInvalidDecl()) 13187 return; 13188 13189 // If this is a built-in function, map its builtin attributes to 13190 // actual attributes. 13191 if (unsigned BuiltinID = FD->getBuiltinID()) { 13192 // Handle printf-formatting attributes. 13193 unsigned FormatIdx; 13194 bool HasVAListArg; 13195 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13196 if (!FD->hasAttr<FormatAttr>()) { 13197 const char *fmt = "printf"; 13198 unsigned int NumParams = FD->getNumParams(); 13199 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13200 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13201 fmt = "NSString"; 13202 FD->addAttr(FormatAttr::CreateImplicit(Context, 13203 &Context.Idents.get(fmt), 13204 FormatIdx+1, 13205 HasVAListArg ? 0 : FormatIdx+2, 13206 FD->getLocation())); 13207 } 13208 } 13209 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13210 HasVAListArg)) { 13211 if (!FD->hasAttr<FormatAttr>()) 13212 FD->addAttr(FormatAttr::CreateImplicit(Context, 13213 &Context.Idents.get("scanf"), 13214 FormatIdx+1, 13215 HasVAListArg ? 0 : FormatIdx+2, 13216 FD->getLocation())); 13217 } 13218 13219 // Mark const if we don't care about errno and that is the only thing 13220 // preventing the function from being const. This allows IRgen to use LLVM 13221 // intrinsics for such functions. 13222 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13223 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13224 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13225 13226 // We make "fma" on some platforms const because we know it does not set 13227 // errno in those environments even though it could set errno based on the 13228 // C standard. 13229 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13230 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13231 !FD->hasAttr<ConstAttr>()) { 13232 switch (BuiltinID) { 13233 case Builtin::BI__builtin_fma: 13234 case Builtin::BI__builtin_fmaf: 13235 case Builtin::BI__builtin_fmal: 13236 case Builtin::BIfma: 13237 case Builtin::BIfmaf: 13238 case Builtin::BIfmal: 13239 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13240 break; 13241 default: 13242 break; 13243 } 13244 } 13245 13246 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13247 !FD->hasAttr<ReturnsTwiceAttr>()) 13248 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13249 FD->getLocation())); 13250 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13251 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13252 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13253 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13254 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13255 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13256 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13257 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13258 // Add the appropriate attribute, depending on the CUDA compilation mode 13259 // and which target the builtin belongs to. For example, during host 13260 // compilation, aux builtins are __device__, while the rest are __host__. 13261 if (getLangOpts().CUDAIsDevice != 13262 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13263 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13264 else 13265 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13266 } 13267 } 13268 13269 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13270 // throw, add an implicit nothrow attribute to any extern "C" function we come 13271 // across. 13272 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13273 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13274 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13275 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13276 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13277 } 13278 13279 IdentifierInfo *Name = FD->getIdentifier(); 13280 if (!Name) 13281 return; 13282 if ((!getLangOpts().CPlusPlus && 13283 FD->getDeclContext()->isTranslationUnit()) || 13284 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13285 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13286 LinkageSpecDecl::lang_c)) { 13287 // Okay: this could be a libc/libm/Objective-C function we know 13288 // about. 13289 } else 13290 return; 13291 13292 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13293 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13294 // target-specific builtins, perhaps? 13295 if (!FD->hasAttr<FormatAttr>()) 13296 FD->addAttr(FormatAttr::CreateImplicit(Context, 13297 &Context.Idents.get("printf"), 2, 13298 Name->isStr("vasprintf") ? 0 : 3, 13299 FD->getLocation())); 13300 } 13301 13302 if (Name->isStr("__CFStringMakeConstantString")) { 13303 // We already have a __builtin___CFStringMakeConstantString, 13304 // but builds that use -fno-constant-cfstrings don't go through that. 13305 if (!FD->hasAttr<FormatArgAttr>()) 13306 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13307 FD->getLocation())); 13308 } 13309 } 13310 13311 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13312 TypeSourceInfo *TInfo) { 13313 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13314 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13315 13316 if (!TInfo) { 13317 assert(D.isInvalidType() && "no declarator info for valid type"); 13318 TInfo = Context.getTrivialTypeSourceInfo(T); 13319 } 13320 13321 // Scope manipulation handled by caller. 13322 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 13323 D.getLocStart(), 13324 D.getIdentifierLoc(), 13325 D.getIdentifier(), 13326 TInfo); 13327 13328 // Bail out immediately if we have an invalid declaration. 13329 if (D.isInvalidType()) { 13330 NewTD->setInvalidDecl(); 13331 return NewTD; 13332 } 13333 13334 if (D.getDeclSpec().isModulePrivateSpecified()) { 13335 if (CurContext->isFunctionOrMethod()) 13336 Diag(NewTD->getLocation(), diag::err_module_private_local) 13337 << 2 << NewTD->getDeclName() 13338 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13339 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13340 else 13341 NewTD->setModulePrivate(); 13342 } 13343 13344 // C++ [dcl.typedef]p8: 13345 // If the typedef declaration defines an unnamed class (or 13346 // enum), the first typedef-name declared by the declaration 13347 // to be that class type (or enum type) is used to denote the 13348 // class type (or enum type) for linkage purposes only. 13349 // We need to check whether the type was declared in the declaration. 13350 switch (D.getDeclSpec().getTypeSpecType()) { 13351 case TST_enum: 13352 case TST_struct: 13353 case TST_interface: 13354 case TST_union: 13355 case TST_class: { 13356 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13357 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13358 break; 13359 } 13360 13361 default: 13362 break; 13363 } 13364 13365 return NewTD; 13366 } 13367 13368 /// Check that this is a valid underlying type for an enum declaration. 13369 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13370 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13371 QualType T = TI->getType(); 13372 13373 if (T->isDependentType()) 13374 return false; 13375 13376 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13377 if (BT->isInteger()) 13378 return false; 13379 13380 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13381 return true; 13382 } 13383 13384 /// Check whether this is a valid redeclaration of a previous enumeration. 13385 /// \return true if the redeclaration was invalid. 13386 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13387 QualType EnumUnderlyingTy, bool IsFixed, 13388 const EnumDecl *Prev) { 13389 if (IsScoped != Prev->isScoped()) { 13390 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13391 << Prev->isScoped(); 13392 Diag(Prev->getLocation(), diag::note_previous_declaration); 13393 return true; 13394 } 13395 13396 if (IsFixed && Prev->isFixed()) { 13397 if (!EnumUnderlyingTy->isDependentType() && 13398 !Prev->getIntegerType()->isDependentType() && 13399 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13400 Prev->getIntegerType())) { 13401 // TODO: Highlight the underlying type of the redeclaration. 13402 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13403 << EnumUnderlyingTy << Prev->getIntegerType(); 13404 Diag(Prev->getLocation(), diag::note_previous_declaration) 13405 << Prev->getIntegerTypeRange(); 13406 return true; 13407 } 13408 } else if (IsFixed != Prev->isFixed()) { 13409 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13410 << Prev->isFixed(); 13411 Diag(Prev->getLocation(), diag::note_previous_declaration); 13412 return true; 13413 } 13414 13415 return false; 13416 } 13417 13418 /// Get diagnostic %select index for tag kind for 13419 /// redeclaration diagnostic message. 13420 /// WARNING: Indexes apply to particular diagnostics only! 13421 /// 13422 /// \returns diagnostic %select index. 13423 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13424 switch (Tag) { 13425 case TTK_Struct: return 0; 13426 case TTK_Interface: return 1; 13427 case TTK_Class: return 2; 13428 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13429 } 13430 } 13431 13432 /// Determine if tag kind is a class-key compatible with 13433 /// class for redeclaration (class, struct, or __interface). 13434 /// 13435 /// \returns true iff the tag kind is compatible. 13436 static bool isClassCompatTagKind(TagTypeKind Tag) 13437 { 13438 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13439 } 13440 13441 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13442 TagTypeKind TTK) { 13443 if (isa<TypedefDecl>(PrevDecl)) 13444 return NTK_Typedef; 13445 else if (isa<TypeAliasDecl>(PrevDecl)) 13446 return NTK_TypeAlias; 13447 else if (isa<ClassTemplateDecl>(PrevDecl)) 13448 return NTK_Template; 13449 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13450 return NTK_TypeAliasTemplate; 13451 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13452 return NTK_TemplateTemplateArgument; 13453 switch (TTK) { 13454 case TTK_Struct: 13455 case TTK_Interface: 13456 case TTK_Class: 13457 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13458 case TTK_Union: 13459 return NTK_NonUnion; 13460 case TTK_Enum: 13461 return NTK_NonEnum; 13462 } 13463 llvm_unreachable("invalid TTK"); 13464 } 13465 13466 /// Determine whether a tag with a given kind is acceptable 13467 /// as a redeclaration of the given tag declaration. 13468 /// 13469 /// \returns true if the new tag kind is acceptable, false otherwise. 13470 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13471 TagTypeKind NewTag, bool isDefinition, 13472 SourceLocation NewTagLoc, 13473 const IdentifierInfo *Name) { 13474 // C++ [dcl.type.elab]p3: 13475 // The class-key or enum keyword present in the 13476 // elaborated-type-specifier shall agree in kind with the 13477 // declaration to which the name in the elaborated-type-specifier 13478 // refers. This rule also applies to the form of 13479 // elaborated-type-specifier that declares a class-name or 13480 // friend class since it can be construed as referring to the 13481 // definition of the class. Thus, in any 13482 // elaborated-type-specifier, the enum keyword shall be used to 13483 // refer to an enumeration (7.2), the union class-key shall be 13484 // used to refer to a union (clause 9), and either the class or 13485 // struct class-key shall be used to refer to a class (clause 9) 13486 // declared using the class or struct class-key. 13487 TagTypeKind OldTag = Previous->getTagKind(); 13488 if (!isDefinition || !isClassCompatTagKind(NewTag)) 13489 if (OldTag == NewTag) 13490 return true; 13491 13492 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13493 // Warn about the struct/class tag mismatch. 13494 bool isTemplate = false; 13495 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13496 isTemplate = Record->getDescribedClassTemplate(); 13497 13498 if (inTemplateInstantiation()) { 13499 // In a template instantiation, do not offer fix-its for tag mismatches 13500 // since they usually mess up the template instead of fixing the problem. 13501 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13502 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13503 << getRedeclDiagFromTagKind(OldTag); 13504 return true; 13505 } 13506 13507 if (isDefinition) { 13508 // On definitions, check previous tags and issue a fix-it for each 13509 // one that doesn't match the current tag. 13510 if (Previous->getDefinition()) { 13511 // Don't suggest fix-its for redefinitions. 13512 return true; 13513 } 13514 13515 bool previousMismatch = false; 13516 for (auto I : Previous->redecls()) { 13517 if (I->getTagKind() != NewTag) { 13518 if (!previousMismatch) { 13519 previousMismatch = true; 13520 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13521 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13522 << getRedeclDiagFromTagKind(I->getTagKind()); 13523 } 13524 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13525 << getRedeclDiagFromTagKind(NewTag) 13526 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13527 TypeWithKeyword::getTagTypeKindName(NewTag)); 13528 } 13529 } 13530 return true; 13531 } 13532 13533 // Check for a previous definition. If current tag and definition 13534 // are same type, do nothing. If no definition, but disagree with 13535 // with previous tag type, give a warning, but no fix-it. 13536 const TagDecl *Redecl = Previous->getDefinition() ? 13537 Previous->getDefinition() : Previous; 13538 if (Redecl->getTagKind() == NewTag) { 13539 return true; 13540 } 13541 13542 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13543 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13544 << getRedeclDiagFromTagKind(OldTag); 13545 Diag(Redecl->getLocation(), diag::note_previous_use); 13546 13547 // If there is a previous definition, suggest a fix-it. 13548 if (Previous->getDefinition()) { 13549 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13550 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13551 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13552 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13553 } 13554 13555 return true; 13556 } 13557 return false; 13558 } 13559 13560 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13561 /// from an outer enclosing namespace or file scope inside a friend declaration. 13562 /// This should provide the commented out code in the following snippet: 13563 /// namespace N { 13564 /// struct X; 13565 /// namespace M { 13566 /// struct Y { friend struct /*N::*/ X; }; 13567 /// } 13568 /// } 13569 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13570 SourceLocation NameLoc) { 13571 // While the decl is in a namespace, do repeated lookup of that name and see 13572 // if we get the same namespace back. If we do not, continue until 13573 // translation unit scope, at which point we have a fully qualified NNS. 13574 SmallVector<IdentifierInfo *, 4> Namespaces; 13575 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13576 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13577 // This tag should be declared in a namespace, which can only be enclosed by 13578 // other namespaces. Bail if there's an anonymous namespace in the chain. 13579 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13580 if (!Namespace || Namespace->isAnonymousNamespace()) 13581 return FixItHint(); 13582 IdentifierInfo *II = Namespace->getIdentifier(); 13583 Namespaces.push_back(II); 13584 NamedDecl *Lookup = SemaRef.LookupSingleName( 13585 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13586 if (Lookup == Namespace) 13587 break; 13588 } 13589 13590 // Once we have all the namespaces, reverse them to go outermost first, and 13591 // build an NNS. 13592 SmallString<64> Insertion; 13593 llvm::raw_svector_ostream OS(Insertion); 13594 if (DC->isTranslationUnit()) 13595 OS << "::"; 13596 std::reverse(Namespaces.begin(), Namespaces.end()); 13597 for (auto *II : Namespaces) 13598 OS << II->getName() << "::"; 13599 return FixItHint::CreateInsertion(NameLoc, Insertion); 13600 } 13601 13602 /// Determine whether a tag originally declared in context \p OldDC can 13603 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 13604 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13605 /// using-declaration). 13606 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13607 DeclContext *NewDC) { 13608 OldDC = OldDC->getRedeclContext(); 13609 NewDC = NewDC->getRedeclContext(); 13610 13611 if (OldDC->Equals(NewDC)) 13612 return true; 13613 13614 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13615 // encloses the other). 13616 if (S.getLangOpts().MSVCCompat && 13617 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13618 return true; 13619 13620 return false; 13621 } 13622 13623 /// This is invoked when we see 'struct foo' or 'struct {'. In the 13624 /// former case, Name will be non-null. In the later case, Name will be null. 13625 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13626 /// reference/declaration/definition of a tag. 13627 /// 13628 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13629 /// trailing-type-specifier) other than one in an alias-declaration. 13630 /// 13631 /// \param SkipBody If non-null, will be set to indicate if the caller should 13632 /// skip the definition of this tag and treat it as if it were a declaration. 13633 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13634 SourceLocation KWLoc, CXXScopeSpec &SS, 13635 IdentifierInfo *Name, SourceLocation NameLoc, 13636 AttributeList *Attr, AccessSpecifier AS, 13637 SourceLocation ModulePrivateLoc, 13638 MultiTemplateParamsArg TemplateParameterLists, 13639 bool &OwnedDecl, bool &IsDependent, 13640 SourceLocation ScopedEnumKWLoc, 13641 bool ScopedEnumUsesClassTag, 13642 TypeResult UnderlyingType, 13643 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13644 SkipBodyInfo *SkipBody) { 13645 // If this is not a definition, it must have a name. 13646 IdentifierInfo *OrigName = Name; 13647 assert((Name != nullptr || TUK == TUK_Definition) && 13648 "Nameless record must be a definition!"); 13649 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13650 13651 OwnedDecl = false; 13652 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13653 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13654 13655 // FIXME: Check member specializations more carefully. 13656 bool isMemberSpecialization = false; 13657 bool Invalid = false; 13658 13659 // We only need to do this matching if we have template parameters 13660 // or a scope specifier, which also conveniently avoids this work 13661 // for non-C++ cases. 13662 if (TemplateParameterLists.size() > 0 || 13663 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13664 if (TemplateParameterList *TemplateParams = 13665 MatchTemplateParametersToScopeSpecifier( 13666 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13667 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13668 if (Kind == TTK_Enum) { 13669 Diag(KWLoc, diag::err_enum_template); 13670 return nullptr; 13671 } 13672 13673 if (TemplateParams->size() > 0) { 13674 // This is a declaration or definition of a class template (which may 13675 // be a member of another template). 13676 13677 if (Invalid) 13678 return nullptr; 13679 13680 OwnedDecl = false; 13681 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13682 SS, Name, NameLoc, Attr, 13683 TemplateParams, AS, 13684 ModulePrivateLoc, 13685 /*FriendLoc*/SourceLocation(), 13686 TemplateParameterLists.size()-1, 13687 TemplateParameterLists.data(), 13688 SkipBody); 13689 return Result.get(); 13690 } else { 13691 // The "template<>" header is extraneous. 13692 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13693 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13694 isMemberSpecialization = true; 13695 } 13696 } 13697 } 13698 13699 // Figure out the underlying type if this a enum declaration. We need to do 13700 // this early, because it's needed to detect if this is an incompatible 13701 // redeclaration. 13702 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13703 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 13704 13705 if (Kind == TTK_Enum) { 13706 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 13707 // No underlying type explicitly specified, or we failed to parse the 13708 // type, default to int. 13709 EnumUnderlying = Context.IntTy.getTypePtr(); 13710 } else if (UnderlyingType.get()) { 13711 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13712 // integral type; any cv-qualification is ignored. 13713 TypeSourceInfo *TI = nullptr; 13714 GetTypeFromParser(UnderlyingType.get(), &TI); 13715 EnumUnderlying = TI; 13716 13717 if (CheckEnumUnderlyingType(TI)) 13718 // Recover by falling back to int. 13719 EnumUnderlying = Context.IntTy.getTypePtr(); 13720 13721 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13722 UPPC_FixedUnderlyingType)) 13723 EnumUnderlying = Context.IntTy.getTypePtr(); 13724 13725 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13726 // For MSVC ABI compatibility, unfixed enums must use an underlying type 13727 // of 'int'. However, if this is an unfixed forward declaration, don't set 13728 // the underlying type unless the user enables -fms-compatibility. This 13729 // makes unfixed forward declared enums incomplete and is more conforming. 13730 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 13731 EnumUnderlying = Context.IntTy.getTypePtr(); 13732 } 13733 } 13734 13735 DeclContext *SearchDC = CurContext; 13736 DeclContext *DC = CurContext; 13737 bool isStdBadAlloc = false; 13738 bool isStdAlignValT = false; 13739 13740 RedeclarationKind Redecl = forRedeclarationInCurContext(); 13741 if (TUK == TUK_Friend || TUK == TUK_Reference) 13742 Redecl = NotForRedeclaration; 13743 13744 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13745 /// implemented asks for structural equivalence checking, the returned decl 13746 /// here is passed back to the parser, allowing the tag body to be parsed. 13747 auto createTagFromNewDecl = [&]() -> TagDecl * { 13748 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13749 // If there is an identifier, use the location of the identifier as the 13750 // location of the decl, otherwise use the location of the struct/union 13751 // keyword. 13752 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13753 TagDecl *New = nullptr; 13754 13755 if (Kind == TTK_Enum) { 13756 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13757 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 13758 // If this is an undefined enum, bail. 13759 if (TUK != TUK_Definition && !Invalid) 13760 return nullptr; 13761 if (EnumUnderlying) { 13762 EnumDecl *ED = cast<EnumDecl>(New); 13763 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13764 ED->setIntegerTypeSourceInfo(TI); 13765 else 13766 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13767 ED->setPromotionType(ED->getIntegerType()); 13768 } 13769 } else { // struct/union 13770 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13771 nullptr); 13772 } 13773 13774 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13775 // Add alignment attributes if necessary; these attributes are checked 13776 // when the ASTContext lays out the structure. 13777 // 13778 // It is important for implementing the correct semantics that this 13779 // happen here (in ActOnTag). The #pragma pack stack is 13780 // maintained as a result of parser callbacks which can occur at 13781 // many points during the parsing of a struct declaration (because 13782 // the #pragma tokens are effectively skipped over during the 13783 // parsing of the struct). 13784 if (TUK == TUK_Definition) { 13785 AddAlignmentAttributesForRecord(RD); 13786 AddMsStructLayoutForRecord(RD); 13787 } 13788 } 13789 New->setLexicalDeclContext(CurContext); 13790 return New; 13791 }; 13792 13793 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13794 if (Name && SS.isNotEmpty()) { 13795 // We have a nested-name tag ('struct foo::bar'). 13796 13797 // Check for invalid 'foo::'. 13798 if (SS.isInvalid()) { 13799 Name = nullptr; 13800 goto CreateNewDecl; 13801 } 13802 13803 // If this is a friend or a reference to a class in a dependent 13804 // context, don't try to make a decl for it. 13805 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13806 DC = computeDeclContext(SS, false); 13807 if (!DC) { 13808 IsDependent = true; 13809 return nullptr; 13810 } 13811 } else { 13812 DC = computeDeclContext(SS, true); 13813 if (!DC) { 13814 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13815 << SS.getRange(); 13816 return nullptr; 13817 } 13818 } 13819 13820 if (RequireCompleteDeclContext(SS, DC)) 13821 return nullptr; 13822 13823 SearchDC = DC; 13824 // Look-up name inside 'foo::'. 13825 LookupQualifiedName(Previous, DC); 13826 13827 if (Previous.isAmbiguous()) 13828 return nullptr; 13829 13830 if (Previous.empty()) { 13831 // Name lookup did not find anything. However, if the 13832 // nested-name-specifier refers to the current instantiation, 13833 // and that current instantiation has any dependent base 13834 // classes, we might find something at instantiation time: treat 13835 // this as a dependent elaborated-type-specifier. 13836 // But this only makes any sense for reference-like lookups. 13837 if (Previous.wasNotFoundInCurrentInstantiation() && 13838 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13839 IsDependent = true; 13840 return nullptr; 13841 } 13842 13843 // A tag 'foo::bar' must already exist. 13844 Diag(NameLoc, diag::err_not_tag_in_scope) 13845 << Kind << Name << DC << SS.getRange(); 13846 Name = nullptr; 13847 Invalid = true; 13848 goto CreateNewDecl; 13849 } 13850 } else if (Name) { 13851 // C++14 [class.mem]p14: 13852 // If T is the name of a class, then each of the following shall have a 13853 // name different from T: 13854 // -- every member of class T that is itself a type 13855 if (TUK != TUK_Reference && TUK != TUK_Friend && 13856 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13857 return nullptr; 13858 13859 // If this is a named struct, check to see if there was a previous forward 13860 // declaration or definition. 13861 // FIXME: We're looking into outer scopes here, even when we 13862 // shouldn't be. Doing so can result in ambiguities that we 13863 // shouldn't be diagnosing. 13864 LookupName(Previous, S); 13865 13866 // When declaring or defining a tag, ignore ambiguities introduced 13867 // by types using'ed into this scope. 13868 if (Previous.isAmbiguous() && 13869 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13870 LookupResult::Filter F = Previous.makeFilter(); 13871 while (F.hasNext()) { 13872 NamedDecl *ND = F.next(); 13873 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13874 SearchDC->getRedeclContext())) 13875 F.erase(); 13876 } 13877 F.done(); 13878 } 13879 13880 // C++11 [namespace.memdef]p3: 13881 // If the name in a friend declaration is neither qualified nor 13882 // a template-id and the declaration is a function or an 13883 // elaborated-type-specifier, the lookup to determine whether 13884 // the entity has been previously declared shall not consider 13885 // any scopes outside the innermost enclosing namespace. 13886 // 13887 // MSVC doesn't implement the above rule for types, so a friend tag 13888 // declaration may be a redeclaration of a type declared in an enclosing 13889 // scope. They do implement this rule for friend functions. 13890 // 13891 // Does it matter that this should be by scope instead of by 13892 // semantic context? 13893 if (!Previous.empty() && TUK == TUK_Friend) { 13894 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13895 LookupResult::Filter F = Previous.makeFilter(); 13896 bool FriendSawTagOutsideEnclosingNamespace = false; 13897 while (F.hasNext()) { 13898 NamedDecl *ND = F.next(); 13899 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13900 if (DC->isFileContext() && 13901 !EnclosingNS->Encloses(ND->getDeclContext())) { 13902 if (getLangOpts().MSVCCompat) 13903 FriendSawTagOutsideEnclosingNamespace = true; 13904 else 13905 F.erase(); 13906 } 13907 } 13908 F.done(); 13909 13910 // Diagnose this MSVC extension in the easy case where lookup would have 13911 // unambiguously found something outside the enclosing namespace. 13912 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13913 NamedDecl *ND = Previous.getFoundDecl(); 13914 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13915 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13916 } 13917 } 13918 13919 // Note: there used to be some attempt at recovery here. 13920 if (Previous.isAmbiguous()) 13921 return nullptr; 13922 13923 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13924 // FIXME: This makes sure that we ignore the contexts associated 13925 // with C structs, unions, and enums when looking for a matching 13926 // tag declaration or definition. See the similar lookup tweak 13927 // in Sema::LookupName; is there a better way to deal with this? 13928 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13929 SearchDC = SearchDC->getParent(); 13930 } 13931 } 13932 13933 if (Previous.isSingleResult() && 13934 Previous.getFoundDecl()->isTemplateParameter()) { 13935 // Maybe we will complain about the shadowed template parameter. 13936 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13937 // Just pretend that we didn't see the previous declaration. 13938 Previous.clear(); 13939 } 13940 13941 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13942 DC->Equals(getStdNamespace())) { 13943 if (Name->isStr("bad_alloc")) { 13944 // This is a declaration of or a reference to "std::bad_alloc". 13945 isStdBadAlloc = true; 13946 13947 // If std::bad_alloc has been implicitly declared (but made invisible to 13948 // name lookup), fill in this implicit declaration as the previous 13949 // declaration, so that the declarations get chained appropriately. 13950 if (Previous.empty() && StdBadAlloc) 13951 Previous.addDecl(getStdBadAlloc()); 13952 } else if (Name->isStr("align_val_t")) { 13953 isStdAlignValT = true; 13954 if (Previous.empty() && StdAlignValT) 13955 Previous.addDecl(getStdAlignValT()); 13956 } 13957 } 13958 13959 // If we didn't find a previous declaration, and this is a reference 13960 // (or friend reference), move to the correct scope. In C++, we 13961 // also need to do a redeclaration lookup there, just in case 13962 // there's a shadow friend decl. 13963 if (Name && Previous.empty() && 13964 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13965 if (Invalid) goto CreateNewDecl; 13966 assert(SS.isEmpty()); 13967 13968 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13969 // C++ [basic.scope.pdecl]p5: 13970 // -- for an elaborated-type-specifier of the form 13971 // 13972 // class-key identifier 13973 // 13974 // if the elaborated-type-specifier is used in the 13975 // decl-specifier-seq or parameter-declaration-clause of a 13976 // function defined in namespace scope, the identifier is 13977 // declared as a class-name in the namespace that contains 13978 // the declaration; otherwise, except as a friend 13979 // declaration, the identifier is declared in the smallest 13980 // non-class, non-function-prototype scope that contains the 13981 // declaration. 13982 // 13983 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13984 // C structs and unions. 13985 // 13986 // It is an error in C++ to declare (rather than define) an enum 13987 // type, including via an elaborated type specifier. We'll 13988 // diagnose that later; for now, declare the enum in the same 13989 // scope as we would have picked for any other tag type. 13990 // 13991 // GNU C also supports this behavior as part of its incomplete 13992 // enum types extension, while GNU C++ does not. 13993 // 13994 // Find the context where we'll be declaring the tag. 13995 // FIXME: We would like to maintain the current DeclContext as the 13996 // lexical context, 13997 SearchDC = getTagInjectionContext(SearchDC); 13998 13999 // Find the scope where we'll be declaring the tag. 14000 S = getTagInjectionScope(S, getLangOpts()); 14001 } else { 14002 assert(TUK == TUK_Friend); 14003 // C++ [namespace.memdef]p3: 14004 // If a friend declaration in a non-local class first declares a 14005 // class or function, the friend class or function is a member of 14006 // the innermost enclosing namespace. 14007 SearchDC = SearchDC->getEnclosingNamespaceContext(); 14008 } 14009 14010 // In C++, we need to do a redeclaration lookup to properly 14011 // diagnose some problems. 14012 // FIXME: redeclaration lookup is also used (with and without C++) to find a 14013 // hidden declaration so that we don't get ambiguity errors when using a 14014 // type declared by an elaborated-type-specifier. In C that is not correct 14015 // and we should instead merge compatible types found by lookup. 14016 if (getLangOpts().CPlusPlus) { 14017 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14018 LookupQualifiedName(Previous, SearchDC); 14019 } else { 14020 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14021 LookupName(Previous, S); 14022 } 14023 } 14024 14025 // If we have a known previous declaration to use, then use it. 14026 if (Previous.empty() && SkipBody && SkipBody->Previous) 14027 Previous.addDecl(SkipBody->Previous); 14028 14029 if (!Previous.empty()) { 14030 NamedDecl *PrevDecl = Previous.getFoundDecl(); 14031 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 14032 14033 // It's okay to have a tag decl in the same scope as a typedef 14034 // which hides a tag decl in the same scope. Finding this 14035 // insanity with a redeclaration lookup can only actually happen 14036 // in C++. 14037 // 14038 // This is also okay for elaborated-type-specifiers, which is 14039 // technically forbidden by the current standard but which is 14040 // okay according to the likely resolution of an open issue; 14041 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 14042 if (getLangOpts().CPlusPlus) { 14043 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14044 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 14045 TagDecl *Tag = TT->getDecl(); 14046 if (Tag->getDeclName() == Name && 14047 Tag->getDeclContext()->getRedeclContext() 14048 ->Equals(TD->getDeclContext()->getRedeclContext())) { 14049 PrevDecl = Tag; 14050 Previous.clear(); 14051 Previous.addDecl(Tag); 14052 Previous.resolveKind(); 14053 } 14054 } 14055 } 14056 } 14057 14058 // If this is a redeclaration of a using shadow declaration, it must 14059 // declare a tag in the same context. In MSVC mode, we allow a 14060 // redefinition if either context is within the other. 14061 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 14062 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 14063 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 14064 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 14065 !(OldTag && isAcceptableTagRedeclContext( 14066 *this, OldTag->getDeclContext(), SearchDC))) { 14067 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 14068 Diag(Shadow->getTargetDecl()->getLocation(), 14069 diag::note_using_decl_target); 14070 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 14071 << 0; 14072 // Recover by ignoring the old declaration. 14073 Previous.clear(); 14074 goto CreateNewDecl; 14075 } 14076 } 14077 14078 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 14079 // If this is a use of a previous tag, or if the tag is already declared 14080 // in the same scope (so that the definition/declaration completes or 14081 // rementions the tag), reuse the decl. 14082 if (TUK == TUK_Reference || TUK == TUK_Friend || 14083 isDeclInScope(DirectPrevDecl, SearchDC, S, 14084 SS.isNotEmpty() || isMemberSpecialization)) { 14085 // Make sure that this wasn't declared as an enum and now used as a 14086 // struct or something similar. 14087 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14088 TUK == TUK_Definition, KWLoc, 14089 Name)) { 14090 bool SafeToContinue 14091 = (PrevTagDecl->getTagKind() != TTK_Enum && 14092 Kind != TTK_Enum); 14093 if (SafeToContinue) 14094 Diag(KWLoc, diag::err_use_with_wrong_tag) 14095 << Name 14096 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14097 PrevTagDecl->getKindName()); 14098 else 14099 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14100 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14101 14102 if (SafeToContinue) 14103 Kind = PrevTagDecl->getTagKind(); 14104 else { 14105 // Recover by making this an anonymous redefinition. 14106 Name = nullptr; 14107 Previous.clear(); 14108 Invalid = true; 14109 } 14110 } 14111 14112 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14113 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14114 14115 // If this is an elaborated-type-specifier for a scoped enumeration, 14116 // the 'class' keyword is not necessary and not permitted. 14117 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14118 if (ScopedEnum) 14119 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14120 << PrevEnum->isScoped() 14121 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14122 return PrevTagDecl; 14123 } 14124 14125 QualType EnumUnderlyingTy; 14126 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14127 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14128 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14129 EnumUnderlyingTy = QualType(T, 0); 14130 14131 // All conflicts with previous declarations are recovered by 14132 // returning the previous declaration, unless this is a definition, 14133 // in which case we want the caller to bail out. 14134 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14135 ScopedEnum, EnumUnderlyingTy, 14136 IsFixed, PrevEnum)) 14137 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14138 } 14139 14140 // C++11 [class.mem]p1: 14141 // A member shall not be declared twice in the member-specification, 14142 // except that a nested class or member class template can be declared 14143 // and then later defined. 14144 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14145 S->isDeclScope(PrevDecl)) { 14146 Diag(NameLoc, diag::ext_member_redeclared); 14147 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14148 } 14149 14150 if (!Invalid) { 14151 // If this is a use, just return the declaration we found, unless 14152 // we have attributes. 14153 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14154 if (Attr) { 14155 // FIXME: Diagnose these attributes. For now, we create a new 14156 // declaration to hold them. 14157 } else if (TUK == TUK_Reference && 14158 (PrevTagDecl->getFriendObjectKind() == 14159 Decl::FOK_Undeclared || 14160 PrevDecl->getOwningModule() != getCurrentModule()) && 14161 SS.isEmpty()) { 14162 // This declaration is a reference to an existing entity, but 14163 // has different visibility from that entity: it either makes 14164 // a friend visible or it makes a type visible in a new module. 14165 // In either case, create a new declaration. We only do this if 14166 // the declaration would have meant the same thing if no prior 14167 // declaration were found, that is, if it was found in the same 14168 // scope where we would have injected a declaration. 14169 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14170 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14171 return PrevTagDecl; 14172 // This is in the injected scope, create a new declaration in 14173 // that scope. 14174 S = getTagInjectionScope(S, getLangOpts()); 14175 } else { 14176 return PrevTagDecl; 14177 } 14178 } 14179 14180 // Diagnose attempts to redefine a tag. 14181 if (TUK == TUK_Definition) { 14182 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14183 // If we're defining a specialization and the previous definition 14184 // is from an implicit instantiation, don't emit an error 14185 // here; we'll catch this in the general case below. 14186 bool IsExplicitSpecializationAfterInstantiation = false; 14187 if (isMemberSpecialization) { 14188 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14189 IsExplicitSpecializationAfterInstantiation = 14190 RD->getTemplateSpecializationKind() != 14191 TSK_ExplicitSpecialization; 14192 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14193 IsExplicitSpecializationAfterInstantiation = 14194 ED->getTemplateSpecializationKind() != 14195 TSK_ExplicitSpecialization; 14196 } 14197 14198 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14199 // not keep more that one definition around (merge them). However, 14200 // ensure the decl passes the structural compatibility check in 14201 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14202 NamedDecl *Hidden = nullptr; 14203 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14204 // There is a definition of this tag, but it is not visible. We 14205 // explicitly make use of C++'s one definition rule here, and 14206 // assume that this definition is identical to the hidden one 14207 // we already have. Make the existing definition visible and 14208 // use it in place of this one. 14209 if (!getLangOpts().CPlusPlus) { 14210 // Postpone making the old definition visible until after we 14211 // complete parsing the new one and do the structural 14212 // comparison. 14213 SkipBody->CheckSameAsPrevious = true; 14214 SkipBody->New = createTagFromNewDecl(); 14215 SkipBody->Previous = Hidden; 14216 } else { 14217 SkipBody->ShouldSkip = true; 14218 makeMergedDefinitionVisible(Hidden); 14219 } 14220 return Def; 14221 } else if (!IsExplicitSpecializationAfterInstantiation) { 14222 // A redeclaration in function prototype scope in C isn't 14223 // visible elsewhere, so merely issue a warning. 14224 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14225 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14226 else 14227 Diag(NameLoc, diag::err_redefinition) << Name; 14228 notePreviousDefinition(Def, 14229 NameLoc.isValid() ? NameLoc : KWLoc); 14230 // If this is a redefinition, recover by making this 14231 // struct be anonymous, which will make any later 14232 // references get the previous definition. 14233 Name = nullptr; 14234 Previous.clear(); 14235 Invalid = true; 14236 } 14237 } else { 14238 // If the type is currently being defined, complain 14239 // about a nested redefinition. 14240 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14241 if (TD->isBeingDefined()) { 14242 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14243 Diag(PrevTagDecl->getLocation(), 14244 diag::note_previous_definition); 14245 Name = nullptr; 14246 Previous.clear(); 14247 Invalid = true; 14248 } 14249 } 14250 14251 // Okay, this is definition of a previously declared or referenced 14252 // tag. We're going to create a new Decl for it. 14253 } 14254 14255 // Okay, we're going to make a redeclaration. If this is some kind 14256 // of reference, make sure we build the redeclaration in the same DC 14257 // as the original, and ignore the current access specifier. 14258 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14259 SearchDC = PrevTagDecl->getDeclContext(); 14260 AS = AS_none; 14261 } 14262 } 14263 // If we get here we have (another) forward declaration or we 14264 // have a definition. Just create a new decl. 14265 14266 } else { 14267 // If we get here, this is a definition of a new tag type in a nested 14268 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14269 // new decl/type. We set PrevDecl to NULL so that the entities 14270 // have distinct types. 14271 Previous.clear(); 14272 } 14273 // If we get here, we're going to create a new Decl. If PrevDecl 14274 // is non-NULL, it's a definition of the tag declared by 14275 // PrevDecl. If it's NULL, we have a new definition. 14276 14277 // Otherwise, PrevDecl is not a tag, but was found with tag 14278 // lookup. This is only actually possible in C++, where a few 14279 // things like templates still live in the tag namespace. 14280 } else { 14281 // Use a better diagnostic if an elaborated-type-specifier 14282 // found the wrong kind of type on the first 14283 // (non-redeclaration) lookup. 14284 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14285 !Previous.isForRedeclaration()) { 14286 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14287 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14288 << Kind; 14289 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14290 Invalid = true; 14291 14292 // Otherwise, only diagnose if the declaration is in scope. 14293 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14294 SS.isNotEmpty() || isMemberSpecialization)) { 14295 // do nothing 14296 14297 // Diagnose implicit declarations introduced by elaborated types. 14298 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14299 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14300 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14301 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14302 Invalid = true; 14303 14304 // Otherwise it's a declaration. Call out a particularly common 14305 // case here. 14306 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14307 unsigned Kind = 0; 14308 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14309 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14310 << Name << Kind << TND->getUnderlyingType(); 14311 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14312 Invalid = true; 14313 14314 // Otherwise, diagnose. 14315 } else { 14316 // The tag name clashes with something else in the target scope, 14317 // issue an error and recover by making this tag be anonymous. 14318 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14319 notePreviousDefinition(PrevDecl, NameLoc); 14320 Name = nullptr; 14321 Invalid = true; 14322 } 14323 14324 // The existing declaration isn't relevant to us; we're in a 14325 // new scope, so clear out the previous declaration. 14326 Previous.clear(); 14327 } 14328 } 14329 14330 CreateNewDecl: 14331 14332 TagDecl *PrevDecl = nullptr; 14333 if (Previous.isSingleResult()) 14334 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14335 14336 // If there is an identifier, use the location of the identifier as the 14337 // location of the decl, otherwise use the location of the struct/union 14338 // keyword. 14339 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14340 14341 // Otherwise, create a new declaration. If there is a previous 14342 // declaration of the same entity, the two will be linked via 14343 // PrevDecl. 14344 TagDecl *New; 14345 14346 bool IsForwardReference = false; 14347 if (Kind == TTK_Enum) { 14348 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14349 // enum X { A, B, C } D; D should chain to X. 14350 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14351 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14352 ScopedEnumUsesClassTag, IsFixed); 14353 14354 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14355 StdAlignValT = cast<EnumDecl>(New); 14356 14357 // If this is an undefined enum, warn. 14358 if (TUK != TUK_Definition && !Invalid) { 14359 TagDecl *Def; 14360 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 14361 cast<EnumDecl>(New)->isFixed()) { 14362 // C++0x: 7.2p2: opaque-enum-declaration. 14363 // Conflicts are diagnosed above. Do nothing. 14364 } 14365 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14366 Diag(Loc, diag::ext_forward_ref_enum_def) 14367 << New; 14368 Diag(Def->getLocation(), diag::note_previous_definition); 14369 } else { 14370 unsigned DiagID = diag::ext_forward_ref_enum; 14371 if (getLangOpts().MSVCCompat) 14372 DiagID = diag::ext_ms_forward_ref_enum; 14373 else if (getLangOpts().CPlusPlus) 14374 DiagID = diag::err_forward_ref_enum; 14375 Diag(Loc, DiagID); 14376 14377 // If this is a forward-declared reference to an enumeration, make a 14378 // note of it; we won't actually be introducing the declaration into 14379 // the declaration context. 14380 if (TUK == TUK_Reference) 14381 IsForwardReference = true; 14382 } 14383 } 14384 14385 if (EnumUnderlying) { 14386 EnumDecl *ED = cast<EnumDecl>(New); 14387 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14388 ED->setIntegerTypeSourceInfo(TI); 14389 else 14390 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14391 ED->setPromotionType(ED->getIntegerType()); 14392 assert(ED->isComplete() && "enum with type should be complete"); 14393 } 14394 } else { 14395 // struct/union/class 14396 14397 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14398 // struct X { int A; } D; D should chain to X. 14399 if (getLangOpts().CPlusPlus) { 14400 // FIXME: Look for a way to use RecordDecl for simple structs. 14401 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14402 cast_or_null<CXXRecordDecl>(PrevDecl)); 14403 14404 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14405 StdBadAlloc = cast<CXXRecordDecl>(New); 14406 } else 14407 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14408 cast_or_null<RecordDecl>(PrevDecl)); 14409 } 14410 14411 // C++11 [dcl.type]p3: 14412 // A type-specifier-seq shall not define a class or enumeration [...]. 14413 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14414 TUK == TUK_Definition) { 14415 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14416 << Context.getTagDeclType(New); 14417 Invalid = true; 14418 } 14419 14420 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14421 DC->getDeclKind() == Decl::Enum) { 14422 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14423 << Context.getTagDeclType(New); 14424 Invalid = true; 14425 } 14426 14427 // Maybe add qualifier info. 14428 if (SS.isNotEmpty()) { 14429 if (SS.isSet()) { 14430 // If this is either a declaration or a definition, check the 14431 // nested-name-specifier against the current context. 14432 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14433 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14434 isMemberSpecialization)) 14435 Invalid = true; 14436 14437 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14438 if (TemplateParameterLists.size() > 0) { 14439 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14440 } 14441 } 14442 else 14443 Invalid = true; 14444 } 14445 14446 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14447 // Add alignment attributes if necessary; these attributes are checked when 14448 // the ASTContext lays out the structure. 14449 // 14450 // It is important for implementing the correct semantics that this 14451 // happen here (in ActOnTag). The #pragma pack stack is 14452 // maintained as a result of parser callbacks which can occur at 14453 // many points during the parsing of a struct declaration (because 14454 // the #pragma tokens are effectively skipped over during the 14455 // parsing of the struct). 14456 if (TUK == TUK_Definition) { 14457 AddAlignmentAttributesForRecord(RD); 14458 AddMsStructLayoutForRecord(RD); 14459 } 14460 } 14461 14462 if (ModulePrivateLoc.isValid()) { 14463 if (isMemberSpecialization) 14464 Diag(New->getLocation(), diag::err_module_private_specialization) 14465 << 2 14466 << FixItHint::CreateRemoval(ModulePrivateLoc); 14467 // __module_private__ does not apply to local classes. However, we only 14468 // diagnose this as an error when the declaration specifiers are 14469 // freestanding. Here, we just ignore the __module_private__. 14470 else if (!SearchDC->isFunctionOrMethod()) 14471 New->setModulePrivate(); 14472 } 14473 14474 // If this is a specialization of a member class (of a class template), 14475 // check the specialization. 14476 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14477 Invalid = true; 14478 14479 // If we're declaring or defining a tag in function prototype scope in C, 14480 // note that this type can only be used within the function and add it to 14481 // the list of decls to inject into the function definition scope. 14482 if ((Name || Kind == TTK_Enum) && 14483 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14484 if (getLangOpts().CPlusPlus) { 14485 // C++ [dcl.fct]p6: 14486 // Types shall not be defined in return or parameter types. 14487 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14488 Diag(Loc, diag::err_type_defined_in_param_type) 14489 << Name; 14490 Invalid = true; 14491 } 14492 } else if (!PrevDecl) { 14493 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14494 } 14495 } 14496 14497 if (Invalid) 14498 New->setInvalidDecl(); 14499 14500 // Set the lexical context. If the tag has a C++ scope specifier, the 14501 // lexical context will be different from the semantic context. 14502 New->setLexicalDeclContext(CurContext); 14503 14504 // Mark this as a friend decl if applicable. 14505 // In Microsoft mode, a friend declaration also acts as a forward 14506 // declaration so we always pass true to setObjectOfFriendDecl to make 14507 // the tag name visible. 14508 if (TUK == TUK_Friend) 14509 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14510 14511 // Set the access specifier. 14512 if (!Invalid && SearchDC->isRecord()) 14513 SetMemberAccessSpecifier(New, PrevDecl, AS); 14514 14515 if (PrevDecl) 14516 CheckRedeclarationModuleOwnership(New, PrevDecl); 14517 14518 if (TUK == TUK_Definition) 14519 New->startDefinition(); 14520 14521 if (Attr) 14522 ProcessDeclAttributeList(S, New, Attr); 14523 AddPragmaAttributes(S, New); 14524 14525 // If this has an identifier, add it to the scope stack. 14526 if (TUK == TUK_Friend) { 14527 // We might be replacing an existing declaration in the lookup tables; 14528 // if so, borrow its access specifier. 14529 if (PrevDecl) 14530 New->setAccess(PrevDecl->getAccess()); 14531 14532 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14533 DC->makeDeclVisibleInContext(New); 14534 if (Name) // can be null along some error paths 14535 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14536 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14537 } else if (Name) { 14538 S = getNonFieldDeclScope(S); 14539 PushOnScopeChains(New, S, !IsForwardReference); 14540 if (IsForwardReference) 14541 SearchDC->makeDeclVisibleInContext(New); 14542 } else { 14543 CurContext->addDecl(New); 14544 } 14545 14546 // If this is the C FILE type, notify the AST context. 14547 if (IdentifierInfo *II = New->getIdentifier()) 14548 if (!New->isInvalidDecl() && 14549 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14550 II->isStr("FILE")) 14551 Context.setFILEDecl(New); 14552 14553 if (PrevDecl) 14554 mergeDeclAttributes(New, PrevDecl); 14555 14556 // If there's a #pragma GCC visibility in scope, set the visibility of this 14557 // record. 14558 AddPushedVisibilityAttribute(New); 14559 14560 if (isMemberSpecialization && !New->isInvalidDecl()) 14561 CompleteMemberSpecialization(New, Previous); 14562 14563 OwnedDecl = true; 14564 // In C++, don't return an invalid declaration. We can't recover well from 14565 // the cases where we make the type anonymous. 14566 if (Invalid && getLangOpts().CPlusPlus) { 14567 if (New->isBeingDefined()) 14568 if (auto RD = dyn_cast<RecordDecl>(New)) 14569 RD->completeDefinition(); 14570 return nullptr; 14571 } else { 14572 return New; 14573 } 14574 } 14575 14576 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14577 AdjustDeclIfTemplate(TagD); 14578 TagDecl *Tag = cast<TagDecl>(TagD); 14579 14580 // Enter the tag context. 14581 PushDeclContext(S, Tag); 14582 14583 ActOnDocumentableDecl(TagD); 14584 14585 // If there's a #pragma GCC visibility in scope, set the visibility of this 14586 // record. 14587 AddPushedVisibilityAttribute(Tag); 14588 } 14589 14590 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14591 SkipBodyInfo &SkipBody) { 14592 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14593 return false; 14594 14595 // Make the previous decl visible. 14596 makeMergedDefinitionVisible(SkipBody.Previous); 14597 return true; 14598 } 14599 14600 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14601 assert(isa<ObjCContainerDecl>(IDecl) && 14602 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14603 DeclContext *OCD = cast<DeclContext>(IDecl); 14604 assert(getContainingDC(OCD) == CurContext && 14605 "The next DeclContext should be lexically contained in the current one."); 14606 CurContext = OCD; 14607 return IDecl; 14608 } 14609 14610 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14611 SourceLocation FinalLoc, 14612 bool IsFinalSpelledSealed, 14613 SourceLocation LBraceLoc) { 14614 AdjustDeclIfTemplate(TagD); 14615 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14616 14617 FieldCollector->StartClass(); 14618 14619 if (!Record->getIdentifier()) 14620 return; 14621 14622 if (FinalLoc.isValid()) 14623 Record->addAttr(new (Context) 14624 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14625 14626 // C++ [class]p2: 14627 // [...] The class-name is also inserted into the scope of the 14628 // class itself; this is known as the injected-class-name. For 14629 // purposes of access checking, the injected-class-name is treated 14630 // as if it were a public member name. 14631 CXXRecordDecl *InjectedClassName 14632 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14633 Record->getLocStart(), Record->getLocation(), 14634 Record->getIdentifier(), 14635 /*PrevDecl=*/nullptr, 14636 /*DelayTypeCreation=*/true); 14637 Context.getTypeDeclType(InjectedClassName, Record); 14638 InjectedClassName->setImplicit(); 14639 InjectedClassName->setAccess(AS_public); 14640 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14641 InjectedClassName->setDescribedClassTemplate(Template); 14642 PushOnScopeChains(InjectedClassName, S); 14643 assert(InjectedClassName->isInjectedClassName() && 14644 "Broken injected-class-name"); 14645 } 14646 14647 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14648 SourceRange BraceRange) { 14649 AdjustDeclIfTemplate(TagD); 14650 TagDecl *Tag = cast<TagDecl>(TagD); 14651 Tag->setBraceRange(BraceRange); 14652 14653 // Make sure we "complete" the definition even it is invalid. 14654 if (Tag->isBeingDefined()) { 14655 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14656 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14657 RD->completeDefinition(); 14658 } 14659 14660 if (isa<CXXRecordDecl>(Tag)) { 14661 FieldCollector->FinishClass(); 14662 } 14663 14664 // Exit this scope of this tag's definition. 14665 PopDeclContext(); 14666 14667 if (getCurLexicalContext()->isObjCContainer() && 14668 Tag->getDeclContext()->isFileContext()) 14669 Tag->setTopLevelDeclInObjCContainer(); 14670 14671 // Notify the consumer that we've defined a tag. 14672 if (!Tag->isInvalidDecl()) 14673 Consumer.HandleTagDeclDefinition(Tag); 14674 } 14675 14676 void Sema::ActOnObjCContainerFinishDefinition() { 14677 // Exit this scope of this interface definition. 14678 PopDeclContext(); 14679 } 14680 14681 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14682 assert(DC == CurContext && "Mismatch of container contexts"); 14683 OriginalLexicalContext = DC; 14684 ActOnObjCContainerFinishDefinition(); 14685 } 14686 14687 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14688 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14689 OriginalLexicalContext = nullptr; 14690 } 14691 14692 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14693 AdjustDeclIfTemplate(TagD); 14694 TagDecl *Tag = cast<TagDecl>(TagD); 14695 Tag->setInvalidDecl(); 14696 14697 // Make sure we "complete" the definition even it is invalid. 14698 if (Tag->isBeingDefined()) { 14699 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14700 RD->completeDefinition(); 14701 } 14702 14703 // We're undoing ActOnTagStartDefinition here, not 14704 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14705 // the FieldCollector. 14706 14707 PopDeclContext(); 14708 } 14709 14710 // Note that FieldName may be null for anonymous bitfields. 14711 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14712 IdentifierInfo *FieldName, 14713 QualType FieldTy, bool IsMsStruct, 14714 Expr *BitWidth, bool *ZeroWidth) { 14715 // Default to true; that shouldn't confuse checks for emptiness 14716 if (ZeroWidth) 14717 *ZeroWidth = true; 14718 14719 // C99 6.7.2.1p4 - verify the field type. 14720 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14721 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14722 // Handle incomplete types with specific error. 14723 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14724 return ExprError(); 14725 if (FieldName) 14726 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14727 << FieldName << FieldTy << BitWidth->getSourceRange(); 14728 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14729 << FieldTy << BitWidth->getSourceRange(); 14730 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14731 UPPC_BitFieldWidth)) 14732 return ExprError(); 14733 14734 // If the bit-width is type- or value-dependent, don't try to check 14735 // it now. 14736 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14737 return BitWidth; 14738 14739 llvm::APSInt Value; 14740 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14741 if (ICE.isInvalid()) 14742 return ICE; 14743 BitWidth = ICE.get(); 14744 14745 if (Value != 0 && ZeroWidth) 14746 *ZeroWidth = false; 14747 14748 // Zero-width bitfield is ok for anonymous field. 14749 if (Value == 0 && FieldName) 14750 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14751 14752 if (Value.isSigned() && Value.isNegative()) { 14753 if (FieldName) 14754 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14755 << FieldName << Value.toString(10); 14756 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14757 << Value.toString(10); 14758 } 14759 14760 if (!FieldTy->isDependentType()) { 14761 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14762 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14763 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14764 14765 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14766 // ABI. 14767 bool CStdConstraintViolation = 14768 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14769 bool MSBitfieldViolation = 14770 Value.ugt(TypeStorageSize) && 14771 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14772 if (CStdConstraintViolation || MSBitfieldViolation) { 14773 unsigned DiagWidth = 14774 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14775 if (FieldName) 14776 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14777 << FieldName << (unsigned)Value.getZExtValue() 14778 << !CStdConstraintViolation << DiagWidth; 14779 14780 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14781 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14782 << DiagWidth; 14783 } 14784 14785 // Warn on types where the user might conceivably expect to get all 14786 // specified bits as value bits: that's all integral types other than 14787 // 'bool'. 14788 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14789 if (FieldName) 14790 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14791 << FieldName << (unsigned)Value.getZExtValue() 14792 << (unsigned)TypeWidth; 14793 else 14794 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14795 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14796 } 14797 } 14798 14799 return BitWidth; 14800 } 14801 14802 /// ActOnField - Each field of a C struct/union is passed into this in order 14803 /// to create a FieldDecl object for it. 14804 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14805 Declarator &D, Expr *BitfieldWidth) { 14806 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14807 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14808 /*InitStyle=*/ICIS_NoInit, AS_public); 14809 return Res; 14810 } 14811 14812 /// HandleField - Analyze a field of a C struct or a C++ data member. 14813 /// 14814 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14815 SourceLocation DeclStart, 14816 Declarator &D, Expr *BitWidth, 14817 InClassInitStyle InitStyle, 14818 AccessSpecifier AS) { 14819 if (D.isDecompositionDeclarator()) { 14820 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14821 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14822 << Decomp.getSourceRange(); 14823 return nullptr; 14824 } 14825 14826 IdentifierInfo *II = D.getIdentifier(); 14827 SourceLocation Loc = DeclStart; 14828 if (II) Loc = D.getIdentifierLoc(); 14829 14830 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14831 QualType T = TInfo->getType(); 14832 if (getLangOpts().CPlusPlus) { 14833 CheckExtraCXXDefaultArguments(D); 14834 14835 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14836 UPPC_DataMemberType)) { 14837 D.setInvalidType(); 14838 T = Context.IntTy; 14839 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14840 } 14841 } 14842 14843 // TR 18037 does not allow fields to be declared with address spaces. 14844 if (T.getQualifiers().hasAddressSpace() || 14845 T->isDependentAddressSpaceType() || 14846 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 14847 Diag(Loc, diag::err_field_with_address_space); 14848 D.setInvalidType(); 14849 } 14850 14851 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14852 // used as structure or union field: image, sampler, event or block types. 14853 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14854 T->isSamplerT() || T->isBlockPointerType())) { 14855 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14856 D.setInvalidType(); 14857 } 14858 14859 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14860 14861 if (D.getDeclSpec().isInlineSpecified()) 14862 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14863 << getLangOpts().CPlusPlus17; 14864 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14865 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14866 diag::err_invalid_thread) 14867 << DeclSpec::getSpecifierName(TSCS); 14868 14869 // Check to see if this name was declared as a member previously 14870 NamedDecl *PrevDecl = nullptr; 14871 LookupResult Previous(*this, II, Loc, LookupMemberName, 14872 ForVisibleRedeclaration); 14873 LookupName(Previous, S); 14874 switch (Previous.getResultKind()) { 14875 case LookupResult::Found: 14876 case LookupResult::FoundUnresolvedValue: 14877 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14878 break; 14879 14880 case LookupResult::FoundOverloaded: 14881 PrevDecl = Previous.getRepresentativeDecl(); 14882 break; 14883 14884 case LookupResult::NotFound: 14885 case LookupResult::NotFoundInCurrentInstantiation: 14886 case LookupResult::Ambiguous: 14887 break; 14888 } 14889 Previous.suppressDiagnostics(); 14890 14891 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14892 // Maybe we will complain about the shadowed template parameter. 14893 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14894 // Just pretend that we didn't see the previous declaration. 14895 PrevDecl = nullptr; 14896 } 14897 14898 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14899 PrevDecl = nullptr; 14900 14901 bool Mutable 14902 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14903 SourceLocation TSSL = D.getLocStart(); 14904 FieldDecl *NewFD 14905 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14906 TSSL, AS, PrevDecl, &D); 14907 14908 if (NewFD->isInvalidDecl()) 14909 Record->setInvalidDecl(); 14910 14911 if (D.getDeclSpec().isModulePrivateSpecified()) 14912 NewFD->setModulePrivate(); 14913 14914 if (NewFD->isInvalidDecl() && PrevDecl) { 14915 // Don't introduce NewFD into scope; there's already something 14916 // with the same name in the same scope. 14917 } else if (II) { 14918 PushOnScopeChains(NewFD, S); 14919 } else 14920 Record->addDecl(NewFD); 14921 14922 return NewFD; 14923 } 14924 14925 /// Build a new FieldDecl and check its well-formedness. 14926 /// 14927 /// This routine builds a new FieldDecl given the fields name, type, 14928 /// record, etc. \p PrevDecl should refer to any previous declaration 14929 /// with the same name and in the same scope as the field to be 14930 /// created. 14931 /// 14932 /// \returns a new FieldDecl. 14933 /// 14934 /// \todo The Declarator argument is a hack. It will be removed once 14935 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14936 TypeSourceInfo *TInfo, 14937 RecordDecl *Record, SourceLocation Loc, 14938 bool Mutable, Expr *BitWidth, 14939 InClassInitStyle InitStyle, 14940 SourceLocation TSSL, 14941 AccessSpecifier AS, NamedDecl *PrevDecl, 14942 Declarator *D) { 14943 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14944 bool InvalidDecl = false; 14945 if (D) InvalidDecl = D->isInvalidType(); 14946 14947 // If we receive a broken type, recover by assuming 'int' and 14948 // marking this declaration as invalid. 14949 if (T.isNull()) { 14950 InvalidDecl = true; 14951 T = Context.IntTy; 14952 } 14953 14954 QualType EltTy = Context.getBaseElementType(T); 14955 if (!EltTy->isDependentType()) { 14956 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14957 // Fields of incomplete type force their record to be invalid. 14958 Record->setInvalidDecl(); 14959 InvalidDecl = true; 14960 } else { 14961 NamedDecl *Def; 14962 EltTy->isIncompleteType(&Def); 14963 if (Def && Def->isInvalidDecl()) { 14964 Record->setInvalidDecl(); 14965 InvalidDecl = true; 14966 } 14967 } 14968 } 14969 14970 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14971 if (BitWidth && getLangOpts().OpenCL) { 14972 Diag(Loc, diag::err_opencl_bitfields); 14973 InvalidDecl = true; 14974 } 14975 14976 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 14977 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 14978 T.hasQualifiers()) { 14979 InvalidDecl = true; 14980 Diag(Loc, diag::err_anon_bitfield_qualifiers); 14981 } 14982 14983 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14984 // than a variably modified type. 14985 if (!InvalidDecl && T->isVariablyModifiedType()) { 14986 bool SizeIsNegative; 14987 llvm::APSInt Oversized; 14988 14989 TypeSourceInfo *FixedTInfo = 14990 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14991 SizeIsNegative, 14992 Oversized); 14993 if (FixedTInfo) { 14994 Diag(Loc, diag::warn_illegal_constant_array_size); 14995 TInfo = FixedTInfo; 14996 T = FixedTInfo->getType(); 14997 } else { 14998 if (SizeIsNegative) 14999 Diag(Loc, diag::err_typecheck_negative_array_size); 15000 else if (Oversized.getBoolValue()) 15001 Diag(Loc, diag::err_array_too_large) 15002 << Oversized.toString(10); 15003 else 15004 Diag(Loc, diag::err_typecheck_field_variable_size); 15005 InvalidDecl = true; 15006 } 15007 } 15008 15009 // Fields can not have abstract class types 15010 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 15011 diag::err_abstract_type_in_decl, 15012 AbstractFieldType)) 15013 InvalidDecl = true; 15014 15015 bool ZeroWidth = false; 15016 if (InvalidDecl) 15017 BitWidth = nullptr; 15018 // If this is declared as a bit-field, check the bit-field. 15019 if (BitWidth) { 15020 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 15021 &ZeroWidth).get(); 15022 if (!BitWidth) { 15023 InvalidDecl = true; 15024 BitWidth = nullptr; 15025 ZeroWidth = false; 15026 } 15027 } 15028 15029 // Check that 'mutable' is consistent with the type of the declaration. 15030 if (!InvalidDecl && Mutable) { 15031 unsigned DiagID = 0; 15032 if (T->isReferenceType()) 15033 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 15034 : diag::err_mutable_reference; 15035 else if (T.isConstQualified()) 15036 DiagID = diag::err_mutable_const; 15037 15038 if (DiagID) { 15039 SourceLocation ErrLoc = Loc; 15040 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 15041 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 15042 Diag(ErrLoc, DiagID); 15043 if (DiagID != diag::ext_mutable_reference) { 15044 Mutable = false; 15045 InvalidDecl = true; 15046 } 15047 } 15048 } 15049 15050 // C++11 [class.union]p8 (DR1460): 15051 // At most one variant member of a union may have a 15052 // brace-or-equal-initializer. 15053 if (InitStyle != ICIS_NoInit) 15054 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 15055 15056 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 15057 BitWidth, Mutable, InitStyle); 15058 if (InvalidDecl) 15059 NewFD->setInvalidDecl(); 15060 15061 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 15062 Diag(Loc, diag::err_duplicate_member) << II; 15063 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15064 NewFD->setInvalidDecl(); 15065 } 15066 15067 if (!InvalidDecl && getLangOpts().CPlusPlus) { 15068 if (Record->isUnion()) { 15069 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15070 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15071 if (RDecl->getDefinition()) { 15072 // C++ [class.union]p1: An object of a class with a non-trivial 15073 // constructor, a non-trivial copy constructor, a non-trivial 15074 // destructor, or a non-trivial copy assignment operator 15075 // cannot be a member of a union, nor can an array of such 15076 // objects. 15077 if (CheckNontrivialField(NewFD)) 15078 NewFD->setInvalidDecl(); 15079 } 15080 } 15081 15082 // C++ [class.union]p1: If a union contains a member of reference type, 15083 // the program is ill-formed, except when compiling with MSVC extensions 15084 // enabled. 15085 if (EltTy->isReferenceType()) { 15086 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15087 diag::ext_union_member_of_reference_type : 15088 diag::err_union_member_of_reference_type) 15089 << NewFD->getDeclName() << EltTy; 15090 if (!getLangOpts().MicrosoftExt) 15091 NewFD->setInvalidDecl(); 15092 } 15093 } 15094 } 15095 15096 // FIXME: We need to pass in the attributes given an AST 15097 // representation, not a parser representation. 15098 if (D) { 15099 // FIXME: The current scope is almost... but not entirely... correct here. 15100 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15101 15102 if (NewFD->hasAttrs()) 15103 CheckAlignasUnderalignment(NewFD); 15104 } 15105 15106 // In auto-retain/release, infer strong retension for fields of 15107 // retainable type. 15108 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15109 NewFD->setInvalidDecl(); 15110 15111 if (T.isObjCGCWeak()) 15112 Diag(Loc, diag::warn_attribute_weak_on_field); 15113 15114 NewFD->setAccess(AS); 15115 return NewFD; 15116 } 15117 15118 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15119 assert(FD); 15120 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15121 15122 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15123 return false; 15124 15125 QualType EltTy = Context.getBaseElementType(FD->getType()); 15126 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15127 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15128 if (RDecl->getDefinition()) { 15129 // We check for copy constructors before constructors 15130 // because otherwise we'll never get complaints about 15131 // copy constructors. 15132 15133 CXXSpecialMember member = CXXInvalid; 15134 // We're required to check for any non-trivial constructors. Since the 15135 // implicit default constructor is suppressed if there are any 15136 // user-declared constructors, we just need to check that there is a 15137 // trivial default constructor and a trivial copy constructor. (We don't 15138 // worry about move constructors here, since this is a C++98 check.) 15139 if (RDecl->hasNonTrivialCopyConstructor()) 15140 member = CXXCopyConstructor; 15141 else if (!RDecl->hasTrivialDefaultConstructor()) 15142 member = CXXDefaultConstructor; 15143 else if (RDecl->hasNonTrivialCopyAssignment()) 15144 member = CXXCopyAssignment; 15145 else if (RDecl->hasNonTrivialDestructor()) 15146 member = CXXDestructor; 15147 15148 if (member != CXXInvalid) { 15149 if (!getLangOpts().CPlusPlus11 && 15150 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15151 // Objective-C++ ARC: it is an error to have a non-trivial field of 15152 // a union. However, system headers in Objective-C programs 15153 // occasionally have Objective-C lifetime objects within unions, 15154 // and rather than cause the program to fail, we make those 15155 // members unavailable. 15156 SourceLocation Loc = FD->getLocation(); 15157 if (getSourceManager().isInSystemHeader(Loc)) { 15158 if (!FD->hasAttr<UnavailableAttr>()) 15159 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15160 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15161 return false; 15162 } 15163 } 15164 15165 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15166 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15167 diag::err_illegal_union_or_anon_struct_member) 15168 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15169 DiagnoseNontrivial(RDecl, member); 15170 return !getLangOpts().CPlusPlus11; 15171 } 15172 } 15173 } 15174 15175 return false; 15176 } 15177 15178 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15179 /// AST enum value. 15180 static ObjCIvarDecl::AccessControl 15181 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15182 switch (ivarVisibility) { 15183 default: llvm_unreachable("Unknown visitibility kind"); 15184 case tok::objc_private: return ObjCIvarDecl::Private; 15185 case tok::objc_public: return ObjCIvarDecl::Public; 15186 case tok::objc_protected: return ObjCIvarDecl::Protected; 15187 case tok::objc_package: return ObjCIvarDecl::Package; 15188 } 15189 } 15190 15191 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15192 /// in order to create an IvarDecl object for it. 15193 Decl *Sema::ActOnIvar(Scope *S, 15194 SourceLocation DeclStart, 15195 Declarator &D, Expr *BitfieldWidth, 15196 tok::ObjCKeywordKind Visibility) { 15197 15198 IdentifierInfo *II = D.getIdentifier(); 15199 Expr *BitWidth = (Expr*)BitfieldWidth; 15200 SourceLocation Loc = DeclStart; 15201 if (II) Loc = D.getIdentifierLoc(); 15202 15203 // FIXME: Unnamed fields can be handled in various different ways, for 15204 // example, unnamed unions inject all members into the struct namespace! 15205 15206 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15207 QualType T = TInfo->getType(); 15208 15209 if (BitWidth) { 15210 // 6.7.2.1p3, 6.7.2.1p4 15211 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15212 if (!BitWidth) 15213 D.setInvalidType(); 15214 } else { 15215 // Not a bitfield. 15216 15217 // validate II. 15218 15219 } 15220 if (T->isReferenceType()) { 15221 Diag(Loc, diag::err_ivar_reference_type); 15222 D.setInvalidType(); 15223 } 15224 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15225 // than a variably modified type. 15226 else if (T->isVariablyModifiedType()) { 15227 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15228 D.setInvalidType(); 15229 } 15230 15231 // Get the visibility (access control) for this ivar. 15232 ObjCIvarDecl::AccessControl ac = 15233 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15234 : ObjCIvarDecl::None; 15235 // Must set ivar's DeclContext to its enclosing interface. 15236 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15237 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15238 return nullptr; 15239 ObjCContainerDecl *EnclosingContext; 15240 if (ObjCImplementationDecl *IMPDecl = 15241 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15242 if (LangOpts.ObjCRuntime.isFragile()) { 15243 // Case of ivar declared in an implementation. Context is that of its class. 15244 EnclosingContext = IMPDecl->getClassInterface(); 15245 assert(EnclosingContext && "Implementation has no class interface!"); 15246 } 15247 else 15248 EnclosingContext = EnclosingDecl; 15249 } else { 15250 if (ObjCCategoryDecl *CDecl = 15251 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15252 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15253 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15254 return nullptr; 15255 } 15256 } 15257 EnclosingContext = EnclosingDecl; 15258 } 15259 15260 // Construct the decl. 15261 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15262 DeclStart, Loc, II, T, 15263 TInfo, ac, (Expr *)BitfieldWidth); 15264 15265 if (II) { 15266 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15267 ForVisibleRedeclaration); 15268 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15269 && !isa<TagDecl>(PrevDecl)) { 15270 Diag(Loc, diag::err_duplicate_member) << II; 15271 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15272 NewID->setInvalidDecl(); 15273 } 15274 } 15275 15276 // Process attributes attached to the ivar. 15277 ProcessDeclAttributes(S, NewID, D); 15278 15279 if (D.isInvalidType()) 15280 NewID->setInvalidDecl(); 15281 15282 // In ARC, infer 'retaining' for ivars of retainable type. 15283 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15284 NewID->setInvalidDecl(); 15285 15286 if (D.getDeclSpec().isModulePrivateSpecified()) 15287 NewID->setModulePrivate(); 15288 15289 if (II) { 15290 // FIXME: When interfaces are DeclContexts, we'll need to add 15291 // these to the interface. 15292 S->AddDecl(NewID); 15293 IdResolver.AddDecl(NewID); 15294 } 15295 15296 if (LangOpts.ObjCRuntime.isNonFragile() && 15297 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15298 Diag(Loc, diag::warn_ivars_in_interface); 15299 15300 return NewID; 15301 } 15302 15303 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15304 /// class and class extensions. For every class \@interface and class 15305 /// extension \@interface, if the last ivar is a bitfield of any type, 15306 /// then add an implicit `char :0` ivar to the end of that interface. 15307 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15308 SmallVectorImpl<Decl *> &AllIvarDecls) { 15309 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15310 return; 15311 15312 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15313 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15314 15315 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15316 return; 15317 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15318 if (!ID) { 15319 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15320 if (!CD->IsClassExtension()) 15321 return; 15322 } 15323 // No need to add this to end of @implementation. 15324 else 15325 return; 15326 } 15327 // All conditions are met. Add a new bitfield to the tail end of ivars. 15328 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15329 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15330 15331 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15332 DeclLoc, DeclLoc, nullptr, 15333 Context.CharTy, 15334 Context.getTrivialTypeSourceInfo(Context.CharTy, 15335 DeclLoc), 15336 ObjCIvarDecl::Private, BW, 15337 true); 15338 AllIvarDecls.push_back(Ivar); 15339 } 15340 15341 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15342 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15343 SourceLocation RBrac, AttributeList *Attr) { 15344 assert(EnclosingDecl && "missing record or interface decl"); 15345 15346 // If this is an Objective-C @implementation or category and we have 15347 // new fields here we should reset the layout of the interface since 15348 // it will now change. 15349 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15350 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15351 switch (DC->getKind()) { 15352 default: break; 15353 case Decl::ObjCCategory: 15354 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15355 break; 15356 case Decl::ObjCImplementation: 15357 Context. 15358 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15359 break; 15360 } 15361 } 15362 15363 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15364 15365 // Start counting up the number of named members; make sure to include 15366 // members of anonymous structs and unions in the total. 15367 unsigned NumNamedMembers = 0; 15368 if (Record) { 15369 for (const auto *I : Record->decls()) { 15370 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15371 if (IFD->getDeclName()) 15372 ++NumNamedMembers; 15373 } 15374 } 15375 15376 // Verify that all the fields are okay. 15377 SmallVector<FieldDecl*, 32> RecFields; 15378 15379 bool ObjCFieldLifetimeErrReported = false; 15380 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15381 i != end; ++i) { 15382 FieldDecl *FD = cast<FieldDecl>(*i); 15383 15384 // Get the type for the field. 15385 const Type *FDTy = FD->getType().getTypePtr(); 15386 15387 if (!FD->isAnonymousStructOrUnion()) { 15388 // Remember all fields written by the user. 15389 RecFields.push_back(FD); 15390 } 15391 15392 // If the field is already invalid for some reason, don't emit more 15393 // diagnostics about it. 15394 if (FD->isInvalidDecl()) { 15395 EnclosingDecl->setInvalidDecl(); 15396 continue; 15397 } 15398 15399 // C99 6.7.2.1p2: 15400 // A structure or union shall not contain a member with 15401 // incomplete or function type (hence, a structure shall not 15402 // contain an instance of itself, but may contain a pointer to 15403 // an instance of itself), except that the last member of a 15404 // structure with more than one named member may have incomplete 15405 // array type; such a structure (and any union containing, 15406 // possibly recursively, a member that is such a structure) 15407 // shall not be a member of a structure or an element of an 15408 // array. 15409 bool IsLastField = (i + 1 == Fields.end()); 15410 if (FDTy->isFunctionType()) { 15411 // Field declared as a function. 15412 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15413 << FD->getDeclName(); 15414 FD->setInvalidDecl(); 15415 EnclosingDecl->setInvalidDecl(); 15416 continue; 15417 } else if (FDTy->isIncompleteArrayType() && 15418 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15419 if (Record) { 15420 // Flexible array member. 15421 // Microsoft and g++ is more permissive regarding flexible array. 15422 // It will accept flexible array in union and also 15423 // as the sole element of a struct/class. 15424 unsigned DiagID = 0; 15425 if (!Record->isUnion() && !IsLastField) { 15426 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15427 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15428 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15429 FD->setInvalidDecl(); 15430 EnclosingDecl->setInvalidDecl(); 15431 continue; 15432 } else if (Record->isUnion()) 15433 DiagID = getLangOpts().MicrosoftExt 15434 ? diag::ext_flexible_array_union_ms 15435 : getLangOpts().CPlusPlus 15436 ? diag::ext_flexible_array_union_gnu 15437 : diag::err_flexible_array_union; 15438 else if (NumNamedMembers < 1) 15439 DiagID = getLangOpts().MicrosoftExt 15440 ? diag::ext_flexible_array_empty_aggregate_ms 15441 : getLangOpts().CPlusPlus 15442 ? diag::ext_flexible_array_empty_aggregate_gnu 15443 : diag::err_flexible_array_empty_aggregate; 15444 15445 if (DiagID) 15446 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15447 << Record->getTagKind(); 15448 // While the layout of types that contain virtual bases is not specified 15449 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15450 // virtual bases after the derived members. This would make a flexible 15451 // array member declared at the end of an object not adjacent to the end 15452 // of the type. 15453 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 15454 if (RD->getNumVBases() != 0) 15455 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15456 << FD->getDeclName() << Record->getTagKind(); 15457 if (!getLangOpts().C99) 15458 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15459 << FD->getDeclName() << Record->getTagKind(); 15460 15461 // If the element type has a non-trivial destructor, we would not 15462 // implicitly destroy the elements, so disallow it for now. 15463 // 15464 // FIXME: GCC allows this. We should probably either implicitly delete 15465 // the destructor of the containing class, or just allow this. 15466 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15467 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15468 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15469 << FD->getDeclName() << FD->getType(); 15470 FD->setInvalidDecl(); 15471 EnclosingDecl->setInvalidDecl(); 15472 continue; 15473 } 15474 // Okay, we have a legal flexible array member at the end of the struct. 15475 Record->setHasFlexibleArrayMember(true); 15476 } else { 15477 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15478 // unless they are followed by another ivar. That check is done 15479 // elsewhere, after synthesized ivars are known. 15480 } 15481 } else if (!FDTy->isDependentType() && 15482 RequireCompleteType(FD->getLocation(), FD->getType(), 15483 diag::err_field_incomplete)) { 15484 // Incomplete type 15485 FD->setInvalidDecl(); 15486 EnclosingDecl->setInvalidDecl(); 15487 continue; 15488 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15489 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15490 // A type which contains a flexible array member is considered to be a 15491 // flexible array member. 15492 Record->setHasFlexibleArrayMember(true); 15493 if (!Record->isUnion()) { 15494 // If this is a struct/class and this is not the last element, reject 15495 // it. Note that GCC supports variable sized arrays in the middle of 15496 // structures. 15497 if (!IsLastField) 15498 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15499 << FD->getDeclName() << FD->getType(); 15500 else { 15501 // We support flexible arrays at the end of structs in 15502 // other structs as an extension. 15503 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15504 << FD->getDeclName(); 15505 } 15506 } 15507 } 15508 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15509 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15510 diag::err_abstract_type_in_decl, 15511 AbstractIvarType)) { 15512 // Ivars can not have abstract class types 15513 FD->setInvalidDecl(); 15514 } 15515 if (Record && FDTTy->getDecl()->hasObjectMember()) 15516 Record->setHasObjectMember(true); 15517 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15518 Record->setHasVolatileMember(true); 15519 } else if (FDTy->isObjCObjectType()) { 15520 /// A field cannot be an Objective-c object 15521 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15522 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15523 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15524 FD->setType(T); 15525 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15526 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { 15527 // It's an error in ARC or Weak if a field has lifetime. 15528 // We don't want to report this in a system header, though, 15529 // so we just make the field unavailable. 15530 // FIXME: that's really not sufficient; we need to make the type 15531 // itself invalid to, say, initialize or copy. 15532 QualType T = FD->getType(); 15533 if (T.hasNonTrivialObjCLifetime()) { 15534 SourceLocation loc = FD->getLocation(); 15535 if (getSourceManager().isInSystemHeader(loc)) { 15536 if (!FD->hasAttr<UnavailableAttr>()) { 15537 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15538 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15539 } 15540 } else { 15541 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15542 << T->isBlockPointerType() << Record->getTagKind(); 15543 } 15544 ObjCFieldLifetimeErrReported = true; 15545 } 15546 } else if (getLangOpts().ObjC1 && 15547 getLangOpts().getGC() != LangOptions::NonGC && 15548 Record && !Record->hasObjectMember()) { 15549 if (FD->getType()->isObjCObjectPointerType() || 15550 FD->getType().isObjCGCStrong()) 15551 Record->setHasObjectMember(true); 15552 else if (Context.getAsArrayType(FD->getType())) { 15553 QualType BaseType = Context.getBaseElementType(FD->getType()); 15554 if (BaseType->isRecordType() && 15555 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15556 Record->setHasObjectMember(true); 15557 else if (BaseType->isObjCObjectPointerType() || 15558 BaseType.isObjCGCStrong()) 15559 Record->setHasObjectMember(true); 15560 } 15561 } 15562 15563 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 15564 QualType FT = FD->getType(); 15565 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 15566 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 15567 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 15568 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 15569 Record->setNonTrivialToPrimitiveCopy(true); 15570 if (FT.isDestructedType()) { 15571 Record->setNonTrivialToPrimitiveDestroy(true); 15572 Record->setParamDestroyedInCallee(true); 15573 } 15574 15575 if (const auto *RT = FT->getAs<RecordType>()) { 15576 if (RT->getDecl()->getArgPassingRestrictions() == 15577 RecordDecl::APK_CanNeverPassInRegs) 15578 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15579 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 15580 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15581 } 15582 15583 if (Record && FD->getType().isVolatileQualified()) 15584 Record->setHasVolatileMember(true); 15585 // Keep track of the number of named members. 15586 if (FD->getIdentifier()) 15587 ++NumNamedMembers; 15588 } 15589 15590 // Okay, we successfully defined 'Record'. 15591 if (Record) { 15592 bool Completed = false; 15593 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15594 if (!CXXRecord->isInvalidDecl()) { 15595 // Set access bits correctly on the directly-declared conversions. 15596 for (CXXRecordDecl::conversion_iterator 15597 I = CXXRecord->conversion_begin(), 15598 E = CXXRecord->conversion_end(); I != E; ++I) 15599 I.setAccess((*I)->getAccess()); 15600 } 15601 15602 if (!CXXRecord->isDependentType()) { 15603 if (CXXRecord->hasUserDeclaredDestructor()) { 15604 // Adjust user-defined destructor exception spec. 15605 if (getLangOpts().CPlusPlus11) 15606 AdjustDestructorExceptionSpec(CXXRecord, 15607 CXXRecord->getDestructor()); 15608 } 15609 15610 // Add any implicitly-declared members to this class. 15611 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15612 15613 if (!CXXRecord->isInvalidDecl()) { 15614 // If we have virtual base classes, we may end up finding multiple 15615 // final overriders for a given virtual function. Check for this 15616 // problem now. 15617 if (CXXRecord->getNumVBases()) { 15618 CXXFinalOverriderMap FinalOverriders; 15619 CXXRecord->getFinalOverriders(FinalOverriders); 15620 15621 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15622 MEnd = FinalOverriders.end(); 15623 M != MEnd; ++M) { 15624 for (OverridingMethods::iterator SO = M->second.begin(), 15625 SOEnd = M->second.end(); 15626 SO != SOEnd; ++SO) { 15627 assert(SO->second.size() > 0 && 15628 "Virtual function without overriding functions?"); 15629 if (SO->second.size() == 1) 15630 continue; 15631 15632 // C++ [class.virtual]p2: 15633 // In a derived class, if a virtual member function of a base 15634 // class subobject has more than one final overrider the 15635 // program is ill-formed. 15636 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15637 << (const NamedDecl *)M->first << Record; 15638 Diag(M->first->getLocation(), 15639 diag::note_overridden_virtual_function); 15640 for (OverridingMethods::overriding_iterator 15641 OM = SO->second.begin(), 15642 OMEnd = SO->second.end(); 15643 OM != OMEnd; ++OM) 15644 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15645 << (const NamedDecl *)M->first << OM->Method->getParent(); 15646 15647 Record->setInvalidDecl(); 15648 } 15649 } 15650 CXXRecord->completeDefinition(&FinalOverriders); 15651 Completed = true; 15652 } 15653 } 15654 } 15655 } 15656 15657 if (!Completed) 15658 Record->completeDefinition(); 15659 15660 // We may have deferred checking for a deleted destructor. Check now. 15661 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15662 auto *Dtor = CXXRecord->getDestructor(); 15663 if (Dtor && Dtor->isImplicit() && 15664 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 15665 CXXRecord->setImplicitDestructorIsDeleted(); 15666 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15667 } 15668 } 15669 15670 if (Record->hasAttrs()) { 15671 CheckAlignasUnderalignment(Record); 15672 15673 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15674 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15675 IA->getRange(), IA->getBestCase(), 15676 IA->getSemanticSpelling()); 15677 } 15678 15679 // Check if the structure/union declaration is a type that can have zero 15680 // size in C. For C this is a language extension, for C++ it may cause 15681 // compatibility problems. 15682 bool CheckForZeroSize; 15683 if (!getLangOpts().CPlusPlus) { 15684 CheckForZeroSize = true; 15685 } else { 15686 // For C++ filter out types that cannot be referenced in C code. 15687 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15688 CheckForZeroSize = 15689 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15690 !CXXRecord->isDependentType() && 15691 CXXRecord->isCLike(); 15692 } 15693 if (CheckForZeroSize) { 15694 bool ZeroSize = true; 15695 bool IsEmpty = true; 15696 unsigned NonBitFields = 0; 15697 for (RecordDecl::field_iterator I = Record->field_begin(), 15698 E = Record->field_end(); 15699 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15700 IsEmpty = false; 15701 if (I->isUnnamedBitfield()) { 15702 if (!I->isZeroLengthBitField(Context)) 15703 ZeroSize = false; 15704 } else { 15705 ++NonBitFields; 15706 QualType FieldType = I->getType(); 15707 if (FieldType->isIncompleteType() || 15708 !Context.getTypeSizeInChars(FieldType).isZero()) 15709 ZeroSize = false; 15710 } 15711 } 15712 15713 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15714 // allowed in C++, but warn if its declaration is inside 15715 // extern "C" block. 15716 if (ZeroSize) { 15717 Diag(RecLoc, getLangOpts().CPlusPlus ? 15718 diag::warn_zero_size_struct_union_in_extern_c : 15719 diag::warn_zero_size_struct_union_compat) 15720 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15721 } 15722 15723 // Structs without named members are extension in C (C99 6.7.2.1p7), 15724 // but are accepted by GCC. 15725 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15726 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15727 diag::ext_no_named_members_in_struct_union) 15728 << Record->isUnion(); 15729 } 15730 } 15731 } else { 15732 ObjCIvarDecl **ClsFields = 15733 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15734 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15735 ID->setEndOfDefinitionLoc(RBrac); 15736 // Add ivar's to class's DeclContext. 15737 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15738 ClsFields[i]->setLexicalDeclContext(ID); 15739 ID->addDecl(ClsFields[i]); 15740 } 15741 // Must enforce the rule that ivars in the base classes may not be 15742 // duplicates. 15743 if (ID->getSuperClass()) 15744 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15745 } else if (ObjCImplementationDecl *IMPDecl = 15746 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15747 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15748 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15749 // Ivar declared in @implementation never belongs to the implementation. 15750 // Only it is in implementation's lexical context. 15751 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15752 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15753 IMPDecl->setIvarLBraceLoc(LBrac); 15754 IMPDecl->setIvarRBraceLoc(RBrac); 15755 } else if (ObjCCategoryDecl *CDecl = 15756 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15757 // case of ivars in class extension; all other cases have been 15758 // reported as errors elsewhere. 15759 // FIXME. Class extension does not have a LocEnd field. 15760 // CDecl->setLocEnd(RBrac); 15761 // Add ivar's to class extension's DeclContext. 15762 // Diagnose redeclaration of private ivars. 15763 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15764 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15765 if (IDecl) { 15766 if (const ObjCIvarDecl *ClsIvar = 15767 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15768 Diag(ClsFields[i]->getLocation(), 15769 diag::err_duplicate_ivar_declaration); 15770 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15771 continue; 15772 } 15773 for (const auto *Ext : IDecl->known_extensions()) { 15774 if (const ObjCIvarDecl *ClsExtIvar 15775 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15776 Diag(ClsFields[i]->getLocation(), 15777 diag::err_duplicate_ivar_declaration); 15778 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15779 continue; 15780 } 15781 } 15782 } 15783 ClsFields[i]->setLexicalDeclContext(CDecl); 15784 CDecl->addDecl(ClsFields[i]); 15785 } 15786 CDecl->setIvarLBraceLoc(LBrac); 15787 CDecl->setIvarRBraceLoc(RBrac); 15788 } 15789 } 15790 15791 if (Attr) 15792 ProcessDeclAttributeList(S, Record, Attr); 15793 } 15794 15795 /// Determine whether the given integral value is representable within 15796 /// the given type T. 15797 static bool isRepresentableIntegerValue(ASTContext &Context, 15798 llvm::APSInt &Value, 15799 QualType T) { 15800 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 15801 "Integral type required!"); 15802 unsigned BitWidth = Context.getIntWidth(T); 15803 15804 if (Value.isUnsigned() || Value.isNonNegative()) { 15805 if (T->isSignedIntegerOrEnumerationType()) 15806 --BitWidth; 15807 return Value.getActiveBits() <= BitWidth; 15808 } 15809 return Value.getMinSignedBits() <= BitWidth; 15810 } 15811 15812 // Given an integral type, return the next larger integral type 15813 // (or a NULL type of no such type exists). 15814 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15815 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15816 // enum checking below. 15817 assert((T->isIntegralType(Context) || 15818 T->isEnumeralType()) && "Integral type required!"); 15819 const unsigned NumTypes = 4; 15820 QualType SignedIntegralTypes[NumTypes] = { 15821 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15822 }; 15823 QualType UnsignedIntegralTypes[NumTypes] = { 15824 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15825 Context.UnsignedLongLongTy 15826 }; 15827 15828 unsigned BitWidth = Context.getTypeSize(T); 15829 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15830 : UnsignedIntegralTypes; 15831 for (unsigned I = 0; I != NumTypes; ++I) 15832 if (Context.getTypeSize(Types[I]) > BitWidth) 15833 return Types[I]; 15834 15835 return QualType(); 15836 } 15837 15838 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15839 EnumConstantDecl *LastEnumConst, 15840 SourceLocation IdLoc, 15841 IdentifierInfo *Id, 15842 Expr *Val) { 15843 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15844 llvm::APSInt EnumVal(IntWidth); 15845 QualType EltTy; 15846 15847 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15848 Val = nullptr; 15849 15850 if (Val) 15851 Val = DefaultLvalueConversion(Val).get(); 15852 15853 if (Val) { 15854 if (Enum->isDependentType() || Val->isTypeDependent()) 15855 EltTy = Context.DependentTy; 15856 else { 15857 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15858 !getLangOpts().MSVCCompat) { 15859 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15860 // constant-expression in the enumerator-definition shall be a converted 15861 // constant expression of the underlying type. 15862 EltTy = Enum->getIntegerType(); 15863 ExprResult Converted = 15864 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15865 CCEK_Enumerator); 15866 if (Converted.isInvalid()) 15867 Val = nullptr; 15868 else 15869 Val = Converted.get(); 15870 } else if (!Val->isValueDependent() && 15871 !(Val = VerifyIntegerConstantExpression(Val, 15872 &EnumVal).get())) { 15873 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15874 } else { 15875 if (Enum->isComplete()) { 15876 EltTy = Enum->getIntegerType(); 15877 15878 // In Obj-C and Microsoft mode, require the enumeration value to be 15879 // representable in the underlying type of the enumeration. In C++11, 15880 // we perform a non-narrowing conversion as part of converted constant 15881 // expression checking. 15882 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15883 if (getLangOpts().MSVCCompat) { 15884 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15885 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15886 } else 15887 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15888 } else 15889 Val = ImpCastExprToType(Val, EltTy, 15890 EltTy->isBooleanType() ? 15891 CK_IntegralToBoolean : CK_IntegralCast) 15892 .get(); 15893 } else if (getLangOpts().CPlusPlus) { 15894 // C++11 [dcl.enum]p5: 15895 // If the underlying type is not fixed, the type of each enumerator 15896 // is the type of its initializing value: 15897 // - If an initializer is specified for an enumerator, the 15898 // initializing value has the same type as the expression. 15899 EltTy = Val->getType(); 15900 } else { 15901 // C99 6.7.2.2p2: 15902 // The expression that defines the value of an enumeration constant 15903 // shall be an integer constant expression that has a value 15904 // representable as an int. 15905 15906 // Complain if the value is not representable in an int. 15907 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15908 Diag(IdLoc, diag::ext_enum_value_not_int) 15909 << EnumVal.toString(10) << Val->getSourceRange() 15910 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15911 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15912 // Force the type of the expression to 'int'. 15913 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15914 } 15915 EltTy = Val->getType(); 15916 } 15917 } 15918 } 15919 } 15920 15921 if (!Val) { 15922 if (Enum->isDependentType()) 15923 EltTy = Context.DependentTy; 15924 else if (!LastEnumConst) { 15925 // C++0x [dcl.enum]p5: 15926 // If the underlying type is not fixed, the type of each enumerator 15927 // is the type of its initializing value: 15928 // - If no initializer is specified for the first enumerator, the 15929 // initializing value has an unspecified integral type. 15930 // 15931 // GCC uses 'int' for its unspecified integral type, as does 15932 // C99 6.7.2.2p3. 15933 if (Enum->isFixed()) { 15934 EltTy = Enum->getIntegerType(); 15935 } 15936 else { 15937 EltTy = Context.IntTy; 15938 } 15939 } else { 15940 // Assign the last value + 1. 15941 EnumVal = LastEnumConst->getInitVal(); 15942 ++EnumVal; 15943 EltTy = LastEnumConst->getType(); 15944 15945 // Check for overflow on increment. 15946 if (EnumVal < LastEnumConst->getInitVal()) { 15947 // C++0x [dcl.enum]p5: 15948 // If the underlying type is not fixed, the type of each enumerator 15949 // is the type of its initializing value: 15950 // 15951 // - Otherwise the type of the initializing value is the same as 15952 // the type of the initializing value of the preceding enumerator 15953 // unless the incremented value is not representable in that type, 15954 // in which case the type is an unspecified integral type 15955 // sufficient to contain the incremented value. If no such type 15956 // exists, the program is ill-formed. 15957 QualType T = getNextLargerIntegralType(Context, EltTy); 15958 if (T.isNull() || Enum->isFixed()) { 15959 // There is no integral type larger enough to represent this 15960 // value. Complain, then allow the value to wrap around. 15961 EnumVal = LastEnumConst->getInitVal(); 15962 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15963 ++EnumVal; 15964 if (Enum->isFixed()) 15965 // When the underlying type is fixed, this is ill-formed. 15966 Diag(IdLoc, diag::err_enumerator_wrapped) 15967 << EnumVal.toString(10) 15968 << EltTy; 15969 else 15970 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15971 << EnumVal.toString(10); 15972 } else { 15973 EltTy = T; 15974 } 15975 15976 // Retrieve the last enumerator's value, extent that type to the 15977 // type that is supposed to be large enough to represent the incremented 15978 // value, then increment. 15979 EnumVal = LastEnumConst->getInitVal(); 15980 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15981 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15982 ++EnumVal; 15983 15984 // If we're not in C++, diagnose the overflow of enumerator values, 15985 // which in C99 means that the enumerator value is not representable in 15986 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15987 // permits enumerator values that are representable in some larger 15988 // integral type. 15989 if (!getLangOpts().CPlusPlus && !T.isNull()) 15990 Diag(IdLoc, diag::warn_enum_value_overflow); 15991 } else if (!getLangOpts().CPlusPlus && 15992 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15993 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15994 Diag(IdLoc, diag::ext_enum_value_not_int) 15995 << EnumVal.toString(10) << 1; 15996 } 15997 } 15998 } 15999 16000 if (!EltTy->isDependentType()) { 16001 // Make the enumerator value match the signedness and size of the 16002 // enumerator's type. 16003 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 16004 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16005 } 16006 16007 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 16008 Val, EnumVal); 16009 } 16010 16011 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 16012 SourceLocation IILoc) { 16013 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 16014 !getLangOpts().CPlusPlus) 16015 return SkipBodyInfo(); 16016 16017 // We have an anonymous enum definition. Look up the first enumerator to 16018 // determine if we should merge the definition with an existing one and 16019 // skip the body. 16020 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 16021 forRedeclarationInCurContext()); 16022 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 16023 if (!PrevECD) 16024 return SkipBodyInfo(); 16025 16026 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 16027 NamedDecl *Hidden; 16028 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 16029 SkipBodyInfo Skip; 16030 Skip.Previous = Hidden; 16031 return Skip; 16032 } 16033 16034 return SkipBodyInfo(); 16035 } 16036 16037 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 16038 SourceLocation IdLoc, IdentifierInfo *Id, 16039 AttributeList *Attr, 16040 SourceLocation EqualLoc, Expr *Val) { 16041 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 16042 EnumConstantDecl *LastEnumConst = 16043 cast_or_null<EnumConstantDecl>(lastEnumConst); 16044 16045 // The scope passed in may not be a decl scope. Zip up the scope tree until 16046 // we find one that is. 16047 S = getNonFieldDeclScope(S); 16048 16049 // Verify that there isn't already something declared with this name in this 16050 // scope. 16051 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 16052 ForVisibleRedeclaration); 16053 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16054 // Maybe we will complain about the shadowed template parameter. 16055 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 16056 // Just pretend that we didn't see the previous declaration. 16057 PrevDecl = nullptr; 16058 } 16059 16060 // C++ [class.mem]p15: 16061 // If T is the name of a class, then each of the following shall have a name 16062 // different from T: 16063 // - every enumerator of every member of class T that is an unscoped 16064 // enumerated type 16065 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 16066 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 16067 DeclarationNameInfo(Id, IdLoc)); 16068 16069 EnumConstantDecl *New = 16070 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 16071 if (!New) 16072 return nullptr; 16073 16074 if (PrevDecl) { 16075 // When in C++, we may get a TagDecl with the same name; in this case the 16076 // enum constant will 'hide' the tag. 16077 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 16078 "Received TagDecl when not in C++!"); 16079 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 16080 if (isa<EnumConstantDecl>(PrevDecl)) 16081 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 16082 else 16083 Diag(IdLoc, diag::err_redefinition) << Id; 16084 notePreviousDefinition(PrevDecl, IdLoc); 16085 return nullptr; 16086 } 16087 } 16088 16089 // Process attributes. 16090 if (Attr) ProcessDeclAttributeList(S, New, Attr); 16091 AddPragmaAttributes(S, New); 16092 16093 // Register this decl in the current scope stack. 16094 New->setAccess(TheEnumDecl->getAccess()); 16095 PushOnScopeChains(New, S); 16096 16097 ActOnDocumentableDecl(New); 16098 16099 return New; 16100 } 16101 16102 // Returns true when the enum initial expression does not trigger the 16103 // duplicate enum warning. A few common cases are exempted as follows: 16104 // Element2 = Element1 16105 // Element2 = Element1 + 1 16106 // Element2 = Element1 - 1 16107 // Where Element2 and Element1 are from the same enum. 16108 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16109 Expr *InitExpr = ECD->getInitExpr(); 16110 if (!InitExpr) 16111 return true; 16112 InitExpr = InitExpr->IgnoreImpCasts(); 16113 16114 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16115 if (!BO->isAdditiveOp()) 16116 return true; 16117 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16118 if (!IL) 16119 return true; 16120 if (IL->getValue() != 1) 16121 return true; 16122 16123 InitExpr = BO->getLHS(); 16124 } 16125 16126 // This checks if the elements are from the same enum. 16127 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16128 if (!DRE) 16129 return true; 16130 16131 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16132 if (!EnumConstant) 16133 return true; 16134 16135 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16136 Enum) 16137 return true; 16138 16139 return false; 16140 } 16141 16142 // Emits a warning when an element is implicitly set a value that 16143 // a previous element has already been set to. 16144 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16145 EnumDecl *Enum, QualType EnumType) { 16146 // Avoid anonymous enums 16147 if (!Enum->getIdentifier()) 16148 return; 16149 16150 // Only check for small enums. 16151 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16152 return; 16153 16154 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16155 return; 16156 16157 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16158 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16159 16160 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16161 typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap; 16162 16163 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16164 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16165 llvm::APSInt Val = D->getInitVal(); 16166 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16167 }; 16168 16169 DuplicatesVector DupVector; 16170 ValueToVectorMap EnumMap; 16171 16172 // Populate the EnumMap with all values represented by enum constants without 16173 // an initializer. 16174 for (auto *Element : Elements) { 16175 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16176 16177 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16178 // this constant. Skip this enum since it may be ill-formed. 16179 if (!ECD) { 16180 return; 16181 } 16182 16183 // Constants with initalizers are handled in the next loop. 16184 if (ECD->getInitExpr()) 16185 continue; 16186 16187 // Duplicate values are handled in the next loop. 16188 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16189 } 16190 16191 if (EnumMap.size() == 0) 16192 return; 16193 16194 // Create vectors for any values that has duplicates. 16195 for (auto *Element : Elements) { 16196 // The last loop returned if any constant was null. 16197 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16198 if (!ValidDuplicateEnum(ECD, Enum)) 16199 continue; 16200 16201 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16202 if (Iter == EnumMap.end()) 16203 continue; 16204 16205 DeclOrVector& Entry = Iter->second; 16206 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16207 // Ensure constants are different. 16208 if (D == ECD) 16209 continue; 16210 16211 // Create new vector and push values onto it. 16212 auto Vec = llvm::make_unique<ECDVector>(); 16213 Vec->push_back(D); 16214 Vec->push_back(ECD); 16215 16216 // Update entry to point to the duplicates vector. 16217 Entry = Vec.get(); 16218 16219 // Store the vector somewhere we can consult later for quick emission of 16220 // diagnostics. 16221 DupVector.emplace_back(std::move(Vec)); 16222 continue; 16223 } 16224 16225 ECDVector *Vec = Entry.get<ECDVector*>(); 16226 // Make sure constants are not added more than once. 16227 if (*Vec->begin() == ECD) 16228 continue; 16229 16230 Vec->push_back(ECD); 16231 } 16232 16233 // Emit diagnostics. 16234 for (const auto &Vec : DupVector) { 16235 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16236 16237 // Emit warning for one enum constant. 16238 auto *FirstECD = Vec->front(); 16239 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16240 << FirstECD << FirstECD->getInitVal().toString(10) 16241 << FirstECD->getSourceRange(); 16242 16243 // Emit one note for each of the remaining enum constants with 16244 // the same value. 16245 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16246 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16247 << ECD << ECD->getInitVal().toString(10) 16248 << ECD->getSourceRange(); 16249 } 16250 } 16251 16252 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16253 bool AllowMask) const { 16254 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16255 assert(ED->isCompleteDefinition() && "expected enum definition"); 16256 16257 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16258 llvm::APInt &FlagBits = R.first->second; 16259 16260 if (R.second) { 16261 for (auto *E : ED->enumerators()) { 16262 const auto &EVal = E->getInitVal(); 16263 // Only single-bit enumerators introduce new flag values. 16264 if (EVal.isPowerOf2()) 16265 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16266 } 16267 } 16268 16269 // A value is in a flag enum if either its bits are a subset of the enum's 16270 // flag bits (the first condition) or we are allowing masks and the same is 16271 // true of its complement (the second condition). When masks are allowed, we 16272 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16273 // 16274 // While it's true that any value could be used as a mask, the assumption is 16275 // that a mask will have all of the insignificant bits set. Anything else is 16276 // likely a logic error. 16277 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16278 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16279 } 16280 16281 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16282 Decl *EnumDeclX, 16283 ArrayRef<Decl *> Elements, 16284 Scope *S, AttributeList *Attr) { 16285 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16286 QualType EnumType = Context.getTypeDeclType(Enum); 16287 16288 if (Attr) 16289 ProcessDeclAttributeList(S, Enum, Attr); 16290 16291 if (Enum->isDependentType()) { 16292 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16293 EnumConstantDecl *ECD = 16294 cast_or_null<EnumConstantDecl>(Elements[i]); 16295 if (!ECD) continue; 16296 16297 ECD->setType(EnumType); 16298 } 16299 16300 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16301 return; 16302 } 16303 16304 // TODO: If the result value doesn't fit in an int, it must be a long or long 16305 // long value. ISO C does not support this, but GCC does as an extension, 16306 // emit a warning. 16307 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16308 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16309 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16310 16311 // Verify that all the values are okay, compute the size of the values, and 16312 // reverse the list. 16313 unsigned NumNegativeBits = 0; 16314 unsigned NumPositiveBits = 0; 16315 16316 // Keep track of whether all elements have type int. 16317 bool AllElementsInt = true; 16318 16319 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16320 EnumConstantDecl *ECD = 16321 cast_or_null<EnumConstantDecl>(Elements[i]); 16322 if (!ECD) continue; // Already issued a diagnostic. 16323 16324 const llvm::APSInt &InitVal = ECD->getInitVal(); 16325 16326 // Keep track of the size of positive and negative values. 16327 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16328 NumPositiveBits = std::max(NumPositiveBits, 16329 (unsigned)InitVal.getActiveBits()); 16330 else 16331 NumNegativeBits = std::max(NumNegativeBits, 16332 (unsigned)InitVal.getMinSignedBits()); 16333 16334 // Keep track of whether every enum element has type int (very commmon). 16335 if (AllElementsInt) 16336 AllElementsInt = ECD->getType() == Context.IntTy; 16337 } 16338 16339 // Figure out the type that should be used for this enum. 16340 QualType BestType; 16341 unsigned BestWidth; 16342 16343 // C++0x N3000 [conv.prom]p3: 16344 // An rvalue of an unscoped enumeration type whose underlying 16345 // type is not fixed can be converted to an rvalue of the first 16346 // of the following types that can represent all the values of 16347 // the enumeration: int, unsigned int, long int, unsigned long 16348 // int, long long int, or unsigned long long int. 16349 // C99 6.4.4.3p2: 16350 // An identifier declared as an enumeration constant has type int. 16351 // The C99 rule is modified by a gcc extension 16352 QualType BestPromotionType; 16353 16354 bool Packed = Enum->hasAttr<PackedAttr>(); 16355 // -fshort-enums is the equivalent to specifying the packed attribute on all 16356 // enum definitions. 16357 if (LangOpts.ShortEnums) 16358 Packed = true; 16359 16360 // If the enum already has a type because it is fixed or dictated by the 16361 // target, promote that type instead of analyzing the enumerators. 16362 if (Enum->isComplete()) { 16363 BestType = Enum->getIntegerType(); 16364 if (BestType->isPromotableIntegerType()) 16365 BestPromotionType = Context.getPromotedIntegerType(BestType); 16366 else 16367 BestPromotionType = BestType; 16368 16369 BestWidth = Context.getIntWidth(BestType); 16370 } 16371 else if (NumNegativeBits) { 16372 // If there is a negative value, figure out the smallest integer type (of 16373 // int/long/longlong) that fits. 16374 // If it's packed, check also if it fits a char or a short. 16375 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16376 BestType = Context.SignedCharTy; 16377 BestWidth = CharWidth; 16378 } else if (Packed && NumNegativeBits <= ShortWidth && 16379 NumPositiveBits < ShortWidth) { 16380 BestType = Context.ShortTy; 16381 BestWidth = ShortWidth; 16382 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16383 BestType = Context.IntTy; 16384 BestWidth = IntWidth; 16385 } else { 16386 BestWidth = Context.getTargetInfo().getLongWidth(); 16387 16388 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16389 BestType = Context.LongTy; 16390 } else { 16391 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16392 16393 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16394 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16395 BestType = Context.LongLongTy; 16396 } 16397 } 16398 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16399 } else { 16400 // If there is no negative value, figure out the smallest type that fits 16401 // all of the enumerator values. 16402 // If it's packed, check also if it fits a char or a short. 16403 if (Packed && NumPositiveBits <= CharWidth) { 16404 BestType = Context.UnsignedCharTy; 16405 BestPromotionType = Context.IntTy; 16406 BestWidth = CharWidth; 16407 } else if (Packed && NumPositiveBits <= ShortWidth) { 16408 BestType = Context.UnsignedShortTy; 16409 BestPromotionType = Context.IntTy; 16410 BestWidth = ShortWidth; 16411 } else if (NumPositiveBits <= IntWidth) { 16412 BestType = Context.UnsignedIntTy; 16413 BestWidth = IntWidth; 16414 BestPromotionType 16415 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16416 ? Context.UnsignedIntTy : Context.IntTy; 16417 } else if (NumPositiveBits <= 16418 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16419 BestType = Context.UnsignedLongTy; 16420 BestPromotionType 16421 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16422 ? Context.UnsignedLongTy : Context.LongTy; 16423 } else { 16424 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16425 assert(NumPositiveBits <= BestWidth && 16426 "How could an initializer get larger than ULL?"); 16427 BestType = Context.UnsignedLongLongTy; 16428 BestPromotionType 16429 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16430 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16431 } 16432 } 16433 16434 // Loop over all of the enumerator constants, changing their types to match 16435 // the type of the enum if needed. 16436 for (auto *D : Elements) { 16437 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16438 if (!ECD) continue; // Already issued a diagnostic. 16439 16440 // Standard C says the enumerators have int type, but we allow, as an 16441 // extension, the enumerators to be larger than int size. If each 16442 // enumerator value fits in an int, type it as an int, otherwise type it the 16443 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16444 // that X has type 'int', not 'unsigned'. 16445 16446 // Determine whether the value fits into an int. 16447 llvm::APSInt InitVal = ECD->getInitVal(); 16448 16449 // If it fits into an integer type, force it. Otherwise force it to match 16450 // the enum decl type. 16451 QualType NewTy; 16452 unsigned NewWidth; 16453 bool NewSign; 16454 if (!getLangOpts().CPlusPlus && 16455 !Enum->isFixed() && 16456 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16457 NewTy = Context.IntTy; 16458 NewWidth = IntWidth; 16459 NewSign = true; 16460 } else if (ECD->getType() == BestType) { 16461 // Already the right type! 16462 if (getLangOpts().CPlusPlus) 16463 // C++ [dcl.enum]p4: Following the closing brace of an 16464 // enum-specifier, each enumerator has the type of its 16465 // enumeration. 16466 ECD->setType(EnumType); 16467 continue; 16468 } else { 16469 NewTy = BestType; 16470 NewWidth = BestWidth; 16471 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16472 } 16473 16474 // Adjust the APSInt value. 16475 InitVal = InitVal.extOrTrunc(NewWidth); 16476 InitVal.setIsSigned(NewSign); 16477 ECD->setInitVal(InitVal); 16478 16479 // Adjust the Expr initializer and type. 16480 if (ECD->getInitExpr() && 16481 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16482 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16483 CK_IntegralCast, 16484 ECD->getInitExpr(), 16485 /*base paths*/ nullptr, 16486 VK_RValue)); 16487 if (getLangOpts().CPlusPlus) 16488 // C++ [dcl.enum]p4: Following the closing brace of an 16489 // enum-specifier, each enumerator has the type of its 16490 // enumeration. 16491 ECD->setType(EnumType); 16492 else 16493 ECD->setType(NewTy); 16494 } 16495 16496 Enum->completeDefinition(BestType, BestPromotionType, 16497 NumPositiveBits, NumNegativeBits); 16498 16499 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16500 16501 if (Enum->isClosedFlag()) { 16502 for (Decl *D : Elements) { 16503 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16504 if (!ECD) continue; // Already issued a diagnostic. 16505 16506 llvm::APSInt InitVal = ECD->getInitVal(); 16507 if (InitVal != 0 && !InitVal.isPowerOf2() && 16508 !IsValueInFlagEnum(Enum, InitVal, true)) 16509 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16510 << ECD << Enum; 16511 } 16512 } 16513 16514 // Now that the enum type is defined, ensure it's not been underaligned. 16515 if (Enum->hasAttrs()) 16516 CheckAlignasUnderalignment(Enum); 16517 } 16518 16519 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16520 SourceLocation StartLoc, 16521 SourceLocation EndLoc) { 16522 StringLiteral *AsmString = cast<StringLiteral>(expr); 16523 16524 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16525 AsmString, StartLoc, 16526 EndLoc); 16527 CurContext->addDecl(New); 16528 return New; 16529 } 16530 16531 static void checkModuleImportContext(Sema &S, Module *M, 16532 SourceLocation ImportLoc, DeclContext *DC, 16533 bool FromInclude = false) { 16534 SourceLocation ExternCLoc; 16535 16536 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16537 switch (LSD->getLanguage()) { 16538 case LinkageSpecDecl::lang_c: 16539 if (ExternCLoc.isInvalid()) 16540 ExternCLoc = LSD->getLocStart(); 16541 break; 16542 case LinkageSpecDecl::lang_cxx: 16543 break; 16544 } 16545 DC = LSD->getParent(); 16546 } 16547 16548 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 16549 DC = DC->getParent(); 16550 16551 if (!isa<TranslationUnitDecl>(DC)) { 16552 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16553 ? diag::ext_module_import_not_at_top_level_noop 16554 : diag::err_module_import_not_at_top_level_fatal) 16555 << M->getFullModuleName() << DC; 16556 S.Diag(cast<Decl>(DC)->getLocStart(), 16557 diag::note_module_import_not_at_top_level) << DC; 16558 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16559 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16560 << M->getFullModuleName(); 16561 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16562 } 16563 } 16564 16565 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16566 SourceLocation ModuleLoc, 16567 ModuleDeclKind MDK, 16568 ModuleIdPath Path) { 16569 assert(getLangOpts().ModulesTS && 16570 "should only have module decl in modules TS"); 16571 16572 // A module implementation unit requires that we are not compiling a module 16573 // of any kind. A module interface unit requires that we are not compiling a 16574 // module map. 16575 switch (getLangOpts().getCompilingModule()) { 16576 case LangOptions::CMK_None: 16577 // It's OK to compile a module interface as a normal translation unit. 16578 break; 16579 16580 case LangOptions::CMK_ModuleInterface: 16581 if (MDK != ModuleDeclKind::Implementation) 16582 break; 16583 16584 // We were asked to compile a module interface unit but this is a module 16585 // implementation unit. That indicates the 'export' is missing. 16586 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16587 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16588 MDK = ModuleDeclKind::Interface; 16589 break; 16590 16591 case LangOptions::CMK_ModuleMap: 16592 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16593 return nullptr; 16594 } 16595 16596 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16597 16598 // FIXME: Most of this work should be done by the preprocessor rather than 16599 // here, in order to support macro import. 16600 16601 // Only one module-declaration is permitted per source file. 16602 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16603 Diag(ModuleLoc, diag::err_module_redeclaration); 16604 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16605 diag::note_prev_module_declaration); 16606 return nullptr; 16607 } 16608 16609 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16610 // modules, the dots here are just another character that can appear in a 16611 // module name. 16612 std::string ModuleName; 16613 for (auto &Piece : Path) { 16614 if (!ModuleName.empty()) 16615 ModuleName += "."; 16616 ModuleName += Piece.first->getName(); 16617 } 16618 16619 // If a module name was explicitly specified on the command line, it must be 16620 // correct. 16621 if (!getLangOpts().CurrentModule.empty() && 16622 getLangOpts().CurrentModule != ModuleName) { 16623 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16624 << SourceRange(Path.front().second, Path.back().second) 16625 << getLangOpts().CurrentModule; 16626 return nullptr; 16627 } 16628 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16629 16630 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16631 Module *Mod; 16632 16633 switch (MDK) { 16634 case ModuleDeclKind::Interface: { 16635 // We can't have parsed or imported a definition of this module or parsed a 16636 // module map defining it already. 16637 if (auto *M = Map.findModule(ModuleName)) { 16638 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16639 if (M->DefinitionLoc.isValid()) 16640 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16641 else if (const auto *FE = M->getASTFile()) 16642 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16643 << FE->getName(); 16644 Mod = M; 16645 break; 16646 } 16647 16648 // Create a Module for the module that we're defining. 16649 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16650 ModuleScopes.front().Module); 16651 assert(Mod && "module creation should not fail"); 16652 break; 16653 } 16654 16655 case ModuleDeclKind::Partition: 16656 // FIXME: Check we are in a submodule of the named module. 16657 return nullptr; 16658 16659 case ModuleDeclKind::Implementation: 16660 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16661 PP.getIdentifierInfo(ModuleName), Path[0].second); 16662 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16663 /*IsIncludeDirective=*/false); 16664 if (!Mod) { 16665 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 16666 // Create an empty module interface unit for error recovery. 16667 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16668 ModuleScopes.front().Module); 16669 } 16670 break; 16671 } 16672 16673 // Switch from the global module to the named module. 16674 ModuleScopes.back().Module = Mod; 16675 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 16676 VisibleModules.setVisible(Mod, ModuleLoc); 16677 16678 // From now on, we have an owning module for all declarations we see. 16679 // However, those declarations are module-private unless explicitly 16680 // exported. 16681 auto *TU = Context.getTranslationUnitDecl(); 16682 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16683 TU->setLocalOwningModule(Mod); 16684 16685 // FIXME: Create a ModuleDecl. 16686 return nullptr; 16687 } 16688 16689 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16690 SourceLocation ImportLoc, 16691 ModuleIdPath Path) { 16692 Module *Mod = 16693 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16694 /*IsIncludeDirective=*/false); 16695 if (!Mod) 16696 return true; 16697 16698 VisibleModules.setVisible(Mod, ImportLoc); 16699 16700 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16701 16702 // FIXME: we should support importing a submodule within a different submodule 16703 // of the same top-level module. Until we do, make it an error rather than 16704 // silently ignoring the import. 16705 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16706 // warn on a redundant import of the current module? 16707 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16708 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16709 Diag(ImportLoc, getLangOpts().isCompilingModule() 16710 ? diag::err_module_self_import 16711 : diag::err_module_import_in_implementation) 16712 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16713 16714 SmallVector<SourceLocation, 2> IdentifierLocs; 16715 Module *ModCheck = Mod; 16716 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16717 // If we've run out of module parents, just drop the remaining identifiers. 16718 // We need the length to be consistent. 16719 if (!ModCheck) 16720 break; 16721 ModCheck = ModCheck->Parent; 16722 16723 IdentifierLocs.push_back(Path[I].second); 16724 } 16725 16726 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 16727 Mod, IdentifierLocs); 16728 if (!ModuleScopes.empty()) 16729 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16730 CurContext->addDecl(Import); 16731 16732 // Re-export the module if needed. 16733 if (Import->isExported() && 16734 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) 16735 getCurrentModule()->Exports.emplace_back(Mod, false); 16736 16737 return Import; 16738 } 16739 16740 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16741 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16742 BuildModuleInclude(DirectiveLoc, Mod); 16743 } 16744 16745 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16746 // Determine whether we're in the #include buffer for a module. The #includes 16747 // in that buffer do not qualify as module imports; they're just an 16748 // implementation detail of us building the module. 16749 // 16750 // FIXME: Should we even get ActOnModuleInclude calls for those? 16751 bool IsInModuleIncludes = 16752 TUKind == TU_Module && 16753 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16754 16755 bool ShouldAddImport = !IsInModuleIncludes; 16756 16757 // If this module import was due to an inclusion directive, create an 16758 // implicit import declaration to capture it in the AST. 16759 if (ShouldAddImport) { 16760 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16761 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16762 DirectiveLoc, Mod, 16763 DirectiveLoc); 16764 if (!ModuleScopes.empty()) 16765 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16766 TU->addDecl(ImportD); 16767 Consumer.HandleImplicitImportDecl(ImportD); 16768 } 16769 16770 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16771 VisibleModules.setVisible(Mod, DirectiveLoc); 16772 } 16773 16774 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16775 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16776 16777 ModuleScopes.push_back({}); 16778 ModuleScopes.back().Module = Mod; 16779 if (getLangOpts().ModulesLocalVisibility) 16780 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16781 16782 VisibleModules.setVisible(Mod, DirectiveLoc); 16783 16784 // The enclosing context is now part of this module. 16785 // FIXME: Consider creating a child DeclContext to hold the entities 16786 // lexically within the module. 16787 if (getLangOpts().trackLocalOwningModule()) { 16788 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16789 cast<Decl>(DC)->setModuleOwnershipKind( 16790 getLangOpts().ModulesLocalVisibility 16791 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16792 : Decl::ModuleOwnershipKind::Visible); 16793 cast<Decl>(DC)->setLocalOwningModule(Mod); 16794 } 16795 } 16796 } 16797 16798 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16799 if (getLangOpts().ModulesLocalVisibility) { 16800 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16801 // Leaving a module hides namespace names, so our visible namespace cache 16802 // is now out of date. 16803 VisibleNamespaceCache.clear(); 16804 } 16805 16806 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16807 "left the wrong module scope"); 16808 ModuleScopes.pop_back(); 16809 16810 // We got to the end of processing a local module. Create an 16811 // ImportDecl as we would for an imported module. 16812 FileID File = getSourceManager().getFileID(EomLoc); 16813 SourceLocation DirectiveLoc; 16814 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16815 // We reached the end of a #included module header. Use the #include loc. 16816 assert(File != getSourceManager().getMainFileID() && 16817 "end of submodule in main source file"); 16818 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16819 } else { 16820 // We reached an EOM pragma. Use the pragma location. 16821 DirectiveLoc = EomLoc; 16822 } 16823 BuildModuleInclude(DirectiveLoc, Mod); 16824 16825 // Any further declarations are in whatever module we returned to. 16826 if (getLangOpts().trackLocalOwningModule()) { 16827 // The parser guarantees that this is the same context that we entered 16828 // the module within. 16829 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16830 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16831 if (!getCurrentModule()) 16832 cast<Decl>(DC)->setModuleOwnershipKind( 16833 Decl::ModuleOwnershipKind::Unowned); 16834 } 16835 } 16836 } 16837 16838 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16839 Module *Mod) { 16840 // Bail if we're not allowed to implicitly import a module here. 16841 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16842 VisibleModules.isVisible(Mod)) 16843 return; 16844 16845 // Create the implicit import declaration. 16846 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16847 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16848 Loc, Mod, Loc); 16849 TU->addDecl(ImportD); 16850 Consumer.HandleImplicitImportDecl(ImportD); 16851 16852 // Make the module visible. 16853 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16854 VisibleModules.setVisible(Mod, Loc); 16855 } 16856 16857 /// We have parsed the start of an export declaration, including the '{' 16858 /// (if present). 16859 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16860 SourceLocation LBraceLoc) { 16861 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16862 16863 // C++ Modules TS draft: 16864 // An export-declaration shall appear in the purview of a module other than 16865 // the global module. 16866 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 16867 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16868 16869 // An export-declaration [...] shall not contain more than one 16870 // export keyword. 16871 // 16872 // The intent here is that an export-declaration cannot appear within another 16873 // export-declaration. 16874 if (D->isExported()) 16875 Diag(ExportLoc, diag::err_export_within_export); 16876 16877 CurContext->addDecl(D); 16878 PushDeclContext(S, D); 16879 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16880 return D; 16881 } 16882 16883 /// Complete the definition of an export declaration. 16884 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16885 auto *ED = cast<ExportDecl>(D); 16886 if (RBraceLoc.isValid()) 16887 ED->setRBraceLoc(RBraceLoc); 16888 16889 // FIXME: Diagnose export of internal-linkage declaration (including 16890 // anonymous namespace). 16891 16892 PopDeclContext(); 16893 return D; 16894 } 16895 16896 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16897 IdentifierInfo* AliasName, 16898 SourceLocation PragmaLoc, 16899 SourceLocation NameLoc, 16900 SourceLocation AliasNameLoc) { 16901 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16902 LookupOrdinaryName); 16903 AsmLabelAttr *Attr = 16904 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16905 16906 // If a declaration that: 16907 // 1) declares a function or a variable 16908 // 2) has external linkage 16909 // already exists, add a label attribute to it. 16910 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16911 if (isDeclExternC(PrevDecl)) 16912 PrevDecl->addAttr(Attr); 16913 else 16914 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16915 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16916 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16917 } else 16918 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16919 } 16920 16921 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16922 SourceLocation PragmaLoc, 16923 SourceLocation NameLoc) { 16924 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16925 16926 if (PrevDecl) { 16927 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16928 } else { 16929 (void)WeakUndeclaredIdentifiers.insert( 16930 std::pair<IdentifierInfo*,WeakInfo> 16931 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16932 } 16933 } 16934 16935 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16936 IdentifierInfo* AliasName, 16937 SourceLocation PragmaLoc, 16938 SourceLocation NameLoc, 16939 SourceLocation AliasNameLoc) { 16940 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16941 LookupOrdinaryName); 16942 WeakInfo W = WeakInfo(Name, NameLoc); 16943 16944 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16945 if (!PrevDecl->hasAttr<AliasAttr>()) 16946 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16947 DeclApplyPragmaWeak(TUScope, ND, W); 16948 } else { 16949 (void)WeakUndeclaredIdentifiers.insert( 16950 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16951 } 16952 } 16953 16954 Decl *Sema::getObjCDeclContext() const { 16955 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16956 } 16957