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 /// \brief 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___float128: 136 case tok::kw_wchar_t: 137 case tok::kw_bool: 138 case tok::kw___underlying_type: 139 case tok::kw___auto_type: 140 return true; 141 142 case tok::annot_typename: 143 case tok::kw_char16_t: 144 case tok::kw_char32_t: 145 case tok::kw_typeof: 146 case tok::annot_decltype: 147 case tok::kw_decltype: 148 return getLangOpts().CPlusPlus; 149 150 default: 151 break; 152 } 153 154 return false; 155 } 156 157 namespace { 158 enum class UnqualifiedTypeNameLookupResult { 159 NotFound, 160 FoundNonType, 161 FoundType 162 }; 163 } // end anonymous namespace 164 165 /// \brief Tries to perform unqualified lookup of the type decls in bases for 166 /// dependent class. 167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 168 /// type decl, \a FoundType if only type decls are found. 169 static UnqualifiedTypeNameLookupResult 170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 171 SourceLocation NameLoc, 172 const CXXRecordDecl *RD) { 173 if (!RD->hasDefinition()) 174 return UnqualifiedTypeNameLookupResult::NotFound; 175 // Look for type decls in base classes. 176 UnqualifiedTypeNameLookupResult FoundTypeDecl = 177 UnqualifiedTypeNameLookupResult::NotFound; 178 for (const auto &Base : RD->bases()) { 179 const CXXRecordDecl *BaseRD = nullptr; 180 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 181 BaseRD = BaseTT->getAsCXXRecordDecl(); 182 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 183 // Look for type decls in dependent base classes that have known primary 184 // templates. 185 if (!TST || !TST->isDependentType()) 186 continue; 187 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 188 if (!TD) 189 continue; 190 if (auto *BasePrimaryTemplate = 191 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 192 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 193 BaseRD = BasePrimaryTemplate; 194 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 195 if (const ClassTemplatePartialSpecializationDecl *PS = 196 CTD->findPartialSpecialization(Base.getType())) 197 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 198 BaseRD = PS; 199 } 200 } 201 } 202 if (BaseRD) { 203 for (NamedDecl *ND : BaseRD->lookup(&II)) { 204 if (!isa<TypeDecl>(ND)) 205 return UnqualifiedTypeNameLookupResult::FoundNonType; 206 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 207 } 208 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 209 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 210 case UnqualifiedTypeNameLookupResult::FoundNonType: 211 return UnqualifiedTypeNameLookupResult::FoundNonType; 212 case UnqualifiedTypeNameLookupResult::FoundType: 213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 214 break; 215 case UnqualifiedTypeNameLookupResult::NotFound: 216 break; 217 } 218 } 219 } 220 } 221 222 return FoundTypeDecl; 223 } 224 225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 226 const IdentifierInfo &II, 227 SourceLocation NameLoc) { 228 // Lookup in the parent class template context, if any. 229 const CXXRecordDecl *RD = nullptr; 230 UnqualifiedTypeNameLookupResult FoundTypeDecl = 231 UnqualifiedTypeNameLookupResult::NotFound; 232 for (DeclContext *DC = S.CurContext; 233 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 234 DC = DC->getParent()) { 235 // Look for type decls in dependent base classes that have known primary 236 // templates. 237 RD = dyn_cast<CXXRecordDecl>(DC); 238 if (RD && RD->getDescribedClassTemplate()) 239 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 240 } 241 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 242 return nullptr; 243 244 // We found some types in dependent base classes. Recover as if the user 245 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 246 // lookup during template instantiation. 247 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 248 249 ASTContext &Context = S.Context; 250 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 251 cast<Type>(Context.getRecordType(RD))); 252 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 253 254 CXXScopeSpec SS; 255 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 256 257 TypeLocBuilder Builder; 258 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 259 DepTL.setNameLoc(NameLoc); 260 DepTL.setElaboratedKeywordLoc(SourceLocation()); 261 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 262 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 263 } 264 265 /// \brief If the identifier refers to a type name within this scope, 266 /// return the declaration of that type. 267 /// 268 /// This routine performs ordinary name lookup of the identifier II 269 /// within the given scope, with optional C++ scope specifier SS, to 270 /// determine whether the name refers to a type. If so, returns an 271 /// opaque pointer (actually a QualType) corresponding to that 272 /// type. Otherwise, returns NULL. 273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 274 Scope *S, CXXScopeSpec *SS, 275 bool isClassName, bool HasTrailingDot, 276 ParsedType ObjectTypePtr, 277 bool IsCtorOrDtorName, 278 bool WantNontrivialTypeSourceInfo, 279 bool IsClassTemplateDeductionContext, 280 IdentifierInfo **CorrectedII) { 281 // FIXME: Consider allowing this outside C++1z mode as an extension. 282 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 283 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName && 284 !isClassName && !HasTrailingDot; 285 286 // Determine where we will perform name lookup. 287 DeclContext *LookupCtx = nullptr; 288 if (ObjectTypePtr) { 289 QualType ObjectType = ObjectTypePtr.get(); 290 if (ObjectType->isRecordType()) 291 LookupCtx = computeDeclContext(ObjectType); 292 } else if (SS && SS->isNotEmpty()) { 293 LookupCtx = computeDeclContext(*SS, false); 294 295 if (!LookupCtx) { 296 if (isDependentScopeSpecifier(*SS)) { 297 // C++ [temp.res]p3: 298 // A qualified-id that refers to a type and in which the 299 // nested-name-specifier depends on a template-parameter (14.6.2) 300 // shall be prefixed by the keyword typename to indicate that the 301 // qualified-id denotes a type, forming an 302 // elaborated-type-specifier (7.1.5.3). 303 // 304 // We therefore do not perform any name lookup if the result would 305 // refer to a member of an unknown specialization. 306 if (!isClassName && !IsCtorOrDtorName) 307 return nullptr; 308 309 // We know from the grammar that this name refers to a type, 310 // so build a dependent node to describe the type. 311 if (WantNontrivialTypeSourceInfo) 312 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 313 314 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 315 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 316 II, NameLoc); 317 return ParsedType::make(T); 318 } 319 320 return nullptr; 321 } 322 323 if (!LookupCtx->isDependentContext() && 324 RequireCompleteDeclContext(*SS, LookupCtx)) 325 return nullptr; 326 } 327 328 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 329 // lookup for class-names. 330 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 331 LookupOrdinaryName; 332 LookupResult Result(*this, &II, NameLoc, Kind); 333 if (LookupCtx) { 334 // Perform "qualified" name lookup into the declaration context we 335 // computed, which is either the type of the base of a member access 336 // expression or the declaration context associated with a prior 337 // nested-name-specifier. 338 LookupQualifiedName(Result, LookupCtx); 339 340 if (ObjectTypePtr && Result.empty()) { 341 // C++ [basic.lookup.classref]p3: 342 // If the unqualified-id is ~type-name, the type-name is looked up 343 // in the context of the entire postfix-expression. If the type T of 344 // the object expression is of a class type C, the type-name is also 345 // looked up in the scope of class C. At least one of the lookups shall 346 // find a name that refers to (possibly cv-qualified) T. 347 LookupName(Result, S); 348 } 349 } else { 350 // Perform unqualified name lookup. 351 LookupName(Result, S); 352 353 // For unqualified lookup in a class template in MSVC mode, look into 354 // dependent base classes where the primary class template is known. 355 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 356 if (ParsedType TypeInBase = 357 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 358 return TypeInBase; 359 } 360 } 361 362 NamedDecl *IIDecl = nullptr; 363 switch (Result.getResultKind()) { 364 case LookupResult::NotFound: 365 case LookupResult::NotFoundInCurrentInstantiation: 366 if (CorrectedII) { 367 TypoCorrection Correction = 368 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 369 llvm::make_unique<TypeNameValidatorCCC>( 370 true, isClassName, AllowDeducedTemplate), 371 CTK_ErrorRecovery); 372 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 373 TemplateTy Template; 374 bool MemberOfUnknownSpecialization; 375 UnqualifiedId TemplateName; 376 TemplateName.setIdentifier(NewII, NameLoc); 377 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 378 CXXScopeSpec NewSS, *NewSSPtr = SS; 379 if (SS && NNS) { 380 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 381 NewSSPtr = &NewSS; 382 } 383 if (Correction && (NNS || NewII != &II) && 384 // Ignore a correction to a template type as the to-be-corrected 385 // identifier is not a template (typo correction for template names 386 // is handled elsewhere). 387 !(getLangOpts().CPlusPlus && NewSSPtr && 388 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 389 Template, MemberOfUnknownSpecialization))) { 390 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 391 isClassName, HasTrailingDot, ObjectTypePtr, 392 IsCtorOrDtorName, 393 WantNontrivialTypeSourceInfo, 394 IsClassTemplateDeductionContext); 395 if (Ty) { 396 diagnoseTypo(Correction, 397 PDiag(diag::err_unknown_type_or_class_name_suggest) 398 << Result.getLookupName() << isClassName); 399 if (SS && NNS) 400 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 401 *CorrectedII = NewII; 402 return Ty; 403 } 404 } 405 } 406 // If typo correction failed or was not performed, fall through 407 case LookupResult::FoundOverloaded: 408 case LookupResult::FoundUnresolvedValue: 409 Result.suppressDiagnostics(); 410 return nullptr; 411 412 case LookupResult::Ambiguous: 413 // Recover from type-hiding ambiguities by hiding the type. We'll 414 // do the lookup again when looking for an object, and we can 415 // diagnose the error then. If we don't do this, then the error 416 // about hiding the type will be immediately followed by an error 417 // that only makes sense if the identifier was treated like a type. 418 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 419 Result.suppressDiagnostics(); 420 return nullptr; 421 } 422 423 // Look to see if we have a type anywhere in the list of results. 424 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 425 Res != ResEnd; ++Res) { 426 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 427 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 428 if (!IIDecl || 429 (*Res)->getLocation().getRawEncoding() < 430 IIDecl->getLocation().getRawEncoding()) 431 IIDecl = *Res; 432 } 433 } 434 435 if (!IIDecl) { 436 // None of the entities we found is a type, so there is no way 437 // to even assume that the result is a type. In this case, don't 438 // complain about the ambiguity. The parser will either try to 439 // perform this lookup again (e.g., as an object name), which 440 // will produce the ambiguity, or will complain that it expected 441 // a type name. 442 Result.suppressDiagnostics(); 443 return nullptr; 444 } 445 446 // We found a type within the ambiguous lookup; diagnose the 447 // ambiguity and then return that type. This might be the right 448 // answer, or it might not be, but it suppresses any attempt to 449 // perform the name lookup again. 450 break; 451 452 case LookupResult::Found: 453 IIDecl = Result.getFoundDecl(); 454 break; 455 } 456 457 assert(IIDecl && "Didn't find decl"); 458 459 QualType T; 460 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 461 // C++ [class.qual]p2: A lookup that would find the injected-class-name 462 // instead names the constructors of the class, except when naming a class. 463 // This is ill-formed when we're not actually forming a ctor or dtor name. 464 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 465 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 466 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 467 FoundRD->isInjectedClassName() && 468 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 469 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 470 << &II << /*Type*/1; 471 472 DiagnoseUseOfDecl(IIDecl, NameLoc); 473 474 T = Context.getTypeDeclType(TD); 475 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 476 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 477 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 478 if (!HasTrailingDot) 479 T = Context.getObjCInterfaceType(IDecl); 480 } else if (AllowDeducedTemplate) { 481 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 482 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 483 QualType(), false); 484 } 485 486 if (T.isNull()) { 487 // If it's not plausibly a type, suppress diagnostics. 488 Result.suppressDiagnostics(); 489 return nullptr; 490 } 491 492 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 493 // constructor or destructor name (in such a case, the scope specifier 494 // will be attached to the enclosing Expr or Decl node). 495 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 496 !isa<ObjCInterfaceDecl>(IIDecl)) { 497 if (WantNontrivialTypeSourceInfo) { 498 // Construct a type with type-source information. 499 TypeLocBuilder Builder; 500 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 501 502 T = getElaboratedType(ETK_None, *SS, T); 503 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 504 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 505 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 506 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 507 } else { 508 T = getElaboratedType(ETK_None, *SS, T); 509 } 510 } 511 512 return ParsedType::make(T); 513 } 514 515 // Builds a fake NNS for the given decl context. 516 static NestedNameSpecifier * 517 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 518 for (;; DC = DC->getLookupParent()) { 519 DC = DC->getPrimaryContext(); 520 auto *ND = dyn_cast<NamespaceDecl>(DC); 521 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 522 return NestedNameSpecifier::Create(Context, nullptr, ND); 523 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 524 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 525 RD->getTypeForDecl()); 526 else if (isa<TranslationUnitDecl>(DC)) 527 return NestedNameSpecifier::GlobalSpecifier(Context); 528 } 529 llvm_unreachable("something isn't in TU scope?"); 530 } 531 532 /// Find the parent class with dependent bases of the innermost enclosing method 533 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 534 /// up allowing unqualified dependent type names at class-level, which MSVC 535 /// correctly rejects. 536 static const CXXRecordDecl * 537 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 538 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 539 DC = DC->getPrimaryContext(); 540 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 541 if (MD->getParent()->hasAnyDependentBases()) 542 return MD->getParent(); 543 } 544 return nullptr; 545 } 546 547 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 548 SourceLocation NameLoc, 549 bool IsTemplateTypeArg) { 550 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 551 552 NestedNameSpecifier *NNS = nullptr; 553 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 554 // If we weren't able to parse a default template argument, delay lookup 555 // until instantiation time by making a non-dependent DependentTypeName. We 556 // pretend we saw a NestedNameSpecifier referring to the current scope, and 557 // lookup is retried. 558 // FIXME: This hurts our diagnostic quality, since we get errors like "no 559 // type named 'Foo' in 'current_namespace'" when the user didn't write any 560 // name specifiers. 561 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 562 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 563 } else if (const CXXRecordDecl *RD = 564 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 565 // Build a DependentNameType that will perform lookup into RD at 566 // instantiation time. 567 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 568 RD->getTypeForDecl()); 569 570 // Diagnose that this identifier was undeclared, and retry the lookup during 571 // template instantiation. 572 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 573 << RD; 574 } else { 575 // This is not a situation that we should recover from. 576 return ParsedType(); 577 } 578 579 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 580 581 // Build type location information. We synthesized the qualifier, so we have 582 // to build a fake NestedNameSpecifierLoc. 583 NestedNameSpecifierLocBuilder NNSLocBuilder; 584 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 585 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 586 587 TypeLocBuilder Builder; 588 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 589 DepTL.setNameLoc(NameLoc); 590 DepTL.setElaboratedKeywordLoc(SourceLocation()); 591 DepTL.setQualifierLoc(QualifierLoc); 592 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 593 } 594 595 /// isTagName() - This method is called *for error recovery purposes only* 596 /// to determine if the specified name is a valid tag name ("struct foo"). If 597 /// so, this returns the TST for the tag corresponding to it (TST_enum, 598 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 599 /// cases in C where the user forgot to specify the tag. 600 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 601 // Do a tag name lookup in this scope. 602 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 603 LookupName(R, S, false); 604 R.suppressDiagnostics(); 605 if (R.getResultKind() == LookupResult::Found) 606 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 607 switch (TD->getTagKind()) { 608 case TTK_Struct: return DeclSpec::TST_struct; 609 case TTK_Interface: return DeclSpec::TST_interface; 610 case TTK_Union: return DeclSpec::TST_union; 611 case TTK_Class: return DeclSpec::TST_class; 612 case TTK_Enum: return DeclSpec::TST_enum; 613 } 614 } 615 616 return DeclSpec::TST_unspecified; 617 } 618 619 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 620 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 621 /// then downgrade the missing typename error to a warning. 622 /// This is needed for MSVC compatibility; Example: 623 /// @code 624 /// template<class T> class A { 625 /// public: 626 /// typedef int TYPE; 627 /// }; 628 /// template<class T> class B : public A<T> { 629 /// public: 630 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 631 /// }; 632 /// @endcode 633 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 634 if (CurContext->isRecord()) { 635 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 636 return true; 637 638 const Type *Ty = SS->getScopeRep()->getAsType(); 639 640 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 641 for (const auto &Base : RD->bases()) 642 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 643 return true; 644 return S->isFunctionPrototypeScope(); 645 } 646 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 647 } 648 649 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 650 SourceLocation IILoc, 651 Scope *S, 652 CXXScopeSpec *SS, 653 ParsedType &SuggestedType, 654 bool IsTemplateName) { 655 // Don't report typename errors for editor placeholders. 656 if (II->isEditorPlaceholder()) 657 return; 658 // We don't have anything to suggest (yet). 659 SuggestedType = nullptr; 660 661 // There may have been a typo in the name of the type. Look up typo 662 // results, in case we have something that we can suggest. 663 if (TypoCorrection Corrected = 664 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 665 llvm::make_unique<TypeNameValidatorCCC>( 666 false, false, IsTemplateName, !IsTemplateName), 667 CTK_ErrorRecovery)) { 668 // FIXME: Support error recovery for the template-name case. 669 bool CanRecover = !IsTemplateName; 670 if (Corrected.isKeyword()) { 671 // We corrected to a keyword. 672 diagnoseTypo(Corrected, 673 PDiag(IsTemplateName ? diag::err_no_template_suggest 674 : diag::err_unknown_typename_suggest) 675 << II); 676 II = Corrected.getCorrectionAsIdentifierInfo(); 677 } else { 678 // We found a similarly-named type or interface; suggest that. 679 if (!SS || !SS->isSet()) { 680 diagnoseTypo(Corrected, 681 PDiag(IsTemplateName ? diag::err_no_template_suggest 682 : diag::err_unknown_typename_suggest) 683 << II, CanRecover); 684 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 685 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 686 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 687 II->getName().equals(CorrectedStr); 688 diagnoseTypo(Corrected, 689 PDiag(IsTemplateName 690 ? diag::err_no_member_template_suggest 691 : diag::err_unknown_nested_typename_suggest) 692 << II << DC << DroppedSpecifier << SS->getRange(), 693 CanRecover); 694 } else { 695 llvm_unreachable("could not have corrected a typo here"); 696 } 697 698 if (!CanRecover) 699 return; 700 701 CXXScopeSpec tmpSS; 702 if (Corrected.getCorrectionSpecifier()) 703 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 704 SourceRange(IILoc)); 705 // FIXME: Support class template argument deduction here. 706 SuggestedType = 707 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 708 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 709 /*IsCtorOrDtorName=*/false, 710 /*NonTrivialTypeSourceInfo=*/true); 711 } 712 return; 713 } 714 715 if (getLangOpts().CPlusPlus && !IsTemplateName) { 716 // See if II is a class template that the user forgot to pass arguments to. 717 UnqualifiedId Name; 718 Name.setIdentifier(II, IILoc); 719 CXXScopeSpec EmptySS; 720 TemplateTy TemplateResult; 721 bool MemberOfUnknownSpecialization; 722 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 723 Name, nullptr, true, TemplateResult, 724 MemberOfUnknownSpecialization) == TNK_Type_template) { 725 TemplateName TplName = TemplateResult.get(); 726 Diag(IILoc, diag::err_template_missing_args) 727 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 728 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 729 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 730 << TplDecl->getTemplateParameters()->getSourceRange(); 731 } 732 return; 733 } 734 } 735 736 // FIXME: Should we move the logic that tries to recover from a missing tag 737 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 738 739 if (!SS || (!SS->isSet() && !SS->isInvalid())) 740 Diag(IILoc, IsTemplateName ? diag::err_no_template 741 : diag::err_unknown_typename) 742 << II; 743 else if (DeclContext *DC = computeDeclContext(*SS, false)) 744 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 745 : diag::err_typename_nested_not_found) 746 << II << DC << SS->getRange(); 747 else if (isDependentScopeSpecifier(*SS)) { 748 unsigned DiagID = diag::err_typename_missing; 749 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 750 DiagID = diag::ext_typename_missing; 751 752 Diag(SS->getRange().getBegin(), DiagID) 753 << SS->getScopeRep() << II->getName() 754 << SourceRange(SS->getRange().getBegin(), IILoc) 755 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 756 SuggestedType = ActOnTypenameType(S, SourceLocation(), 757 *SS, *II, IILoc).get(); 758 } else { 759 assert(SS && SS->isInvalid() && 760 "Invalid scope specifier has already been diagnosed"); 761 } 762 } 763 764 /// \brief Determine whether the given result set contains either a type name 765 /// or 766 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 767 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 768 NextToken.is(tok::less); 769 770 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 771 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 772 return true; 773 774 if (CheckTemplate && isa<TemplateDecl>(*I)) 775 return true; 776 } 777 778 return false; 779 } 780 781 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 782 Scope *S, CXXScopeSpec &SS, 783 IdentifierInfo *&Name, 784 SourceLocation NameLoc) { 785 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 786 SemaRef.LookupParsedName(R, S, &SS); 787 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 788 StringRef FixItTagName; 789 switch (Tag->getTagKind()) { 790 case TTK_Class: 791 FixItTagName = "class "; 792 break; 793 794 case TTK_Enum: 795 FixItTagName = "enum "; 796 break; 797 798 case TTK_Struct: 799 FixItTagName = "struct "; 800 break; 801 802 case TTK_Interface: 803 FixItTagName = "__interface "; 804 break; 805 806 case TTK_Union: 807 FixItTagName = "union "; 808 break; 809 } 810 811 StringRef TagName = FixItTagName.drop_back(); 812 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 813 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 814 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 815 816 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 817 I != IEnd; ++I) 818 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 819 << Name << TagName; 820 821 // Replace lookup results with just the tag decl. 822 Result.clear(Sema::LookupTagName); 823 SemaRef.LookupParsedName(Result, S, &SS); 824 return true; 825 } 826 827 return false; 828 } 829 830 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 831 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 832 QualType T, SourceLocation NameLoc) { 833 ASTContext &Context = S.Context; 834 835 TypeLocBuilder Builder; 836 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 837 838 T = S.getElaboratedType(ETK_None, SS, T); 839 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 840 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 841 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 842 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 843 } 844 845 Sema::NameClassification 846 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 847 SourceLocation NameLoc, const Token &NextToken, 848 bool IsAddressOfOperand, 849 std::unique_ptr<CorrectionCandidateCallback> CCC) { 850 DeclarationNameInfo NameInfo(Name, NameLoc); 851 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 852 853 if (NextToken.is(tok::coloncolon)) { 854 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 855 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 856 } else if (getLangOpts().CPlusPlus && SS.isSet() && 857 isCurrentClassName(*Name, S, &SS)) { 858 // Per [class.qual]p2, this names the constructors of SS, not the 859 // injected-class-name. We don't have a classification for that. 860 // There's not much point caching this result, since the parser 861 // will reject it later. 862 return NameClassification::Unknown(); 863 } 864 865 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 866 LookupParsedName(Result, S, &SS, !CurMethod); 867 868 // For unqualified lookup in a class template in MSVC mode, look into 869 // dependent base classes where the primary class template is known. 870 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 871 if (ParsedType TypeInBase = 872 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 873 return TypeInBase; 874 } 875 876 // Perform lookup for Objective-C instance variables (including automatically 877 // synthesized instance variables), if we're in an Objective-C method. 878 // FIXME: This lookup really, really needs to be folded in to the normal 879 // unqualified lookup mechanism. 880 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 881 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 882 if (E.get() || E.isInvalid()) 883 return E; 884 } 885 886 bool SecondTry = false; 887 bool IsFilteredTemplateName = false; 888 889 Corrected: 890 switch (Result.getResultKind()) { 891 case LookupResult::NotFound: 892 // If an unqualified-id is followed by a '(', then we have a function 893 // call. 894 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 895 // In C++, this is an ADL-only call. 896 // FIXME: Reference? 897 if (getLangOpts().CPlusPlus) 898 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 899 900 // C90 6.3.2.2: 901 // If the expression that precedes the parenthesized argument list in a 902 // function call consists solely of an identifier, and if no 903 // declaration is visible for this identifier, the identifier is 904 // implicitly declared exactly as if, in the innermost block containing 905 // the function call, the declaration 906 // 907 // extern int identifier (); 908 // 909 // appeared. 910 // 911 // We also allow this in C99 as an extension. 912 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 913 Result.addDecl(D); 914 Result.resolveKind(); 915 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 916 } 917 } 918 919 // In C, we first see whether there is a tag type by the same name, in 920 // which case it's likely that the user just forgot to write "enum", 921 // "struct", or "union". 922 if (!getLangOpts().CPlusPlus && !SecondTry && 923 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 924 break; 925 } 926 927 // Perform typo correction to determine if there is another name that is 928 // close to this name. 929 if (!SecondTry && CCC) { 930 SecondTry = true; 931 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 932 Result.getLookupKind(), S, 933 &SS, std::move(CCC), 934 CTK_ErrorRecovery)) { 935 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 936 unsigned QualifiedDiag = diag::err_no_member_suggest; 937 938 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 939 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 940 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 941 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 942 UnqualifiedDiag = diag::err_no_template_suggest; 943 QualifiedDiag = diag::err_no_member_template_suggest; 944 } else if (UnderlyingFirstDecl && 945 (isa<TypeDecl>(UnderlyingFirstDecl) || 946 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 947 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 948 UnqualifiedDiag = diag::err_unknown_typename_suggest; 949 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 950 } 951 952 if (SS.isEmpty()) { 953 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 954 } else {// FIXME: is this even reachable? Test it. 955 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 956 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 957 Name->getName().equals(CorrectedStr); 958 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 959 << Name << computeDeclContext(SS, false) 960 << DroppedSpecifier << SS.getRange()); 961 } 962 963 // Update the name, so that the caller has the new name. 964 Name = Corrected.getCorrectionAsIdentifierInfo(); 965 966 // Typo correction corrected to a keyword. 967 if (Corrected.isKeyword()) 968 return Name; 969 970 // Also update the LookupResult... 971 // FIXME: This should probably go away at some point 972 Result.clear(); 973 Result.setLookupName(Corrected.getCorrection()); 974 if (FirstDecl) 975 Result.addDecl(FirstDecl); 976 977 // If we found an Objective-C instance variable, let 978 // LookupInObjCMethod build the appropriate expression to 979 // reference the ivar. 980 // FIXME: This is a gross hack. 981 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 982 Result.clear(); 983 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 984 return E; 985 } 986 987 goto Corrected; 988 } 989 } 990 991 // We failed to correct; just fall through and let the parser deal with it. 992 Result.suppressDiagnostics(); 993 return NameClassification::Unknown(); 994 995 case LookupResult::NotFoundInCurrentInstantiation: { 996 // We performed name lookup into the current instantiation, and there were 997 // dependent bases, so we treat this result the same way as any other 998 // dependent nested-name-specifier. 999 1000 // C++ [temp.res]p2: 1001 // A name used in a template declaration or definition and that is 1002 // dependent on a template-parameter is assumed not to name a type 1003 // unless the applicable name lookup finds a type name or the name is 1004 // qualified by the keyword typename. 1005 // 1006 // FIXME: If the next token is '<', we might want to ask the parser to 1007 // perform some heroics to see if we actually have a 1008 // template-argument-list, which would indicate a missing 'template' 1009 // keyword here. 1010 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1011 NameInfo, IsAddressOfOperand, 1012 /*TemplateArgs=*/nullptr); 1013 } 1014 1015 case LookupResult::Found: 1016 case LookupResult::FoundOverloaded: 1017 case LookupResult::FoundUnresolvedValue: 1018 break; 1019 1020 case LookupResult::Ambiguous: 1021 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1022 hasAnyAcceptableTemplateNames(Result)) { 1023 // C++ [temp.local]p3: 1024 // A lookup that finds an injected-class-name (10.2) can result in an 1025 // ambiguity in certain cases (for example, if it is found in more than 1026 // one base class). If all of the injected-class-names that are found 1027 // refer to specializations of the same class template, and if the name 1028 // is followed by a template-argument-list, the reference refers to the 1029 // class template itself and not a specialization thereof, and is not 1030 // ambiguous. 1031 // 1032 // This filtering can make an ambiguous result into an unambiguous one, 1033 // so try again after filtering out template names. 1034 FilterAcceptableTemplateNames(Result); 1035 if (!Result.isAmbiguous()) { 1036 IsFilteredTemplateName = true; 1037 break; 1038 } 1039 } 1040 1041 // Diagnose the ambiguity and return an error. 1042 return NameClassification::Error(); 1043 } 1044 1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1046 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1047 // C++ [temp.names]p3: 1048 // After name lookup (3.4) finds that a name is a template-name or that 1049 // an operator-function-id or a literal- operator-id refers to a set of 1050 // overloaded functions any member of which is a function template if 1051 // this is followed by a <, the < is always taken as the delimiter of a 1052 // template-argument-list and never as the less-than operator. 1053 if (!IsFilteredTemplateName) 1054 FilterAcceptableTemplateNames(Result); 1055 1056 if (!Result.empty()) { 1057 bool IsFunctionTemplate; 1058 bool IsVarTemplate; 1059 TemplateName Template; 1060 if (Result.end() - Result.begin() > 1) { 1061 IsFunctionTemplate = true; 1062 Template = Context.getOverloadedTemplateName(Result.begin(), 1063 Result.end()); 1064 } else { 1065 TemplateDecl *TD 1066 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1067 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1068 IsVarTemplate = isa<VarTemplateDecl>(TD); 1069 1070 if (SS.isSet() && !SS.isInvalid()) 1071 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1072 /*TemplateKeyword=*/false, 1073 TD); 1074 else 1075 Template = TemplateName(TD); 1076 } 1077 1078 if (IsFunctionTemplate) { 1079 // Function templates always go through overload resolution, at which 1080 // point we'll perform the various checks (e.g., accessibility) we need 1081 // to based on which function we selected. 1082 Result.suppressDiagnostics(); 1083 1084 return NameClassification::FunctionTemplate(Template); 1085 } 1086 1087 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1088 : NameClassification::TypeTemplate(Template); 1089 } 1090 } 1091 1092 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1093 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1094 DiagnoseUseOfDecl(Type, NameLoc); 1095 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1096 QualType T = Context.getTypeDeclType(Type); 1097 if (SS.isNotEmpty()) 1098 return buildNestedType(*this, SS, T, NameLoc); 1099 return ParsedType::make(T); 1100 } 1101 1102 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1103 if (!Class) { 1104 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1105 if (ObjCCompatibleAliasDecl *Alias = 1106 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1107 Class = Alias->getClassInterface(); 1108 } 1109 1110 if (Class) { 1111 DiagnoseUseOfDecl(Class, NameLoc); 1112 1113 if (NextToken.is(tok::period)) { 1114 // Interface. <something> is parsed as a property reference expression. 1115 // Just return "unknown" as a fall-through for now. 1116 Result.suppressDiagnostics(); 1117 return NameClassification::Unknown(); 1118 } 1119 1120 QualType T = Context.getObjCInterfaceType(Class); 1121 return ParsedType::make(T); 1122 } 1123 1124 // We can have a type template here if we're classifying a template argument. 1125 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1126 !isa<VarTemplateDecl>(FirstDecl)) 1127 return NameClassification::TypeTemplate( 1128 TemplateName(cast<TemplateDecl>(FirstDecl))); 1129 1130 // Check for a tag type hidden by a non-type decl in a few cases where it 1131 // seems likely a type is wanted instead of the non-type that was found. 1132 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1133 if ((NextToken.is(tok::identifier) || 1134 (NextIsOp && 1135 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1136 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1137 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1138 DiagnoseUseOfDecl(Type, NameLoc); 1139 QualType T = Context.getTypeDeclType(Type); 1140 if (SS.isNotEmpty()) 1141 return buildNestedType(*this, SS, T, NameLoc); 1142 return ParsedType::make(T); 1143 } 1144 1145 if (FirstDecl->isCXXClassMember()) 1146 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1147 nullptr, S); 1148 1149 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1150 return BuildDeclarationNameExpr(SS, Result, ADL); 1151 } 1152 1153 Sema::TemplateNameKindForDiagnostics 1154 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1155 auto *TD = Name.getAsTemplateDecl(); 1156 if (!TD) 1157 return TemplateNameKindForDiagnostics::DependentTemplate; 1158 if (isa<ClassTemplateDecl>(TD)) 1159 return TemplateNameKindForDiagnostics::ClassTemplate; 1160 if (isa<FunctionTemplateDecl>(TD)) 1161 return TemplateNameKindForDiagnostics::FunctionTemplate; 1162 if (isa<VarTemplateDecl>(TD)) 1163 return TemplateNameKindForDiagnostics::VarTemplate; 1164 if (isa<TypeAliasTemplateDecl>(TD)) 1165 return TemplateNameKindForDiagnostics::AliasTemplate; 1166 if (isa<TemplateTemplateParmDecl>(TD)) 1167 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1168 return TemplateNameKindForDiagnostics::DependentTemplate; 1169 } 1170 1171 // Determines the context to return to after temporarily entering a 1172 // context. This depends in an unnecessarily complicated way on the 1173 // exact ordering of callbacks from the parser. 1174 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1175 1176 // Functions defined inline within classes aren't parsed until we've 1177 // finished parsing the top-level class, so the top-level class is 1178 // the context we'll need to return to. 1179 // A Lambda call operator whose parent is a class must not be treated 1180 // as an inline member function. A Lambda can be used legally 1181 // either as an in-class member initializer or a default argument. These 1182 // are parsed once the class has been marked complete and so the containing 1183 // context would be the nested class (when the lambda is defined in one); 1184 // If the class is not complete, then the lambda is being used in an 1185 // ill-formed fashion (such as to specify the width of a bit-field, or 1186 // in an array-bound) - in which case we still want to return the 1187 // lexically containing DC (which could be a nested class). 1188 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1189 DC = DC->getLexicalParent(); 1190 1191 // A function not defined within a class will always return to its 1192 // lexical context. 1193 if (!isa<CXXRecordDecl>(DC)) 1194 return DC; 1195 1196 // A C++ inline method/friend is parsed *after* the topmost class 1197 // it was declared in is fully parsed ("complete"); the topmost 1198 // class is the context we need to return to. 1199 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1200 DC = RD; 1201 1202 // Return the declaration context of the topmost class the inline method is 1203 // declared in. 1204 return DC; 1205 } 1206 1207 return DC->getLexicalParent(); 1208 } 1209 1210 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1211 assert(getContainingDC(DC) == CurContext && 1212 "The next DeclContext should be lexically contained in the current one."); 1213 CurContext = DC; 1214 S->setEntity(DC); 1215 } 1216 1217 void Sema::PopDeclContext() { 1218 assert(CurContext && "DeclContext imbalance!"); 1219 1220 CurContext = getContainingDC(CurContext); 1221 assert(CurContext && "Popped translation unit!"); 1222 } 1223 1224 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1225 Decl *D) { 1226 // Unlike PushDeclContext, the context to which we return is not necessarily 1227 // the containing DC of TD, because the new context will be some pre-existing 1228 // TagDecl definition instead of a fresh one. 1229 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1230 CurContext = cast<TagDecl>(D)->getDefinition(); 1231 assert(CurContext && "skipping definition of undefined tag"); 1232 // Start lookups from the parent of the current context; we don't want to look 1233 // into the pre-existing complete definition. 1234 S->setEntity(CurContext->getLookupParent()); 1235 return Result; 1236 } 1237 1238 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1239 CurContext = static_cast<decltype(CurContext)>(Context); 1240 } 1241 1242 /// EnterDeclaratorContext - Used when we must lookup names in the context 1243 /// of a declarator's nested name specifier. 1244 /// 1245 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1246 // C++0x [basic.lookup.unqual]p13: 1247 // A name used in the definition of a static data member of class 1248 // X (after the qualified-id of the static member) is looked up as 1249 // if the name was used in a member function of X. 1250 // C++0x [basic.lookup.unqual]p14: 1251 // If a variable member of a namespace is defined outside of the 1252 // scope of its namespace then any name used in the definition of 1253 // the variable member (after the declarator-id) is looked up as 1254 // if the definition of the variable member occurred in its 1255 // namespace. 1256 // Both of these imply that we should push a scope whose context 1257 // is the semantic context of the declaration. We can't use 1258 // PushDeclContext here because that context is not necessarily 1259 // lexically contained in the current context. Fortunately, 1260 // the containing scope should have the appropriate information. 1261 1262 assert(!S->getEntity() && "scope already has entity"); 1263 1264 #ifndef NDEBUG 1265 Scope *Ancestor = S->getParent(); 1266 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1267 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1268 #endif 1269 1270 CurContext = DC; 1271 S->setEntity(DC); 1272 } 1273 1274 void Sema::ExitDeclaratorContext(Scope *S) { 1275 assert(S->getEntity() == CurContext && "Context imbalance!"); 1276 1277 // Switch back to the lexical context. The safety of this is 1278 // enforced by an assert in EnterDeclaratorContext. 1279 Scope *Ancestor = S->getParent(); 1280 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1281 CurContext = Ancestor->getEntity(); 1282 1283 // We don't need to do anything with the scope, which is going to 1284 // disappear. 1285 } 1286 1287 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1288 // We assume that the caller has already called 1289 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1290 FunctionDecl *FD = D->getAsFunction(); 1291 if (!FD) 1292 return; 1293 1294 // Same implementation as PushDeclContext, but enters the context 1295 // from the lexical parent, rather than the top-level class. 1296 assert(CurContext == FD->getLexicalParent() && 1297 "The next DeclContext should be lexically contained in the current one."); 1298 CurContext = FD; 1299 S->setEntity(CurContext); 1300 1301 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1302 ParmVarDecl *Param = FD->getParamDecl(P); 1303 // If the parameter has an identifier, then add it to the scope 1304 if (Param->getIdentifier()) { 1305 S->AddDecl(Param); 1306 IdResolver.AddDecl(Param); 1307 } 1308 } 1309 } 1310 1311 void Sema::ActOnExitFunctionContext() { 1312 // Same implementation as PopDeclContext, but returns to the lexical parent, 1313 // rather than the top-level class. 1314 assert(CurContext && "DeclContext imbalance!"); 1315 CurContext = CurContext->getLexicalParent(); 1316 assert(CurContext && "Popped translation unit!"); 1317 } 1318 1319 /// \brief Determine whether we allow overloading of the function 1320 /// PrevDecl with another declaration. 1321 /// 1322 /// This routine determines whether overloading is possible, not 1323 /// whether some new function is actually an overload. It will return 1324 /// true in C++ (where we can always provide overloads) or, as an 1325 /// extension, in C when the previous function is already an 1326 /// overloaded function declaration or has the "overloadable" 1327 /// attribute. 1328 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1329 ASTContext &Context) { 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 } 1339 1340 /// Add this decl to the scope shadowed decl chains. 1341 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1342 // Move up the scope chain until we find the nearest enclosing 1343 // non-transparent context. The declaration will be introduced into this 1344 // scope. 1345 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1346 S = S->getParent(); 1347 1348 // Add scoped declarations into their context, so that they can be 1349 // found later. Declarations without a context won't be inserted 1350 // into any context. 1351 if (AddToContext) 1352 CurContext->addDecl(D); 1353 1354 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1355 // are function-local declarations. 1356 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1357 !D->getDeclContext()->getRedeclContext()->Equals( 1358 D->getLexicalDeclContext()->getRedeclContext()) && 1359 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1360 return; 1361 1362 // Template instantiations should also not be pushed into scope. 1363 if (isa<FunctionDecl>(D) && 1364 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1365 return; 1366 1367 // If this replaces anything in the current scope, 1368 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1369 IEnd = IdResolver.end(); 1370 for (; I != IEnd; ++I) { 1371 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1372 S->RemoveDecl(*I); 1373 IdResolver.RemoveDecl(*I); 1374 1375 // Should only need to replace one decl. 1376 break; 1377 } 1378 } 1379 1380 S->AddDecl(D); 1381 1382 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1383 // Implicitly-generated labels may end up getting generated in an order that 1384 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1385 // the label at the appropriate place in the identifier chain. 1386 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1387 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1388 if (IDC == CurContext) { 1389 if (!S->isDeclScope(*I)) 1390 continue; 1391 } else if (IDC->Encloses(CurContext)) 1392 break; 1393 } 1394 1395 IdResolver.InsertDeclAfter(I, D); 1396 } else { 1397 IdResolver.AddDecl(D); 1398 } 1399 } 1400 1401 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1402 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1403 TUScope->AddDecl(D); 1404 } 1405 1406 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1407 bool AllowInlineNamespace) { 1408 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1409 } 1410 1411 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1412 DeclContext *TargetDC = DC->getPrimaryContext(); 1413 do { 1414 if (DeclContext *ScopeDC = S->getEntity()) 1415 if (ScopeDC->getPrimaryContext() == TargetDC) 1416 return S; 1417 } while ((S = S->getParent())); 1418 1419 return nullptr; 1420 } 1421 1422 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1423 DeclContext*, 1424 ASTContext&); 1425 1426 /// Filters out lookup results that don't fall within the given scope 1427 /// as determined by isDeclInScope. 1428 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1429 bool ConsiderLinkage, 1430 bool AllowInlineNamespace) { 1431 LookupResult::Filter F = R.makeFilter(); 1432 while (F.hasNext()) { 1433 NamedDecl *D = F.next(); 1434 1435 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1436 continue; 1437 1438 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1439 continue; 1440 1441 F.erase(); 1442 } 1443 1444 F.done(); 1445 } 1446 1447 static bool isUsingDecl(NamedDecl *D) { 1448 return isa<UsingShadowDecl>(D) || 1449 isa<UnresolvedUsingTypenameDecl>(D) || 1450 isa<UnresolvedUsingValueDecl>(D); 1451 } 1452 1453 /// Removes using shadow declarations from the lookup results. 1454 static void RemoveUsingDecls(LookupResult &R) { 1455 LookupResult::Filter F = R.makeFilter(); 1456 while (F.hasNext()) 1457 if (isUsingDecl(F.next())) 1458 F.erase(); 1459 1460 F.done(); 1461 } 1462 1463 /// \brief Check for this common pattern: 1464 /// @code 1465 /// class S { 1466 /// S(const S&); // DO NOT IMPLEMENT 1467 /// void operator=(const S&); // DO NOT IMPLEMENT 1468 /// }; 1469 /// @endcode 1470 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1471 // FIXME: Should check for private access too but access is set after we get 1472 // the decl here. 1473 if (D->doesThisDeclarationHaveABody()) 1474 return false; 1475 1476 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1477 return CD->isCopyConstructor(); 1478 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1479 return Method->isCopyAssignmentOperator(); 1480 return false; 1481 } 1482 1483 // We need this to handle 1484 // 1485 // typedef struct { 1486 // void *foo() { return 0; } 1487 // } A; 1488 // 1489 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1490 // for example. If 'A', foo will have external linkage. If we have '*A', 1491 // foo will have no linkage. Since we can't know until we get to the end 1492 // of the typedef, this function finds out if D might have non-external linkage. 1493 // Callers should verify at the end of the TU if it D has external linkage or 1494 // not. 1495 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1496 const DeclContext *DC = D->getDeclContext(); 1497 while (!DC->isTranslationUnit()) { 1498 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1499 if (!RD->hasNameForLinkage()) 1500 return true; 1501 } 1502 DC = DC->getParent(); 1503 } 1504 1505 return !D->isExternallyVisible(); 1506 } 1507 1508 // FIXME: This needs to be refactored; some other isInMainFile users want 1509 // these semantics. 1510 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1511 if (S.TUKind != TU_Complete) 1512 return false; 1513 return S.SourceMgr.isInMainFile(Loc); 1514 } 1515 1516 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1517 assert(D); 1518 1519 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1520 return false; 1521 1522 // Ignore all entities declared within templates, and out-of-line definitions 1523 // of members of class templates. 1524 if (D->getDeclContext()->isDependentContext() || 1525 D->getLexicalDeclContext()->isDependentContext()) 1526 return false; 1527 1528 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1529 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1530 return false; 1531 // A non-out-of-line declaration of a member specialization was implicitly 1532 // instantiated; it's the out-of-line declaration that we're interested in. 1533 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1534 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1535 return false; 1536 1537 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1538 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1539 return false; 1540 } else { 1541 // 'static inline' functions are defined in headers; don't warn. 1542 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1543 return false; 1544 } 1545 1546 if (FD->doesThisDeclarationHaveABody() && 1547 Context.DeclMustBeEmitted(FD)) 1548 return false; 1549 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1550 // Constants and utility variables are defined in headers with internal 1551 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1552 // like "inline".) 1553 if (!isMainFileLoc(*this, VD->getLocation())) 1554 return false; 1555 1556 if (Context.DeclMustBeEmitted(VD)) 1557 return false; 1558 1559 if (VD->isStaticDataMember() && 1560 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1561 return false; 1562 if (VD->isStaticDataMember() && 1563 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1564 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1565 return false; 1566 1567 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1568 return false; 1569 } else { 1570 return false; 1571 } 1572 1573 // Only warn for unused decls internal to the translation unit. 1574 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1575 // for inline functions defined in the main source file, for instance. 1576 return mightHaveNonExternalLinkage(D); 1577 } 1578 1579 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1580 if (!D) 1581 return; 1582 1583 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1584 const FunctionDecl *First = FD->getFirstDecl(); 1585 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1586 return; // First should already be in the vector. 1587 } 1588 1589 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1590 const VarDecl *First = VD->getFirstDecl(); 1591 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1592 return; // First should already be in the vector. 1593 } 1594 1595 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1596 UnusedFileScopedDecls.push_back(D); 1597 } 1598 1599 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1600 if (D->isInvalidDecl()) 1601 return false; 1602 1603 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1604 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1605 return false; 1606 1607 if (isa<LabelDecl>(D)) 1608 return true; 1609 1610 // Except for labels, we only care about unused decls that are local to 1611 // functions. 1612 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1613 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1614 // For dependent types, the diagnostic is deferred. 1615 WithinFunction = 1616 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1617 if (!WithinFunction) 1618 return false; 1619 1620 if (isa<TypedefNameDecl>(D)) 1621 return true; 1622 1623 // White-list anything that isn't a local variable. 1624 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1625 return false; 1626 1627 // Types of valid local variables should be complete, so this should succeed. 1628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1629 1630 // White-list anything with an __attribute__((unused)) type. 1631 const auto *Ty = VD->getType().getTypePtr(); 1632 1633 // Only look at the outermost level of typedef. 1634 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1635 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1636 return false; 1637 } 1638 1639 // If we failed to complete the type for some reason, or if the type is 1640 // dependent, don't diagnose the variable. 1641 if (Ty->isIncompleteType() || Ty->isDependentType()) 1642 return false; 1643 1644 // Look at the element type to ensure that the warning behaviour is 1645 // consistent for both scalars and arrays. 1646 Ty = Ty->getBaseElementTypeUnsafe(); 1647 1648 if (const TagType *TT = Ty->getAs<TagType>()) { 1649 const TagDecl *Tag = TT->getDecl(); 1650 if (Tag->hasAttr<UnusedAttr>()) 1651 return false; 1652 1653 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1654 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1655 return false; 1656 1657 if (const Expr *Init = VD->getInit()) { 1658 if (const ExprWithCleanups *Cleanups = 1659 dyn_cast<ExprWithCleanups>(Init)) 1660 Init = Cleanups->getSubExpr(); 1661 const CXXConstructExpr *Construct = 1662 dyn_cast<CXXConstructExpr>(Init); 1663 if (Construct && !Construct->isElidable()) { 1664 CXXConstructorDecl *CD = Construct->getConstructor(); 1665 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1666 return false; 1667 } 1668 } 1669 } 1670 } 1671 1672 // TODO: __attribute__((unused)) templates? 1673 } 1674 1675 return true; 1676 } 1677 1678 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1679 FixItHint &Hint) { 1680 if (isa<LabelDecl>(D)) { 1681 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1682 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1683 if (AfterColon.isInvalid()) 1684 return; 1685 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1686 getCharRange(D->getLocStart(), AfterColon)); 1687 } 1688 } 1689 1690 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1691 if (D->getTypeForDecl()->isDependentType()) 1692 return; 1693 1694 for (auto *TmpD : D->decls()) { 1695 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1696 DiagnoseUnusedDecl(T); 1697 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1698 DiagnoseUnusedNestedTypedefs(R); 1699 } 1700 } 1701 1702 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1703 /// unless they are marked attr(unused). 1704 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1705 if (!ShouldDiagnoseUnusedDecl(D)) 1706 return; 1707 1708 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1709 // typedefs can be referenced later on, so the diagnostics are emitted 1710 // at end-of-translation-unit. 1711 UnusedLocalTypedefNameCandidates.insert(TD); 1712 return; 1713 } 1714 1715 FixItHint Hint; 1716 GenerateFixForUnusedDecl(D, Context, Hint); 1717 1718 unsigned DiagID; 1719 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1720 DiagID = diag::warn_unused_exception_param; 1721 else if (isa<LabelDecl>(D)) 1722 DiagID = diag::warn_unused_label; 1723 else 1724 DiagID = diag::warn_unused_variable; 1725 1726 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1727 } 1728 1729 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1730 // Verify that we have no forward references left. If so, there was a goto 1731 // or address of a label taken, but no definition of it. Label fwd 1732 // definitions are indicated with a null substmt which is also not a resolved 1733 // MS inline assembly label name. 1734 bool Diagnose = false; 1735 if (L->isMSAsmLabel()) 1736 Diagnose = !L->isResolvedMSAsmLabel(); 1737 else 1738 Diagnose = L->getStmt() == nullptr; 1739 if (Diagnose) 1740 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1741 } 1742 1743 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1744 S->mergeNRVOIntoParent(); 1745 1746 if (S->decl_empty()) return; 1747 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1748 "Scope shouldn't contain decls!"); 1749 1750 for (auto *TmpD : S->decls()) { 1751 assert(TmpD && "This decl didn't get pushed??"); 1752 1753 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1754 NamedDecl *D = cast<NamedDecl>(TmpD); 1755 1756 if (!D->getDeclName()) continue; 1757 1758 // Diagnose unused variables in this scope. 1759 if (!S->hasUnrecoverableErrorOccurred()) { 1760 DiagnoseUnusedDecl(D); 1761 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1762 DiagnoseUnusedNestedTypedefs(RD); 1763 } 1764 1765 // If this was a forward reference to a label, verify it was defined. 1766 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1767 CheckPoppedLabel(LD, *this); 1768 1769 // Remove this name from our lexical scope, and warn on it if we haven't 1770 // already. 1771 IdResolver.RemoveDecl(D); 1772 auto ShadowI = ShadowingDecls.find(D); 1773 if (ShadowI != ShadowingDecls.end()) { 1774 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1775 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1776 << D << FD << FD->getParent(); 1777 Diag(FD->getLocation(), diag::note_previous_declaration); 1778 } 1779 ShadowingDecls.erase(ShadowI); 1780 } 1781 } 1782 } 1783 1784 /// \brief Look for an Objective-C class in the translation unit. 1785 /// 1786 /// \param Id The name of the Objective-C class we're looking for. If 1787 /// typo-correction fixes this name, the Id will be updated 1788 /// to the fixed name. 1789 /// 1790 /// \param IdLoc The location of the name in the translation unit. 1791 /// 1792 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1793 /// if there is no class with the given name. 1794 /// 1795 /// \returns The declaration of the named Objective-C class, or NULL if the 1796 /// class could not be found. 1797 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1798 SourceLocation IdLoc, 1799 bool DoTypoCorrection) { 1800 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1801 // creation from this context. 1802 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1803 1804 if (!IDecl && DoTypoCorrection) { 1805 // Perform typo correction at the given location, but only if we 1806 // find an Objective-C class name. 1807 if (TypoCorrection C = CorrectTypo( 1808 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1809 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1810 CTK_ErrorRecovery)) { 1811 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1812 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1813 Id = IDecl->getIdentifier(); 1814 } 1815 } 1816 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1817 // This routine must always return a class definition, if any. 1818 if (Def && Def->getDefinition()) 1819 Def = Def->getDefinition(); 1820 return Def; 1821 } 1822 1823 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1824 /// from S, where a non-field would be declared. This routine copes 1825 /// with the difference between C and C++ scoping rules in structs and 1826 /// unions. For example, the following code is well-formed in C but 1827 /// ill-formed in C++: 1828 /// @code 1829 /// struct S6 { 1830 /// enum { BAR } e; 1831 /// }; 1832 /// 1833 /// void test_S6() { 1834 /// struct S6 a; 1835 /// a.e = BAR; 1836 /// } 1837 /// @endcode 1838 /// For the declaration of BAR, this routine will return a different 1839 /// scope. The scope S will be the scope of the unnamed enumeration 1840 /// within S6. In C++, this routine will return the scope associated 1841 /// with S6, because the enumeration's scope is a transparent 1842 /// context but structures can contain non-field names. In C, this 1843 /// routine will return the translation unit scope, since the 1844 /// enumeration's scope is a transparent context and structures cannot 1845 /// contain non-field names. 1846 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1847 while (((S->getFlags() & Scope::DeclScope) == 0) || 1848 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1849 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1850 S = S->getParent(); 1851 return S; 1852 } 1853 1854 /// \brief Looks up the declaration of "struct objc_super" and 1855 /// saves it for later use in building builtin declaration of 1856 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1857 /// pre-existing declaration exists no action takes place. 1858 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1859 IdentifierInfo *II) { 1860 if (!II->isStr("objc_msgSendSuper")) 1861 return; 1862 ASTContext &Context = ThisSema.Context; 1863 1864 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1865 SourceLocation(), Sema::LookupTagName); 1866 ThisSema.LookupName(Result, S); 1867 if (Result.getResultKind() == LookupResult::Found) 1868 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1869 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1870 } 1871 1872 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1873 switch (Error) { 1874 case ASTContext::GE_None: 1875 return ""; 1876 case ASTContext::GE_Missing_stdio: 1877 return "stdio.h"; 1878 case ASTContext::GE_Missing_setjmp: 1879 return "setjmp.h"; 1880 case ASTContext::GE_Missing_ucontext: 1881 return "ucontext.h"; 1882 } 1883 llvm_unreachable("unhandled error kind"); 1884 } 1885 1886 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1887 /// file scope. lazily create a decl for it. ForRedeclaration is true 1888 /// if we're creating this built-in in anticipation of redeclaring the 1889 /// built-in. 1890 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1891 Scope *S, bool ForRedeclaration, 1892 SourceLocation Loc) { 1893 LookupPredefedObjCSuperType(*this, S, II); 1894 1895 ASTContext::GetBuiltinTypeError Error; 1896 QualType R = Context.GetBuiltinType(ID, Error); 1897 if (Error) { 1898 if (ForRedeclaration) 1899 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1900 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1901 return nullptr; 1902 } 1903 1904 if (!ForRedeclaration && 1905 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1906 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1907 Diag(Loc, diag::ext_implicit_lib_function_decl) 1908 << Context.BuiltinInfo.getName(ID) << R; 1909 if (Context.BuiltinInfo.getHeaderName(ID) && 1910 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1911 Diag(Loc, diag::note_include_header_or_declare) 1912 << Context.BuiltinInfo.getHeaderName(ID) 1913 << Context.BuiltinInfo.getName(ID); 1914 } 1915 1916 if (R.isNull()) 1917 return nullptr; 1918 1919 DeclContext *Parent = Context.getTranslationUnitDecl(); 1920 if (getLangOpts().CPlusPlus) { 1921 LinkageSpecDecl *CLinkageDecl = 1922 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1923 LinkageSpecDecl::lang_c, false); 1924 CLinkageDecl->setImplicit(); 1925 Parent->addDecl(CLinkageDecl); 1926 Parent = CLinkageDecl; 1927 } 1928 1929 FunctionDecl *New = FunctionDecl::Create(Context, 1930 Parent, 1931 Loc, Loc, II, R, /*TInfo=*/nullptr, 1932 SC_Extern, 1933 false, 1934 R->isFunctionProtoType()); 1935 New->setImplicit(); 1936 1937 // Create Decl objects for each parameter, adding them to the 1938 // FunctionDecl. 1939 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1940 SmallVector<ParmVarDecl*, 16> Params; 1941 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1942 ParmVarDecl *parm = 1943 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1944 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1945 SC_None, nullptr); 1946 parm->setScopeInfo(0, i); 1947 Params.push_back(parm); 1948 } 1949 New->setParams(Params); 1950 } 1951 1952 AddKnownFunctionAttributes(New); 1953 RegisterLocallyScopedExternCDecl(New, S); 1954 1955 // TUScope is the translation-unit scope to insert this function into. 1956 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1957 // relate Scopes to DeclContexts, and probably eliminate CurContext 1958 // entirely, but we're not there yet. 1959 DeclContext *SavedContext = CurContext; 1960 CurContext = Parent; 1961 PushOnScopeChains(New, TUScope); 1962 CurContext = SavedContext; 1963 return New; 1964 } 1965 1966 /// Typedef declarations don't have linkage, but they still denote the same 1967 /// entity if their types are the same. 1968 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1969 /// isSameEntity. 1970 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1971 TypedefNameDecl *Decl, 1972 LookupResult &Previous) { 1973 // This is only interesting when modules are enabled. 1974 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1975 return; 1976 1977 // Empty sets are uninteresting. 1978 if (Previous.empty()) 1979 return; 1980 1981 LookupResult::Filter Filter = Previous.makeFilter(); 1982 while (Filter.hasNext()) { 1983 NamedDecl *Old = Filter.next(); 1984 1985 // Non-hidden declarations are never ignored. 1986 if (S.isVisible(Old)) 1987 continue; 1988 1989 // Declarations of the same entity are not ignored, even if they have 1990 // different linkages. 1991 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1992 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1993 Decl->getUnderlyingType())) 1994 continue; 1995 1996 // If both declarations give a tag declaration a typedef name for linkage 1997 // purposes, then they declare the same entity. 1998 if (S.getLangOpts().CPlusPlus && 1999 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2000 Decl->getAnonDeclWithTypedefName()) 2001 continue; 2002 } 2003 2004 Filter.erase(); 2005 } 2006 2007 Filter.done(); 2008 } 2009 2010 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2011 QualType OldType; 2012 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2013 OldType = OldTypedef->getUnderlyingType(); 2014 else 2015 OldType = Context.getTypeDeclType(Old); 2016 QualType NewType = New->getUnderlyingType(); 2017 2018 if (NewType->isVariablyModifiedType()) { 2019 // Must not redefine a typedef with a variably-modified type. 2020 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2021 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2022 << Kind << NewType; 2023 if (Old->getLocation().isValid()) 2024 notePreviousDefinition(Old, New->getLocation()); 2025 New->setInvalidDecl(); 2026 return true; 2027 } 2028 2029 if (OldType != NewType && 2030 !OldType->isDependentType() && 2031 !NewType->isDependentType() && 2032 !Context.hasSameType(OldType, NewType)) { 2033 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2034 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2035 << Kind << NewType << OldType; 2036 if (Old->getLocation().isValid()) 2037 notePreviousDefinition(Old, New->getLocation()); 2038 New->setInvalidDecl(); 2039 return true; 2040 } 2041 return false; 2042 } 2043 2044 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2045 /// same name and scope as a previous declaration 'Old'. Figure out 2046 /// how to resolve this situation, merging decls or emitting 2047 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2048 /// 2049 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2050 LookupResult &OldDecls) { 2051 // If the new decl is known invalid already, don't bother doing any 2052 // merging checks. 2053 if (New->isInvalidDecl()) return; 2054 2055 // Allow multiple definitions for ObjC built-in typedefs. 2056 // FIXME: Verify the underlying types are equivalent! 2057 if (getLangOpts().ObjC1) { 2058 const IdentifierInfo *TypeID = New->getIdentifier(); 2059 switch (TypeID->getLength()) { 2060 default: break; 2061 case 2: 2062 { 2063 if (!TypeID->isStr("id")) 2064 break; 2065 QualType T = New->getUnderlyingType(); 2066 if (!T->isPointerType()) 2067 break; 2068 if (!T->isVoidPointerType()) { 2069 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2070 if (!PT->isStructureType()) 2071 break; 2072 } 2073 Context.setObjCIdRedefinitionType(T); 2074 // Install the built-in type for 'id', ignoring the current definition. 2075 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2076 return; 2077 } 2078 case 5: 2079 if (!TypeID->isStr("Class")) 2080 break; 2081 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2082 // Install the built-in type for 'Class', ignoring the current definition. 2083 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2084 return; 2085 case 3: 2086 if (!TypeID->isStr("SEL")) 2087 break; 2088 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2089 // Install the built-in type for 'SEL', ignoring the current definition. 2090 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2091 return; 2092 } 2093 // Fall through - the typedef name was not a builtin type. 2094 } 2095 2096 // Verify the old decl was also a type. 2097 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2098 if (!Old) { 2099 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2100 << New->getDeclName(); 2101 2102 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2103 if (OldD->getLocation().isValid()) 2104 notePreviousDefinition(OldD, New->getLocation()); 2105 2106 return New->setInvalidDecl(); 2107 } 2108 2109 // If the old declaration is invalid, just give up here. 2110 if (Old->isInvalidDecl()) 2111 return New->setInvalidDecl(); 2112 2113 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2114 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2115 auto *NewTag = New->getAnonDeclWithTypedefName(); 2116 NamedDecl *Hidden = nullptr; 2117 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2118 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2119 !hasVisibleDefinition(OldTag, &Hidden)) { 2120 // There is a definition of this tag, but it is not visible. Use it 2121 // instead of our tag. 2122 New->setTypeForDecl(OldTD->getTypeForDecl()); 2123 if (OldTD->isModed()) 2124 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2125 OldTD->getUnderlyingType()); 2126 else 2127 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2128 2129 // Make the old tag definition visible. 2130 makeMergedDefinitionVisible(Hidden); 2131 2132 // If this was an unscoped enumeration, yank all of its enumerators 2133 // out of the scope. 2134 if (isa<EnumDecl>(NewTag)) { 2135 Scope *EnumScope = getNonFieldDeclScope(S); 2136 for (auto *D : NewTag->decls()) { 2137 auto *ED = cast<EnumConstantDecl>(D); 2138 assert(EnumScope->isDeclScope(ED)); 2139 EnumScope->RemoveDecl(ED); 2140 IdResolver.RemoveDecl(ED); 2141 ED->getLexicalDeclContext()->removeDecl(ED); 2142 } 2143 } 2144 } 2145 } 2146 2147 // If the typedef types are not identical, reject them in all languages and 2148 // with any extensions enabled. 2149 if (isIncompatibleTypedef(Old, New)) 2150 return; 2151 2152 // The types match. Link up the redeclaration chain and merge attributes if 2153 // the old declaration was a typedef. 2154 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2155 New->setPreviousDecl(Typedef); 2156 mergeDeclAttributes(New, Old); 2157 } 2158 2159 if (getLangOpts().MicrosoftExt) 2160 return; 2161 2162 if (getLangOpts().CPlusPlus) { 2163 // C++ [dcl.typedef]p2: 2164 // In a given non-class scope, a typedef specifier can be used to 2165 // redefine the name of any type declared in that scope to refer 2166 // to the type to which it already refers. 2167 if (!isa<CXXRecordDecl>(CurContext)) 2168 return; 2169 2170 // C++0x [dcl.typedef]p4: 2171 // In a given class scope, a typedef specifier can be used to redefine 2172 // any class-name declared in that scope that is not also a typedef-name 2173 // to refer to the type to which it already refers. 2174 // 2175 // This wording came in via DR424, which was a correction to the 2176 // wording in DR56, which accidentally banned code like: 2177 // 2178 // struct S { 2179 // typedef struct A { } A; 2180 // }; 2181 // 2182 // in the C++03 standard. We implement the C++0x semantics, which 2183 // allow the above but disallow 2184 // 2185 // struct S { 2186 // typedef int I; 2187 // typedef int I; 2188 // }; 2189 // 2190 // since that was the intent of DR56. 2191 if (!isa<TypedefNameDecl>(Old)) 2192 return; 2193 2194 Diag(New->getLocation(), diag::err_redefinition) 2195 << New->getDeclName(); 2196 notePreviousDefinition(Old, New->getLocation()); 2197 return New->setInvalidDecl(); 2198 } 2199 2200 // Modules always permit redefinition of typedefs, as does C11. 2201 if (getLangOpts().Modules || getLangOpts().C11) 2202 return; 2203 2204 // If we have a redefinition of a typedef in C, emit a warning. This warning 2205 // is normally mapped to an error, but can be controlled with 2206 // -Wtypedef-redefinition. If either the original or the redefinition is 2207 // in a system header, don't emit this for compatibility with GCC. 2208 if (getDiagnostics().getSuppressSystemWarnings() && 2209 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2210 (Old->isImplicit() || 2211 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2212 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2213 return; 2214 2215 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2216 << New->getDeclName(); 2217 notePreviousDefinition(Old, New->getLocation()); 2218 } 2219 2220 /// DeclhasAttr - returns true if decl Declaration already has the target 2221 /// attribute. 2222 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2223 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2224 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2225 for (const auto *i : D->attrs()) 2226 if (i->getKind() == A->getKind()) { 2227 if (Ann) { 2228 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2229 return true; 2230 continue; 2231 } 2232 // FIXME: Don't hardcode this check 2233 if (OA && isa<OwnershipAttr>(i)) 2234 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2235 return true; 2236 } 2237 2238 return false; 2239 } 2240 2241 static bool isAttributeTargetADefinition(Decl *D) { 2242 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2243 return VD->isThisDeclarationADefinition(); 2244 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2245 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2246 return true; 2247 } 2248 2249 /// Merge alignment attributes from \p Old to \p New, taking into account the 2250 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2251 /// 2252 /// \return \c true if any attributes were added to \p New. 2253 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2254 // Look for alignas attributes on Old, and pick out whichever attribute 2255 // specifies the strictest alignment requirement. 2256 AlignedAttr *OldAlignasAttr = nullptr; 2257 AlignedAttr *OldStrictestAlignAttr = nullptr; 2258 unsigned OldAlign = 0; 2259 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2260 // FIXME: We have no way of representing inherited dependent alignments 2261 // in a case like: 2262 // template<int A, int B> struct alignas(A) X; 2263 // template<int A, int B> struct alignas(B) X {}; 2264 // For now, we just ignore any alignas attributes which are not on the 2265 // definition in such a case. 2266 if (I->isAlignmentDependent()) 2267 return false; 2268 2269 if (I->isAlignas()) 2270 OldAlignasAttr = I; 2271 2272 unsigned Align = I->getAlignment(S.Context); 2273 if (Align > OldAlign) { 2274 OldAlign = Align; 2275 OldStrictestAlignAttr = I; 2276 } 2277 } 2278 2279 // Look for alignas attributes on New. 2280 AlignedAttr *NewAlignasAttr = nullptr; 2281 unsigned NewAlign = 0; 2282 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2283 if (I->isAlignmentDependent()) 2284 return false; 2285 2286 if (I->isAlignas()) 2287 NewAlignasAttr = I; 2288 2289 unsigned Align = I->getAlignment(S.Context); 2290 if (Align > NewAlign) 2291 NewAlign = Align; 2292 } 2293 2294 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2295 // Both declarations have 'alignas' attributes. We require them to match. 2296 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2297 // fall short. (If two declarations both have alignas, they must both match 2298 // every definition, and so must match each other if there is a definition.) 2299 2300 // If either declaration only contains 'alignas(0)' specifiers, then it 2301 // specifies the natural alignment for the type. 2302 if (OldAlign == 0 || NewAlign == 0) { 2303 QualType Ty; 2304 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2305 Ty = VD->getType(); 2306 else 2307 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2308 2309 if (OldAlign == 0) 2310 OldAlign = S.Context.getTypeAlign(Ty); 2311 if (NewAlign == 0) 2312 NewAlign = S.Context.getTypeAlign(Ty); 2313 } 2314 2315 if (OldAlign != NewAlign) { 2316 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2317 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2318 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2319 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2320 } 2321 } 2322 2323 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2324 // C++11 [dcl.align]p6: 2325 // if any declaration of an entity has an alignment-specifier, 2326 // every defining declaration of that entity shall specify an 2327 // equivalent alignment. 2328 // C11 6.7.5/7: 2329 // If the definition of an object does not have an alignment 2330 // specifier, any other declaration of that object shall also 2331 // have no alignment specifier. 2332 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2333 << OldAlignasAttr; 2334 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2335 << OldAlignasAttr; 2336 } 2337 2338 bool AnyAdded = false; 2339 2340 // Ensure we have an attribute representing the strictest alignment. 2341 if (OldAlign > NewAlign) { 2342 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2343 Clone->setInherited(true); 2344 New->addAttr(Clone); 2345 AnyAdded = true; 2346 } 2347 2348 // Ensure we have an alignas attribute if the old declaration had one. 2349 if (OldAlignasAttr && !NewAlignasAttr && 2350 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2351 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2352 Clone->setInherited(true); 2353 New->addAttr(Clone); 2354 AnyAdded = true; 2355 } 2356 2357 return AnyAdded; 2358 } 2359 2360 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2361 const InheritableAttr *Attr, 2362 Sema::AvailabilityMergeKind AMK) { 2363 // This function copies an attribute Attr from a previous declaration to the 2364 // new declaration D if the new declaration doesn't itself have that attribute 2365 // yet or if that attribute allows duplicates. 2366 // If you're adding a new attribute that requires logic different from 2367 // "use explicit attribute on decl if present, else use attribute from 2368 // previous decl", for example if the attribute needs to be consistent 2369 // between redeclarations, you need to call a custom merge function here. 2370 InheritableAttr *NewAttr = nullptr; 2371 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2372 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2373 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2374 AA->isImplicit(), AA->getIntroduced(), 2375 AA->getDeprecated(), 2376 AA->getObsoleted(), AA->getUnavailable(), 2377 AA->getMessage(), AA->getStrict(), 2378 AA->getReplacement(), AMK, 2379 AttrSpellingListIndex); 2380 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2381 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2382 AttrSpellingListIndex); 2383 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2384 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2385 AttrSpellingListIndex); 2386 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2387 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2388 AttrSpellingListIndex); 2389 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2390 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2391 AttrSpellingListIndex); 2392 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2393 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2394 FA->getFormatIdx(), FA->getFirstArg(), 2395 AttrSpellingListIndex); 2396 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2397 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2398 AttrSpellingListIndex); 2399 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2400 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2401 AttrSpellingListIndex, 2402 IA->getSemanticSpelling()); 2403 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2404 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2405 &S.Context.Idents.get(AA->getSpelling()), 2406 AttrSpellingListIndex); 2407 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2408 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2409 isa<CUDAGlobalAttr>(Attr))) { 2410 // CUDA target attributes are part of function signature for 2411 // overloading purposes and must not be merged. 2412 return false; 2413 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2414 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2415 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2416 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2417 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2418 NewAttr = S.mergeInternalLinkageAttr( 2419 D, InternalLinkageA->getRange(), 2420 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2421 AttrSpellingListIndex); 2422 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2423 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2424 &S.Context.Idents.get(CommonA->getSpelling()), 2425 AttrSpellingListIndex); 2426 else if (isa<AlignedAttr>(Attr)) 2427 // AlignedAttrs are handled separately, because we need to handle all 2428 // such attributes on a declaration at the same time. 2429 NewAttr = nullptr; 2430 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2431 (AMK == Sema::AMK_Override || 2432 AMK == Sema::AMK_ProtocolImplementation)) 2433 NewAttr = nullptr; 2434 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2435 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2436 UA->getGuid()); 2437 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2438 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2439 2440 if (NewAttr) { 2441 NewAttr->setInherited(true); 2442 D->addAttr(NewAttr); 2443 if (isa<MSInheritanceAttr>(NewAttr)) 2444 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2445 return true; 2446 } 2447 2448 return false; 2449 } 2450 2451 static const NamedDecl *getDefinition(const Decl *D) { 2452 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2453 return TD->getDefinition(); 2454 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2455 const VarDecl *Def = VD->getDefinition(); 2456 if (Def) 2457 return Def; 2458 return VD->getActingDefinition(); 2459 } 2460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2461 return FD->getDefinition(); 2462 return nullptr; 2463 } 2464 2465 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2466 for (const auto *Attribute : D->attrs()) 2467 if (Attribute->getKind() == Kind) 2468 return true; 2469 return false; 2470 } 2471 2472 /// checkNewAttributesAfterDef - If we already have a definition, check that 2473 /// there are no new attributes in this declaration. 2474 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2475 if (!New->hasAttrs()) 2476 return; 2477 2478 const NamedDecl *Def = getDefinition(Old); 2479 if (!Def || Def == New) 2480 return; 2481 2482 AttrVec &NewAttributes = New->getAttrs(); 2483 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2484 const Attr *NewAttribute = NewAttributes[I]; 2485 2486 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2487 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2488 Sema::SkipBodyInfo SkipBody; 2489 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2490 2491 // If we're skipping this definition, drop the "alias" attribute. 2492 if (SkipBody.ShouldSkip) { 2493 NewAttributes.erase(NewAttributes.begin() + I); 2494 --E; 2495 continue; 2496 } 2497 } else { 2498 VarDecl *VD = cast<VarDecl>(New); 2499 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2500 VarDecl::TentativeDefinition 2501 ? diag::err_alias_after_tentative 2502 : diag::err_redefinition; 2503 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2504 if (Diag == diag::err_redefinition) 2505 S.notePreviousDefinition(Def, VD->getLocation()); 2506 else 2507 S.Diag(Def->getLocation(), diag::note_previous_definition); 2508 VD->setInvalidDecl(); 2509 } 2510 ++I; 2511 continue; 2512 } 2513 2514 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2515 // Tentative definitions are only interesting for the alias check above. 2516 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2517 ++I; 2518 continue; 2519 } 2520 } 2521 2522 if (hasAttribute(Def, NewAttribute->getKind())) { 2523 ++I; 2524 continue; // regular attr merging will take care of validating this. 2525 } 2526 2527 if (isa<C11NoReturnAttr>(NewAttribute)) { 2528 // C's _Noreturn is allowed to be added to a function after it is defined. 2529 ++I; 2530 continue; 2531 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2532 if (AA->isAlignas()) { 2533 // C++11 [dcl.align]p6: 2534 // if any declaration of an entity has an alignment-specifier, 2535 // every defining declaration of that entity shall specify an 2536 // equivalent alignment. 2537 // C11 6.7.5/7: 2538 // If the definition of an object does not have an alignment 2539 // specifier, any other declaration of that object shall also 2540 // have no alignment specifier. 2541 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2542 << AA; 2543 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2544 << AA; 2545 NewAttributes.erase(NewAttributes.begin() + I); 2546 --E; 2547 continue; 2548 } 2549 } 2550 2551 S.Diag(NewAttribute->getLocation(), 2552 diag::warn_attribute_precede_definition); 2553 S.Diag(Def->getLocation(), diag::note_previous_definition); 2554 NewAttributes.erase(NewAttributes.begin() + I); 2555 --E; 2556 } 2557 } 2558 2559 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2560 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2561 AvailabilityMergeKind AMK) { 2562 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2563 UsedAttr *NewAttr = OldAttr->clone(Context); 2564 NewAttr->setInherited(true); 2565 New->addAttr(NewAttr); 2566 } 2567 2568 if (!Old->hasAttrs() && !New->hasAttrs()) 2569 return; 2570 2571 // Attributes declared post-definition are currently ignored. 2572 checkNewAttributesAfterDef(*this, New, Old); 2573 2574 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2575 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2576 if (OldA->getLabel() != NewA->getLabel()) { 2577 // This redeclaration changes __asm__ label. 2578 Diag(New->getLocation(), diag::err_different_asm_label); 2579 Diag(OldA->getLocation(), diag::note_previous_declaration); 2580 } 2581 } else if (Old->isUsed()) { 2582 // This redeclaration adds an __asm__ label to a declaration that has 2583 // already been ODR-used. 2584 Diag(New->getLocation(), diag::err_late_asm_label_name) 2585 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2586 } 2587 } 2588 2589 // Re-declaration cannot add abi_tag's. 2590 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2591 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2592 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2593 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2594 NewTag) == OldAbiTagAttr->tags_end()) { 2595 Diag(NewAbiTagAttr->getLocation(), 2596 diag::err_new_abi_tag_on_redeclaration) 2597 << NewTag; 2598 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2599 } 2600 } 2601 } else { 2602 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2603 Diag(Old->getLocation(), diag::note_previous_declaration); 2604 } 2605 } 2606 2607 if (!Old->hasAttrs()) 2608 return; 2609 2610 bool foundAny = New->hasAttrs(); 2611 2612 // Ensure that any moving of objects within the allocated map is done before 2613 // we process them. 2614 if (!foundAny) New->setAttrs(AttrVec()); 2615 2616 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2617 // Ignore deprecated/unavailable/availability attributes if requested. 2618 AvailabilityMergeKind LocalAMK = AMK_None; 2619 if (isa<DeprecatedAttr>(I) || 2620 isa<UnavailableAttr>(I) || 2621 isa<AvailabilityAttr>(I)) { 2622 switch (AMK) { 2623 case AMK_None: 2624 continue; 2625 2626 case AMK_Redeclaration: 2627 case AMK_Override: 2628 case AMK_ProtocolImplementation: 2629 LocalAMK = AMK; 2630 break; 2631 } 2632 } 2633 2634 // Already handled. 2635 if (isa<UsedAttr>(I)) 2636 continue; 2637 2638 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2639 foundAny = true; 2640 } 2641 2642 if (mergeAlignedAttrs(*this, New, Old)) 2643 foundAny = true; 2644 2645 if (!foundAny) New->dropAttrs(); 2646 } 2647 2648 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2649 /// to the new one. 2650 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2651 const ParmVarDecl *oldDecl, 2652 Sema &S) { 2653 // C++11 [dcl.attr.depend]p2: 2654 // The first declaration of a function shall specify the 2655 // carries_dependency attribute for its declarator-id if any declaration 2656 // of the function specifies the carries_dependency attribute. 2657 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2658 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2659 S.Diag(CDA->getLocation(), 2660 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2661 // Find the first declaration of the parameter. 2662 // FIXME: Should we build redeclaration chains for function parameters? 2663 const FunctionDecl *FirstFD = 2664 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2665 const ParmVarDecl *FirstVD = 2666 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2667 S.Diag(FirstVD->getLocation(), 2668 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2669 } 2670 2671 if (!oldDecl->hasAttrs()) 2672 return; 2673 2674 bool foundAny = newDecl->hasAttrs(); 2675 2676 // Ensure that any moving of objects within the allocated map is 2677 // done before we process them. 2678 if (!foundAny) newDecl->setAttrs(AttrVec()); 2679 2680 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2681 if (!DeclHasAttr(newDecl, I)) { 2682 InheritableAttr *newAttr = 2683 cast<InheritableParamAttr>(I->clone(S.Context)); 2684 newAttr->setInherited(true); 2685 newDecl->addAttr(newAttr); 2686 foundAny = true; 2687 } 2688 } 2689 2690 if (!foundAny) newDecl->dropAttrs(); 2691 } 2692 2693 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2694 const ParmVarDecl *OldParam, 2695 Sema &S) { 2696 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2697 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2698 if (*Oldnullability != *Newnullability) { 2699 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2700 << DiagNullabilityKind( 2701 *Newnullability, 2702 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2703 != 0)) 2704 << DiagNullabilityKind( 2705 *Oldnullability, 2706 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2707 != 0)); 2708 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2709 } 2710 } else { 2711 QualType NewT = NewParam->getType(); 2712 NewT = S.Context.getAttributedType( 2713 AttributedType::getNullabilityAttrKind(*Oldnullability), 2714 NewT, NewT); 2715 NewParam->setType(NewT); 2716 } 2717 } 2718 } 2719 2720 namespace { 2721 2722 /// Used in MergeFunctionDecl to keep track of function parameters in 2723 /// C. 2724 struct GNUCompatibleParamWarning { 2725 ParmVarDecl *OldParm; 2726 ParmVarDecl *NewParm; 2727 QualType PromotedType; 2728 }; 2729 2730 } // end anonymous namespace 2731 2732 /// getSpecialMember - get the special member enum for a method. 2733 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2734 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2735 if (Ctor->isDefaultConstructor()) 2736 return Sema::CXXDefaultConstructor; 2737 2738 if (Ctor->isCopyConstructor()) 2739 return Sema::CXXCopyConstructor; 2740 2741 if (Ctor->isMoveConstructor()) 2742 return Sema::CXXMoveConstructor; 2743 } else if (isa<CXXDestructorDecl>(MD)) { 2744 return Sema::CXXDestructor; 2745 } else if (MD->isCopyAssignmentOperator()) { 2746 return Sema::CXXCopyAssignment; 2747 } else if (MD->isMoveAssignmentOperator()) { 2748 return Sema::CXXMoveAssignment; 2749 } 2750 2751 return Sema::CXXInvalid; 2752 } 2753 2754 // Determine whether the previous declaration was a definition, implicit 2755 // declaration, or a declaration. 2756 template <typename T> 2757 static std::pair<diag::kind, SourceLocation> 2758 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2759 diag::kind PrevDiag; 2760 SourceLocation OldLocation = Old->getLocation(); 2761 if (Old->isThisDeclarationADefinition()) 2762 PrevDiag = diag::note_previous_definition; 2763 else if (Old->isImplicit()) { 2764 PrevDiag = diag::note_previous_implicit_declaration; 2765 if (OldLocation.isInvalid()) 2766 OldLocation = New->getLocation(); 2767 } else 2768 PrevDiag = diag::note_previous_declaration; 2769 return std::make_pair(PrevDiag, OldLocation); 2770 } 2771 2772 /// canRedefineFunction - checks if a function can be redefined. Currently, 2773 /// only extern inline functions can be redefined, and even then only in 2774 /// GNU89 mode. 2775 static bool canRedefineFunction(const FunctionDecl *FD, 2776 const LangOptions& LangOpts) { 2777 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2778 !LangOpts.CPlusPlus && 2779 FD->isInlineSpecified() && 2780 FD->getStorageClass() == SC_Extern); 2781 } 2782 2783 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2784 const AttributedType *AT = T->getAs<AttributedType>(); 2785 while (AT && !AT->isCallingConv()) 2786 AT = AT->getModifiedType()->getAs<AttributedType>(); 2787 return AT; 2788 } 2789 2790 template <typename T> 2791 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2792 const DeclContext *DC = Old->getDeclContext(); 2793 if (DC->isRecord()) 2794 return false; 2795 2796 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2797 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2798 return true; 2799 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2800 return true; 2801 return false; 2802 } 2803 2804 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2805 static bool isExternC(VarTemplateDecl *) { return false; } 2806 2807 /// \brief Check whether a redeclaration of an entity introduced by a 2808 /// using-declaration is valid, given that we know it's not an overload 2809 /// (nor a hidden tag declaration). 2810 template<typename ExpectedDecl> 2811 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2812 ExpectedDecl *New) { 2813 // C++11 [basic.scope.declarative]p4: 2814 // Given a set of declarations in a single declarative region, each of 2815 // which specifies the same unqualified name, 2816 // -- they shall all refer to the same entity, or all refer to functions 2817 // and function templates; or 2818 // -- exactly one declaration shall declare a class name or enumeration 2819 // name that is not a typedef name and the other declarations shall all 2820 // refer to the same variable or enumerator, or all refer to functions 2821 // and function templates; in this case the class name or enumeration 2822 // name is hidden (3.3.10). 2823 2824 // C++11 [namespace.udecl]p14: 2825 // If a function declaration in namespace scope or block scope has the 2826 // same name and the same parameter-type-list as a function introduced 2827 // by a using-declaration, and the declarations do not declare the same 2828 // function, the program is ill-formed. 2829 2830 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2831 if (Old && 2832 !Old->getDeclContext()->getRedeclContext()->Equals( 2833 New->getDeclContext()->getRedeclContext()) && 2834 !(isExternC(Old) && isExternC(New))) 2835 Old = nullptr; 2836 2837 if (!Old) { 2838 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2839 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2840 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2841 return true; 2842 } 2843 return false; 2844 } 2845 2846 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2847 const FunctionDecl *B) { 2848 assert(A->getNumParams() == B->getNumParams()); 2849 2850 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2851 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2852 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2853 if (AttrA == AttrB) 2854 return true; 2855 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2856 }; 2857 2858 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2859 } 2860 2861 /// MergeFunctionDecl - We just parsed a function 'New' from 2862 /// declarator D which has the same name and scope as a previous 2863 /// declaration 'Old'. Figure out how to resolve this situation, 2864 /// merging decls or emitting diagnostics as appropriate. 2865 /// 2866 /// In C++, New and Old must be declarations that are not 2867 /// overloaded. Use IsOverload to determine whether New and Old are 2868 /// overloaded, and to select the Old declaration that New should be 2869 /// merged with. 2870 /// 2871 /// Returns true if there was an error, false otherwise. 2872 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2873 Scope *S, bool MergeTypeWithOld) { 2874 // Verify the old decl was also a function. 2875 FunctionDecl *Old = OldD->getAsFunction(); 2876 if (!Old) { 2877 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2878 if (New->getFriendObjectKind()) { 2879 Diag(New->getLocation(), diag::err_using_decl_friend); 2880 Diag(Shadow->getTargetDecl()->getLocation(), 2881 diag::note_using_decl_target); 2882 Diag(Shadow->getUsingDecl()->getLocation(), 2883 diag::note_using_decl) << 0; 2884 return true; 2885 } 2886 2887 // Check whether the two declarations might declare the same function. 2888 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2889 return true; 2890 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2891 } else { 2892 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2893 << New->getDeclName(); 2894 notePreviousDefinition(OldD, New->getLocation()); 2895 return true; 2896 } 2897 } 2898 2899 // If the old declaration is invalid, just give up here. 2900 if (Old->isInvalidDecl()) 2901 return true; 2902 2903 diag::kind PrevDiag; 2904 SourceLocation OldLocation; 2905 std::tie(PrevDiag, OldLocation) = 2906 getNoteDiagForInvalidRedeclaration(Old, New); 2907 2908 // Don't complain about this if we're in GNU89 mode and the old function 2909 // is an extern inline function. 2910 // Don't complain about specializations. They are not supposed to have 2911 // storage classes. 2912 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2913 New->getStorageClass() == SC_Static && 2914 Old->hasExternalFormalLinkage() && 2915 !New->getTemplateSpecializationInfo() && 2916 !canRedefineFunction(Old, getLangOpts())) { 2917 if (getLangOpts().MicrosoftExt) { 2918 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2919 Diag(OldLocation, PrevDiag); 2920 } else { 2921 Diag(New->getLocation(), diag::err_static_non_static) << New; 2922 Diag(OldLocation, PrevDiag); 2923 return true; 2924 } 2925 } 2926 2927 if (New->hasAttr<InternalLinkageAttr>() && 2928 !Old->hasAttr<InternalLinkageAttr>()) { 2929 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2930 << New->getDeclName(); 2931 notePreviousDefinition(Old, New->getLocation()); 2932 New->dropAttr<InternalLinkageAttr>(); 2933 } 2934 2935 // If a function is first declared with a calling convention, but is later 2936 // declared or defined without one, all following decls assume the calling 2937 // convention of the first. 2938 // 2939 // It's OK if a function is first declared without a calling convention, 2940 // but is later declared or defined with the default calling convention. 2941 // 2942 // To test if either decl has an explicit calling convention, we look for 2943 // AttributedType sugar nodes on the type as written. If they are missing or 2944 // were canonicalized away, we assume the calling convention was implicit. 2945 // 2946 // Note also that we DO NOT return at this point, because we still have 2947 // other tests to run. 2948 QualType OldQType = Context.getCanonicalType(Old->getType()); 2949 QualType NewQType = Context.getCanonicalType(New->getType()); 2950 const FunctionType *OldType = cast<FunctionType>(OldQType); 2951 const FunctionType *NewType = cast<FunctionType>(NewQType); 2952 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2953 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2954 bool RequiresAdjustment = false; 2955 2956 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2957 FunctionDecl *First = Old->getFirstDecl(); 2958 const FunctionType *FT = 2959 First->getType().getCanonicalType()->castAs<FunctionType>(); 2960 FunctionType::ExtInfo FI = FT->getExtInfo(); 2961 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2962 if (!NewCCExplicit) { 2963 // Inherit the CC from the previous declaration if it was specified 2964 // there but not here. 2965 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2966 RequiresAdjustment = true; 2967 } else { 2968 // Calling conventions aren't compatible, so complain. 2969 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2970 Diag(New->getLocation(), diag::err_cconv_change) 2971 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2972 << !FirstCCExplicit 2973 << (!FirstCCExplicit ? "" : 2974 FunctionType::getNameForCallConv(FI.getCC())); 2975 2976 // Put the note on the first decl, since it is the one that matters. 2977 Diag(First->getLocation(), diag::note_previous_declaration); 2978 return true; 2979 } 2980 } 2981 2982 // FIXME: diagnose the other way around? 2983 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2984 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2985 RequiresAdjustment = true; 2986 } 2987 2988 // Merge regparm attribute. 2989 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2990 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2991 if (NewTypeInfo.getHasRegParm()) { 2992 Diag(New->getLocation(), diag::err_regparm_mismatch) 2993 << NewType->getRegParmType() 2994 << OldType->getRegParmType(); 2995 Diag(OldLocation, diag::note_previous_declaration); 2996 return true; 2997 } 2998 2999 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3000 RequiresAdjustment = true; 3001 } 3002 3003 // Merge ns_returns_retained attribute. 3004 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3005 if (NewTypeInfo.getProducesResult()) { 3006 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3007 << "'ns_returns_retained'"; 3008 Diag(OldLocation, diag::note_previous_declaration); 3009 return true; 3010 } 3011 3012 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3013 RequiresAdjustment = true; 3014 } 3015 3016 if (OldTypeInfo.getNoCallerSavedRegs() != 3017 NewTypeInfo.getNoCallerSavedRegs()) { 3018 if (NewTypeInfo.getNoCallerSavedRegs()) { 3019 AnyX86NoCallerSavedRegistersAttr *Attr = 3020 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3021 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3022 Diag(OldLocation, diag::note_previous_declaration); 3023 return true; 3024 } 3025 3026 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3027 RequiresAdjustment = true; 3028 } 3029 3030 if (RequiresAdjustment) { 3031 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3032 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3033 New->setType(QualType(AdjustedType, 0)); 3034 NewQType = Context.getCanonicalType(New->getType()); 3035 NewType = cast<FunctionType>(NewQType); 3036 } 3037 3038 // If this redeclaration makes the function inline, we may need to add it to 3039 // UndefinedButUsed. 3040 if (!Old->isInlined() && New->isInlined() && 3041 !New->hasAttr<GNUInlineAttr>() && 3042 !getLangOpts().GNUInline && 3043 Old->isUsed(false) && 3044 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3045 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3046 SourceLocation())); 3047 3048 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3049 // about it. 3050 if (New->hasAttr<GNUInlineAttr>() && 3051 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3052 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3053 } 3054 3055 // If pass_object_size params don't match up perfectly, this isn't a valid 3056 // redeclaration. 3057 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3058 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3059 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3060 << New->getDeclName(); 3061 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3062 return true; 3063 } 3064 3065 if (getLangOpts().CPlusPlus) { 3066 // C++1z [over.load]p2 3067 // Certain function declarations cannot be overloaded: 3068 // -- Function declarations that differ only in the return type, 3069 // the exception specification, or both cannot be overloaded. 3070 3071 // Check the exception specifications match. This may recompute the type of 3072 // both Old and New if it resolved exception specifications, so grab the 3073 // types again after this. Because this updates the type, we do this before 3074 // any of the other checks below, which may update the "de facto" NewQType 3075 // but do not necessarily update the type of New. 3076 if (CheckEquivalentExceptionSpec(Old, New)) 3077 return true; 3078 OldQType = Context.getCanonicalType(Old->getType()); 3079 NewQType = Context.getCanonicalType(New->getType()); 3080 3081 // Go back to the type source info to compare the declared return types, 3082 // per C++1y [dcl.type.auto]p13: 3083 // Redeclarations or specializations of a function or function template 3084 // with a declared return type that uses a placeholder type shall also 3085 // use that placeholder, not a deduced type. 3086 QualType OldDeclaredReturnType = 3087 (Old->getTypeSourceInfo() 3088 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3089 : OldType)->getReturnType(); 3090 QualType NewDeclaredReturnType = 3091 (New->getTypeSourceInfo() 3092 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3093 : NewType)->getReturnType(); 3094 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3095 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3096 New->isLocalExternDecl())) { 3097 QualType ResQT; 3098 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3099 OldDeclaredReturnType->isObjCObjectPointerType()) 3100 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3101 if (ResQT.isNull()) { 3102 if (New->isCXXClassMember() && New->isOutOfLine()) 3103 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3104 << New << New->getReturnTypeSourceRange(); 3105 else 3106 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3107 << New->getReturnTypeSourceRange(); 3108 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3109 << Old->getReturnTypeSourceRange(); 3110 return true; 3111 } 3112 else 3113 NewQType = ResQT; 3114 } 3115 3116 QualType OldReturnType = OldType->getReturnType(); 3117 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3118 if (OldReturnType != NewReturnType) { 3119 // If this function has a deduced return type and has already been 3120 // defined, copy the deduced value from the old declaration. 3121 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3122 if (OldAT && OldAT->isDeduced()) { 3123 New->setType( 3124 SubstAutoType(New->getType(), 3125 OldAT->isDependentType() ? Context.DependentTy 3126 : OldAT->getDeducedType())); 3127 NewQType = Context.getCanonicalType( 3128 SubstAutoType(NewQType, 3129 OldAT->isDependentType() ? Context.DependentTy 3130 : OldAT->getDeducedType())); 3131 } 3132 } 3133 3134 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3135 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3136 if (OldMethod && NewMethod) { 3137 // Preserve triviality. 3138 NewMethod->setTrivial(OldMethod->isTrivial()); 3139 3140 // MSVC allows explicit template specialization at class scope: 3141 // 2 CXXMethodDecls referring to the same function will be injected. 3142 // We don't want a redeclaration error. 3143 bool IsClassScopeExplicitSpecialization = 3144 OldMethod->isFunctionTemplateSpecialization() && 3145 NewMethod->isFunctionTemplateSpecialization(); 3146 bool isFriend = NewMethod->getFriendObjectKind(); 3147 3148 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3149 !IsClassScopeExplicitSpecialization) { 3150 // -- Member function declarations with the same name and the 3151 // same parameter types cannot be overloaded if any of them 3152 // is a static member function declaration. 3153 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3154 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3155 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3156 return true; 3157 } 3158 3159 // C++ [class.mem]p1: 3160 // [...] A member shall not be declared twice in the 3161 // member-specification, except that a nested class or member 3162 // class template can be declared and then later defined. 3163 if (!inTemplateInstantiation()) { 3164 unsigned NewDiag; 3165 if (isa<CXXConstructorDecl>(OldMethod)) 3166 NewDiag = diag::err_constructor_redeclared; 3167 else if (isa<CXXDestructorDecl>(NewMethod)) 3168 NewDiag = diag::err_destructor_redeclared; 3169 else if (isa<CXXConversionDecl>(NewMethod)) 3170 NewDiag = diag::err_conv_function_redeclared; 3171 else 3172 NewDiag = diag::err_member_redeclared; 3173 3174 Diag(New->getLocation(), NewDiag); 3175 } else { 3176 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3177 << New << New->getType(); 3178 } 3179 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3180 return true; 3181 3182 // Complain if this is an explicit declaration of a special 3183 // member that was initially declared implicitly. 3184 // 3185 // As an exception, it's okay to befriend such methods in order 3186 // to permit the implicit constructor/destructor/operator calls. 3187 } else if (OldMethod->isImplicit()) { 3188 if (isFriend) { 3189 NewMethod->setImplicit(); 3190 } else { 3191 Diag(NewMethod->getLocation(), 3192 diag::err_definition_of_implicitly_declared_member) 3193 << New << getSpecialMember(OldMethod); 3194 return true; 3195 } 3196 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3197 Diag(NewMethod->getLocation(), 3198 diag::err_definition_of_explicitly_defaulted_member) 3199 << getSpecialMember(OldMethod); 3200 return true; 3201 } 3202 } 3203 3204 // C++11 [dcl.attr.noreturn]p1: 3205 // The first declaration of a function shall specify the noreturn 3206 // attribute if any declaration of that function specifies the noreturn 3207 // attribute. 3208 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3209 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3210 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3211 Diag(Old->getFirstDecl()->getLocation(), 3212 diag::note_noreturn_missing_first_decl); 3213 } 3214 3215 // C++11 [dcl.attr.depend]p2: 3216 // The first declaration of a function shall specify the 3217 // carries_dependency attribute for its declarator-id if any declaration 3218 // of the function specifies the carries_dependency attribute. 3219 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3220 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3221 Diag(CDA->getLocation(), 3222 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3223 Diag(Old->getFirstDecl()->getLocation(), 3224 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3225 } 3226 3227 // (C++98 8.3.5p3): 3228 // All declarations for a function shall agree exactly in both the 3229 // return type and the parameter-type-list. 3230 // We also want to respect all the extended bits except noreturn. 3231 3232 // noreturn should now match unless the old type info didn't have it. 3233 QualType OldQTypeForComparison = OldQType; 3234 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3235 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3236 const FunctionType *OldTypeForComparison 3237 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3238 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3239 assert(OldQTypeForComparison.isCanonical()); 3240 } 3241 3242 if (haveIncompatibleLanguageLinkages(Old, New)) { 3243 // As a special case, retain the language linkage from previous 3244 // declarations of a friend function as an extension. 3245 // 3246 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3247 // and is useful because there's otherwise no way to specify language 3248 // linkage within class scope. 3249 // 3250 // Check cautiously as the friend object kind isn't yet complete. 3251 if (New->getFriendObjectKind() != Decl::FOK_None) { 3252 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3253 Diag(OldLocation, PrevDiag); 3254 } else { 3255 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3256 Diag(OldLocation, PrevDiag); 3257 return true; 3258 } 3259 } 3260 3261 if (OldQTypeForComparison == NewQType) 3262 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3263 3264 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3265 New->isLocalExternDecl()) { 3266 // It's OK if we couldn't merge types for a local function declaraton 3267 // if either the old or new type is dependent. We'll merge the types 3268 // when we instantiate the function. 3269 return false; 3270 } 3271 3272 // Fall through for conflicting redeclarations and redefinitions. 3273 } 3274 3275 // C: Function types need to be compatible, not identical. This handles 3276 // duplicate function decls like "void f(int); void f(enum X);" properly. 3277 if (!getLangOpts().CPlusPlus && 3278 Context.typesAreCompatible(OldQType, NewQType)) { 3279 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3280 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3281 const FunctionProtoType *OldProto = nullptr; 3282 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3283 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3284 // The old declaration provided a function prototype, but the 3285 // new declaration does not. Merge in the prototype. 3286 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3287 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3288 NewQType = 3289 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3290 OldProto->getExtProtoInfo()); 3291 New->setType(NewQType); 3292 New->setHasInheritedPrototype(); 3293 3294 // Synthesize parameters with the same types. 3295 SmallVector<ParmVarDecl*, 16> Params; 3296 for (const auto &ParamType : OldProto->param_types()) { 3297 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3298 SourceLocation(), nullptr, 3299 ParamType, /*TInfo=*/nullptr, 3300 SC_None, nullptr); 3301 Param->setScopeInfo(0, Params.size()); 3302 Param->setImplicit(); 3303 Params.push_back(Param); 3304 } 3305 3306 New->setParams(Params); 3307 } 3308 3309 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3310 } 3311 3312 // GNU C permits a K&R definition to follow a prototype declaration 3313 // if the declared types of the parameters in the K&R definition 3314 // match the types in the prototype declaration, even when the 3315 // promoted types of the parameters from the K&R definition differ 3316 // from the types in the prototype. GCC then keeps the types from 3317 // the prototype. 3318 // 3319 // If a variadic prototype is followed by a non-variadic K&R definition, 3320 // the K&R definition becomes variadic. This is sort of an edge case, but 3321 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3322 // C99 6.9.1p8. 3323 if (!getLangOpts().CPlusPlus && 3324 Old->hasPrototype() && !New->hasPrototype() && 3325 New->getType()->getAs<FunctionProtoType>() && 3326 Old->getNumParams() == New->getNumParams()) { 3327 SmallVector<QualType, 16> ArgTypes; 3328 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3329 const FunctionProtoType *OldProto 3330 = Old->getType()->getAs<FunctionProtoType>(); 3331 const FunctionProtoType *NewProto 3332 = New->getType()->getAs<FunctionProtoType>(); 3333 3334 // Determine whether this is the GNU C extension. 3335 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3336 NewProto->getReturnType()); 3337 bool LooseCompatible = !MergedReturn.isNull(); 3338 for (unsigned Idx = 0, End = Old->getNumParams(); 3339 LooseCompatible && Idx != End; ++Idx) { 3340 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3341 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3342 if (Context.typesAreCompatible(OldParm->getType(), 3343 NewProto->getParamType(Idx))) { 3344 ArgTypes.push_back(NewParm->getType()); 3345 } else if (Context.typesAreCompatible(OldParm->getType(), 3346 NewParm->getType(), 3347 /*CompareUnqualified=*/true)) { 3348 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3349 NewProto->getParamType(Idx) }; 3350 Warnings.push_back(Warn); 3351 ArgTypes.push_back(NewParm->getType()); 3352 } else 3353 LooseCompatible = false; 3354 } 3355 3356 if (LooseCompatible) { 3357 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3358 Diag(Warnings[Warn].NewParm->getLocation(), 3359 diag::ext_param_promoted_not_compatible_with_prototype) 3360 << Warnings[Warn].PromotedType 3361 << Warnings[Warn].OldParm->getType(); 3362 if (Warnings[Warn].OldParm->getLocation().isValid()) 3363 Diag(Warnings[Warn].OldParm->getLocation(), 3364 diag::note_previous_declaration); 3365 } 3366 3367 if (MergeTypeWithOld) 3368 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3369 OldProto->getExtProtoInfo())); 3370 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3371 } 3372 3373 // Fall through to diagnose conflicting types. 3374 } 3375 3376 // A function that has already been declared has been redeclared or 3377 // defined with a different type; show an appropriate diagnostic. 3378 3379 // If the previous declaration was an implicitly-generated builtin 3380 // declaration, then at the very least we should use a specialized note. 3381 unsigned BuiltinID; 3382 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3383 // If it's actually a library-defined builtin function like 'malloc' 3384 // or 'printf', just warn about the incompatible redeclaration. 3385 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3386 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3387 Diag(OldLocation, diag::note_previous_builtin_declaration) 3388 << Old << Old->getType(); 3389 3390 // If this is a global redeclaration, just forget hereafter 3391 // about the "builtin-ness" of the function. 3392 // 3393 // Doing this for local extern declarations is problematic. If 3394 // the builtin declaration remains visible, a second invalid 3395 // local declaration will produce a hard error; if it doesn't 3396 // remain visible, a single bogus local redeclaration (which is 3397 // actually only a warning) could break all the downstream code. 3398 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3399 New->getIdentifier()->revertBuiltin(); 3400 3401 return false; 3402 } 3403 3404 PrevDiag = diag::note_previous_builtin_declaration; 3405 } 3406 3407 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3408 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3409 return true; 3410 } 3411 3412 /// \brief Completes the merge of two function declarations that are 3413 /// known to be compatible. 3414 /// 3415 /// This routine handles the merging of attributes and other 3416 /// properties of function declarations from the old declaration to 3417 /// the new declaration, once we know that New is in fact a 3418 /// redeclaration of Old. 3419 /// 3420 /// \returns false 3421 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3422 Scope *S, bool MergeTypeWithOld) { 3423 // Merge the attributes 3424 mergeDeclAttributes(New, Old); 3425 3426 // Merge "pure" flag. 3427 if (Old->isPure()) 3428 New->setPure(); 3429 3430 // Merge "used" flag. 3431 if (Old->getMostRecentDecl()->isUsed(false)) 3432 New->setIsUsed(); 3433 3434 // Merge attributes from the parameters. These can mismatch with K&R 3435 // declarations. 3436 if (New->getNumParams() == Old->getNumParams()) 3437 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3438 ParmVarDecl *NewParam = New->getParamDecl(i); 3439 ParmVarDecl *OldParam = Old->getParamDecl(i); 3440 mergeParamDeclAttributes(NewParam, OldParam, *this); 3441 mergeParamDeclTypes(NewParam, OldParam, *this); 3442 } 3443 3444 if (getLangOpts().CPlusPlus) 3445 return MergeCXXFunctionDecl(New, Old, S); 3446 3447 // Merge the function types so the we get the composite types for the return 3448 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3449 // was visible. 3450 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3451 if (!Merged.isNull() && MergeTypeWithOld) 3452 New->setType(Merged); 3453 3454 return false; 3455 } 3456 3457 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3458 ObjCMethodDecl *oldMethod) { 3459 // Merge the attributes, including deprecated/unavailable 3460 AvailabilityMergeKind MergeKind = 3461 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3462 ? AMK_ProtocolImplementation 3463 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3464 : AMK_Override; 3465 3466 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3467 3468 // Merge attributes from the parameters. 3469 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3470 oe = oldMethod->param_end(); 3471 for (ObjCMethodDecl::param_iterator 3472 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3473 ni != ne && oi != oe; ++ni, ++oi) 3474 mergeParamDeclAttributes(*ni, *oi, *this); 3475 3476 CheckObjCMethodOverride(newMethod, oldMethod); 3477 } 3478 3479 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3480 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3481 3482 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3483 ? diag::err_redefinition_different_type 3484 : diag::err_redeclaration_different_type) 3485 << New->getDeclName() << New->getType() << Old->getType(); 3486 3487 diag::kind PrevDiag; 3488 SourceLocation OldLocation; 3489 std::tie(PrevDiag, OldLocation) 3490 = getNoteDiagForInvalidRedeclaration(Old, New); 3491 S.Diag(OldLocation, PrevDiag); 3492 New->setInvalidDecl(); 3493 } 3494 3495 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3496 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3497 /// emitting diagnostics as appropriate. 3498 /// 3499 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3500 /// to here in AddInitializerToDecl. We can't check them before the initializer 3501 /// is attached. 3502 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3503 bool MergeTypeWithOld) { 3504 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3505 return; 3506 3507 QualType MergedT; 3508 if (getLangOpts().CPlusPlus) { 3509 if (New->getType()->isUndeducedType()) { 3510 // We don't know what the new type is until the initializer is attached. 3511 return; 3512 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3513 // These could still be something that needs exception specs checked. 3514 return MergeVarDeclExceptionSpecs(New, Old); 3515 } 3516 // C++ [basic.link]p10: 3517 // [...] the types specified by all declarations referring to a given 3518 // object or function shall be identical, except that declarations for an 3519 // array object can specify array types that differ by the presence or 3520 // absence of a major array bound (8.3.4). 3521 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3522 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3523 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3524 3525 // We are merging a variable declaration New into Old. If it has an array 3526 // bound, and that bound differs from Old's bound, we should diagnose the 3527 // mismatch. 3528 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3529 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3530 PrevVD = PrevVD->getPreviousDecl()) { 3531 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3532 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3533 continue; 3534 3535 if (!Context.hasSameType(NewArray, PrevVDTy)) 3536 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3537 } 3538 } 3539 3540 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3541 if (Context.hasSameType(OldArray->getElementType(), 3542 NewArray->getElementType())) 3543 MergedT = New->getType(); 3544 } 3545 // FIXME: Check visibility. New is hidden but has a complete type. If New 3546 // has no array bound, it should not inherit one from Old, if Old is not 3547 // visible. 3548 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3549 if (Context.hasSameType(OldArray->getElementType(), 3550 NewArray->getElementType())) 3551 MergedT = Old->getType(); 3552 } 3553 } 3554 else if (New->getType()->isObjCObjectPointerType() && 3555 Old->getType()->isObjCObjectPointerType()) { 3556 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3557 Old->getType()); 3558 } 3559 } else { 3560 // C 6.2.7p2: 3561 // All declarations that refer to the same object or function shall have 3562 // compatible type. 3563 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3564 } 3565 if (MergedT.isNull()) { 3566 // It's OK if we couldn't merge types if either type is dependent, for a 3567 // block-scope variable. In other cases (static data members of class 3568 // templates, variable templates, ...), we require the types to be 3569 // equivalent. 3570 // FIXME: The C++ standard doesn't say anything about this. 3571 if ((New->getType()->isDependentType() || 3572 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3573 // If the old type was dependent, we can't merge with it, so the new type 3574 // becomes dependent for now. We'll reproduce the original type when we 3575 // instantiate the TypeSourceInfo for the variable. 3576 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3577 New->setType(Context.DependentTy); 3578 return; 3579 } 3580 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3581 } 3582 3583 // Don't actually update the type on the new declaration if the old 3584 // declaration was an extern declaration in a different scope. 3585 if (MergeTypeWithOld) 3586 New->setType(MergedT); 3587 } 3588 3589 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3590 LookupResult &Previous) { 3591 // C11 6.2.7p4: 3592 // For an identifier with internal or external linkage declared 3593 // in a scope in which a prior declaration of that identifier is 3594 // visible, if the prior declaration specifies internal or 3595 // external linkage, the type of the identifier at the later 3596 // declaration becomes the composite type. 3597 // 3598 // If the variable isn't visible, we do not merge with its type. 3599 if (Previous.isShadowed()) 3600 return false; 3601 3602 if (S.getLangOpts().CPlusPlus) { 3603 // C++11 [dcl.array]p3: 3604 // If there is a preceding declaration of the entity in the same 3605 // scope in which the bound was specified, an omitted array bound 3606 // is taken to be the same as in that earlier declaration. 3607 return NewVD->isPreviousDeclInSameBlockScope() || 3608 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3609 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3610 } else { 3611 // If the old declaration was function-local, don't merge with its 3612 // type unless we're in the same function. 3613 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3614 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3615 } 3616 } 3617 3618 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3619 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3620 /// situation, merging decls or emitting diagnostics as appropriate. 3621 /// 3622 /// Tentative definition rules (C99 6.9.2p2) are checked by 3623 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3624 /// definitions here, since the initializer hasn't been attached. 3625 /// 3626 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3627 // If the new decl is already invalid, don't do any other checking. 3628 if (New->isInvalidDecl()) 3629 return; 3630 3631 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3632 return; 3633 3634 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3635 3636 // Verify the old decl was also a variable or variable template. 3637 VarDecl *Old = nullptr; 3638 VarTemplateDecl *OldTemplate = nullptr; 3639 if (Previous.isSingleResult()) { 3640 if (NewTemplate) { 3641 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3642 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3643 3644 if (auto *Shadow = 3645 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3646 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3647 return New->setInvalidDecl(); 3648 } else { 3649 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3650 3651 if (auto *Shadow = 3652 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3653 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3654 return New->setInvalidDecl(); 3655 } 3656 } 3657 if (!Old) { 3658 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3659 << New->getDeclName(); 3660 notePreviousDefinition(Previous.getRepresentativeDecl(), 3661 New->getLocation()); 3662 return New->setInvalidDecl(); 3663 } 3664 3665 // Ensure the template parameters are compatible. 3666 if (NewTemplate && 3667 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3668 OldTemplate->getTemplateParameters(), 3669 /*Complain=*/true, TPL_TemplateMatch)) 3670 return New->setInvalidDecl(); 3671 3672 // C++ [class.mem]p1: 3673 // A member shall not be declared twice in the member-specification [...] 3674 // 3675 // Here, we need only consider static data members. 3676 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3677 Diag(New->getLocation(), diag::err_duplicate_member) 3678 << New->getIdentifier(); 3679 Diag(Old->getLocation(), diag::note_previous_declaration); 3680 New->setInvalidDecl(); 3681 } 3682 3683 mergeDeclAttributes(New, Old); 3684 // Warn if an already-declared variable is made a weak_import in a subsequent 3685 // declaration 3686 if (New->hasAttr<WeakImportAttr>() && 3687 Old->getStorageClass() == SC_None && 3688 !Old->hasAttr<WeakImportAttr>()) { 3689 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3690 notePreviousDefinition(Old, New->getLocation()); 3691 // Remove weak_import attribute on new declaration. 3692 New->dropAttr<WeakImportAttr>(); 3693 } 3694 3695 if (New->hasAttr<InternalLinkageAttr>() && 3696 !Old->hasAttr<InternalLinkageAttr>()) { 3697 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3698 << New->getDeclName(); 3699 notePreviousDefinition(Old, New->getLocation()); 3700 New->dropAttr<InternalLinkageAttr>(); 3701 } 3702 3703 // Merge the types. 3704 VarDecl *MostRecent = Old->getMostRecentDecl(); 3705 if (MostRecent != Old) { 3706 MergeVarDeclTypes(New, MostRecent, 3707 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3708 if (New->isInvalidDecl()) 3709 return; 3710 } 3711 3712 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3713 if (New->isInvalidDecl()) 3714 return; 3715 3716 diag::kind PrevDiag; 3717 SourceLocation OldLocation; 3718 std::tie(PrevDiag, OldLocation) = 3719 getNoteDiagForInvalidRedeclaration(Old, New); 3720 3721 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3722 if (New->getStorageClass() == SC_Static && 3723 !New->isStaticDataMember() && 3724 Old->hasExternalFormalLinkage()) { 3725 if (getLangOpts().MicrosoftExt) { 3726 Diag(New->getLocation(), diag::ext_static_non_static) 3727 << New->getDeclName(); 3728 Diag(OldLocation, PrevDiag); 3729 } else { 3730 Diag(New->getLocation(), diag::err_static_non_static) 3731 << New->getDeclName(); 3732 Diag(OldLocation, PrevDiag); 3733 return New->setInvalidDecl(); 3734 } 3735 } 3736 // C99 6.2.2p4: 3737 // For an identifier declared with the storage-class specifier 3738 // extern in a scope in which a prior declaration of that 3739 // identifier is visible,23) if the prior declaration specifies 3740 // internal or external linkage, the linkage of the identifier at 3741 // the later declaration is the same as the linkage specified at 3742 // the prior declaration. If no prior declaration is visible, or 3743 // if the prior declaration specifies no linkage, then the 3744 // identifier has external linkage. 3745 if (New->hasExternalStorage() && Old->hasLinkage()) 3746 /* Okay */; 3747 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3748 !New->isStaticDataMember() && 3749 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3750 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3751 Diag(OldLocation, PrevDiag); 3752 return New->setInvalidDecl(); 3753 } 3754 3755 // Check if extern is followed by non-extern and vice-versa. 3756 if (New->hasExternalStorage() && 3757 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3758 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3759 Diag(OldLocation, PrevDiag); 3760 return New->setInvalidDecl(); 3761 } 3762 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3763 !New->hasExternalStorage()) { 3764 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3765 Diag(OldLocation, PrevDiag); 3766 return New->setInvalidDecl(); 3767 } 3768 3769 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3770 3771 // FIXME: The test for external storage here seems wrong? We still 3772 // need to check for mismatches. 3773 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3774 // Don't complain about out-of-line definitions of static members. 3775 !(Old->getLexicalDeclContext()->isRecord() && 3776 !New->getLexicalDeclContext()->isRecord())) { 3777 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3778 Diag(OldLocation, PrevDiag); 3779 return New->setInvalidDecl(); 3780 } 3781 3782 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3783 if (VarDecl *Def = Old->getDefinition()) { 3784 // C++1z [dcl.fcn.spec]p4: 3785 // If the definition of a variable appears in a translation unit before 3786 // its first declaration as inline, the program is ill-formed. 3787 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3788 Diag(Def->getLocation(), diag::note_previous_definition); 3789 } 3790 } 3791 3792 // If this redeclaration makes the function inline, we may need to add it to 3793 // UndefinedButUsed. 3794 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3795 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3796 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3797 SourceLocation())); 3798 3799 if (New->getTLSKind() != Old->getTLSKind()) { 3800 if (!Old->getTLSKind()) { 3801 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3802 Diag(OldLocation, PrevDiag); 3803 } else if (!New->getTLSKind()) { 3804 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3805 Diag(OldLocation, PrevDiag); 3806 } else { 3807 // Do not allow redeclaration to change the variable between requiring 3808 // static and dynamic initialization. 3809 // FIXME: GCC allows this, but uses the TLS keyword on the first 3810 // declaration to determine the kind. Do we need to be compatible here? 3811 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3812 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3813 Diag(OldLocation, PrevDiag); 3814 } 3815 } 3816 3817 // C++ doesn't have tentative definitions, so go right ahead and check here. 3818 if (getLangOpts().CPlusPlus && 3819 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3820 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3821 Old->getCanonicalDecl()->isConstexpr()) { 3822 // This definition won't be a definition any more once it's been merged. 3823 Diag(New->getLocation(), 3824 diag::warn_deprecated_redundant_constexpr_static_def); 3825 } else if (VarDecl *Def = Old->getDefinition()) { 3826 if (checkVarDeclRedefinition(Def, New)) 3827 return; 3828 } 3829 } 3830 3831 if (haveIncompatibleLanguageLinkages(Old, New)) { 3832 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3833 Diag(OldLocation, PrevDiag); 3834 New->setInvalidDecl(); 3835 return; 3836 } 3837 3838 // Merge "used" flag. 3839 if (Old->getMostRecentDecl()->isUsed(false)) 3840 New->setIsUsed(); 3841 3842 // Keep a chain of previous declarations. 3843 New->setPreviousDecl(Old); 3844 if (NewTemplate) 3845 NewTemplate->setPreviousDecl(OldTemplate); 3846 3847 // Inherit access appropriately. 3848 New->setAccess(Old->getAccess()); 3849 if (NewTemplate) 3850 NewTemplate->setAccess(New->getAccess()); 3851 3852 if (Old->isInline()) 3853 New->setImplicitlyInline(); 3854 } 3855 3856 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 3857 SourceManager &SrcMgr = getSourceManager(); 3858 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 3859 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 3860 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 3861 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 3862 auto &HSI = PP.getHeaderSearchInfo(); 3863 StringRef HdrFilename = 3864 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 3865 3866 auto noteFromModuleOrInclude = [&](Module *Mod, 3867 SourceLocation IncLoc) -> bool { 3868 // Redefinition errors with modules are common with non modular mapped 3869 // headers, example: a non-modular header H in module A that also gets 3870 // included directly in a TU. Pointing twice to the same header/definition 3871 // is confusing, try to get better diagnostics when modules is on. 3872 if (IncLoc.isValid()) { 3873 if (Mod) { 3874 Diag(IncLoc, diag::note_redefinition_modules_same_file) 3875 << HdrFilename.str() << Mod->getFullModuleName(); 3876 if (!Mod->DefinitionLoc.isInvalid()) 3877 Diag(Mod->DefinitionLoc, diag::note_defined_here) 3878 << Mod->getFullModuleName(); 3879 } else { 3880 Diag(IncLoc, diag::note_redefinition_include_same_file) 3881 << HdrFilename.str(); 3882 } 3883 return true; 3884 } 3885 3886 return false; 3887 }; 3888 3889 // Is it the same file and same offset? Provide more information on why 3890 // this leads to a redefinition error. 3891 bool EmittedDiag = false; 3892 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 3893 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 3894 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 3895 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 3896 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 3897 3898 // If the header has no guards, emit a note suggesting one. 3899 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 3900 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 3901 3902 if (EmittedDiag) 3903 return; 3904 } 3905 3906 // Redefinition coming from different files or couldn't do better above. 3907 Diag(Old->getLocation(), diag::note_previous_definition); 3908 } 3909 3910 /// We've just determined that \p Old and \p New both appear to be definitions 3911 /// of the same variable. Either diagnose or fix the problem. 3912 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3913 if (!hasVisibleDefinition(Old) && 3914 (New->getFormalLinkage() == InternalLinkage || 3915 New->isInline() || 3916 New->getDescribedVarTemplate() || 3917 New->getNumTemplateParameterLists() || 3918 New->getDeclContext()->isDependentContext())) { 3919 // The previous definition is hidden, and multiple definitions are 3920 // permitted (in separate TUs). Demote this to a declaration. 3921 New->demoteThisDefinitionToDeclaration(); 3922 3923 // Make the canonical definition visible. 3924 if (auto *OldTD = Old->getDescribedVarTemplate()) 3925 makeMergedDefinitionVisible(OldTD); 3926 makeMergedDefinitionVisible(Old); 3927 return false; 3928 } else { 3929 Diag(New->getLocation(), diag::err_redefinition) << New; 3930 notePreviousDefinition(Old, New->getLocation()); 3931 New->setInvalidDecl(); 3932 return true; 3933 } 3934 } 3935 3936 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3937 /// no declarator (e.g. "struct foo;") is parsed. 3938 Decl * 3939 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3940 RecordDecl *&AnonRecord) { 3941 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3942 AnonRecord); 3943 } 3944 3945 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3946 // disambiguate entities defined in different scopes. 3947 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3948 // compatibility. 3949 // We will pick our mangling number depending on which version of MSVC is being 3950 // targeted. 3951 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3952 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3953 ? S->getMSCurManglingNumber() 3954 : S->getMSLastManglingNumber(); 3955 } 3956 3957 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3958 if (!Context.getLangOpts().CPlusPlus) 3959 return; 3960 3961 if (isa<CXXRecordDecl>(Tag->getParent())) { 3962 // If this tag is the direct child of a class, number it if 3963 // it is anonymous. 3964 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3965 return; 3966 MangleNumberingContext &MCtx = 3967 Context.getManglingNumberContext(Tag->getParent()); 3968 Context.setManglingNumber( 3969 Tag, MCtx.getManglingNumber( 3970 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3971 return; 3972 } 3973 3974 // If this tag isn't a direct child of a class, number it if it is local. 3975 Decl *ManglingContextDecl; 3976 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3977 Tag->getDeclContext(), ManglingContextDecl)) { 3978 Context.setManglingNumber( 3979 Tag, MCtx->getManglingNumber( 3980 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3981 } 3982 } 3983 3984 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3985 TypedefNameDecl *NewTD) { 3986 if (TagFromDeclSpec->isInvalidDecl()) 3987 return; 3988 3989 // Do nothing if the tag already has a name for linkage purposes. 3990 if (TagFromDeclSpec->hasNameForLinkage()) 3991 return; 3992 3993 // A well-formed anonymous tag must always be a TUK_Definition. 3994 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3995 3996 // The type must match the tag exactly; no qualifiers allowed. 3997 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3998 Context.getTagDeclType(TagFromDeclSpec))) { 3999 if (getLangOpts().CPlusPlus) 4000 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4001 return; 4002 } 4003 4004 // If we've already computed linkage for the anonymous tag, then 4005 // adding a typedef name for the anonymous decl can change that 4006 // linkage, which might be a serious problem. Diagnose this as 4007 // unsupported and ignore the typedef name. TODO: we should 4008 // pursue this as a language defect and establish a formal rule 4009 // for how to handle it. 4010 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4011 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4012 4013 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4014 tagLoc = getLocForEndOfToken(tagLoc); 4015 4016 llvm::SmallString<40> textToInsert; 4017 textToInsert += ' '; 4018 textToInsert += NewTD->getIdentifier()->getName(); 4019 Diag(tagLoc, diag::note_typedef_changes_linkage) 4020 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4021 return; 4022 } 4023 4024 // Otherwise, set this is the anon-decl typedef for the tag. 4025 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4026 } 4027 4028 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4029 switch (T) { 4030 case DeclSpec::TST_class: 4031 return 0; 4032 case DeclSpec::TST_struct: 4033 return 1; 4034 case DeclSpec::TST_interface: 4035 return 2; 4036 case DeclSpec::TST_union: 4037 return 3; 4038 case DeclSpec::TST_enum: 4039 return 4; 4040 default: 4041 llvm_unreachable("unexpected type specifier"); 4042 } 4043 } 4044 4045 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4046 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4047 /// parameters to cope with template friend declarations. 4048 Decl * 4049 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4050 MultiTemplateParamsArg TemplateParams, 4051 bool IsExplicitInstantiation, 4052 RecordDecl *&AnonRecord) { 4053 Decl *TagD = nullptr; 4054 TagDecl *Tag = nullptr; 4055 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4056 DS.getTypeSpecType() == DeclSpec::TST_struct || 4057 DS.getTypeSpecType() == DeclSpec::TST_interface || 4058 DS.getTypeSpecType() == DeclSpec::TST_union || 4059 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4060 TagD = DS.getRepAsDecl(); 4061 4062 if (!TagD) // We probably had an error 4063 return nullptr; 4064 4065 // Note that the above type specs guarantee that the 4066 // type rep is a Decl, whereas in many of the others 4067 // it's a Type. 4068 if (isa<TagDecl>(TagD)) 4069 Tag = cast<TagDecl>(TagD); 4070 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4071 Tag = CTD->getTemplatedDecl(); 4072 } 4073 4074 if (Tag) { 4075 handleTagNumbering(Tag, S); 4076 Tag->setFreeStanding(); 4077 if (Tag->isInvalidDecl()) 4078 return Tag; 4079 } 4080 4081 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4082 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4083 // or incomplete types shall not be restrict-qualified." 4084 if (TypeQuals & DeclSpec::TQ_restrict) 4085 Diag(DS.getRestrictSpecLoc(), 4086 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4087 << DS.getSourceRange(); 4088 } 4089 4090 if (DS.isInlineSpecified()) 4091 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4092 << getLangOpts().CPlusPlus1z; 4093 4094 if (DS.isConstexprSpecified()) { 4095 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4096 // and definitions of functions and variables. 4097 if (Tag) 4098 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4099 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4100 else 4101 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4102 // Don't emit warnings after this error. 4103 return TagD; 4104 } 4105 4106 if (DS.isConceptSpecified()) { 4107 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 4108 // either a function concept and its definition or a variable concept and 4109 // its initializer. 4110 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 4111 return TagD; 4112 } 4113 4114 DiagnoseFunctionSpecifiers(DS); 4115 4116 if (DS.isFriendSpecified()) { 4117 // If we're dealing with a decl but not a TagDecl, assume that 4118 // whatever routines created it handled the friendship aspect. 4119 if (TagD && !Tag) 4120 return nullptr; 4121 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4122 } 4123 4124 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4125 bool IsExplicitSpecialization = 4126 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4127 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4128 !IsExplicitInstantiation && !IsExplicitSpecialization && 4129 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4130 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4131 // nested-name-specifier unless it is an explicit instantiation 4132 // or an explicit specialization. 4133 // 4134 // FIXME: We allow class template partial specializations here too, per the 4135 // obvious intent of DR1819. 4136 // 4137 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4138 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4139 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4140 return nullptr; 4141 } 4142 4143 // Track whether this decl-specifier declares anything. 4144 bool DeclaresAnything = true; 4145 4146 // Handle anonymous struct definitions. 4147 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4148 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4149 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4150 if (getLangOpts().CPlusPlus || 4151 Record->getDeclContext()->isRecord()) { 4152 // If CurContext is a DeclContext that can contain statements, 4153 // RecursiveASTVisitor won't visit the decls that 4154 // BuildAnonymousStructOrUnion() will put into CurContext. 4155 // Also store them here so that they can be part of the 4156 // DeclStmt that gets created in this case. 4157 // FIXME: Also return the IndirectFieldDecls created by 4158 // BuildAnonymousStructOr union, for the same reason? 4159 if (CurContext->isFunctionOrMethod()) 4160 AnonRecord = Record; 4161 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4162 Context.getPrintingPolicy()); 4163 } 4164 4165 DeclaresAnything = false; 4166 } 4167 } 4168 4169 // C11 6.7.2.1p2: 4170 // A struct-declaration that does not declare an anonymous structure or 4171 // anonymous union shall contain a struct-declarator-list. 4172 // 4173 // This rule also existed in C89 and C99; the grammar for struct-declaration 4174 // did not permit a struct-declaration without a struct-declarator-list. 4175 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4176 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4177 // Check for Microsoft C extension: anonymous struct/union member. 4178 // Handle 2 kinds of anonymous struct/union: 4179 // struct STRUCT; 4180 // union UNION; 4181 // and 4182 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4183 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4184 if ((Tag && Tag->getDeclName()) || 4185 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4186 RecordDecl *Record = nullptr; 4187 if (Tag) 4188 Record = dyn_cast<RecordDecl>(Tag); 4189 else if (const RecordType *RT = 4190 DS.getRepAsType().get()->getAsStructureType()) 4191 Record = RT->getDecl(); 4192 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4193 Record = UT->getDecl(); 4194 4195 if (Record && getLangOpts().MicrosoftExt) { 4196 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4197 << Record->isUnion() << DS.getSourceRange(); 4198 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4199 } 4200 4201 DeclaresAnything = false; 4202 } 4203 } 4204 4205 // Skip all the checks below if we have a type error. 4206 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4207 (TagD && TagD->isInvalidDecl())) 4208 return TagD; 4209 4210 if (getLangOpts().CPlusPlus && 4211 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4212 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4213 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4214 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4215 DeclaresAnything = false; 4216 4217 if (!DS.isMissingDeclaratorOk()) { 4218 // Customize diagnostic for a typedef missing a name. 4219 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4220 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4221 << DS.getSourceRange(); 4222 else 4223 DeclaresAnything = false; 4224 } 4225 4226 if (DS.isModulePrivateSpecified() && 4227 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4228 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4229 << Tag->getTagKind() 4230 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4231 4232 ActOnDocumentableDecl(TagD); 4233 4234 // C 6.7/2: 4235 // A declaration [...] shall declare at least a declarator [...], a tag, 4236 // or the members of an enumeration. 4237 // C++ [dcl.dcl]p3: 4238 // [If there are no declarators], and except for the declaration of an 4239 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4240 // names into the program, or shall redeclare a name introduced by a 4241 // previous declaration. 4242 if (!DeclaresAnything) { 4243 // In C, we allow this as a (popular) extension / bug. Don't bother 4244 // producing further diagnostics for redundant qualifiers after this. 4245 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4246 return TagD; 4247 } 4248 4249 // C++ [dcl.stc]p1: 4250 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4251 // init-declarator-list of the declaration shall not be empty. 4252 // C++ [dcl.fct.spec]p1: 4253 // If a cv-qualifier appears in a decl-specifier-seq, the 4254 // init-declarator-list of the declaration shall not be empty. 4255 // 4256 // Spurious qualifiers here appear to be valid in C. 4257 unsigned DiagID = diag::warn_standalone_specifier; 4258 if (getLangOpts().CPlusPlus) 4259 DiagID = diag::ext_standalone_specifier; 4260 4261 // Note that a linkage-specification sets a storage class, but 4262 // 'extern "C" struct foo;' is actually valid and not theoretically 4263 // useless. 4264 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4265 if (SCS == DeclSpec::SCS_mutable) 4266 // Since mutable is not a viable storage class specifier in C, there is 4267 // no reason to treat it as an extension. Instead, diagnose as an error. 4268 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4269 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4270 Diag(DS.getStorageClassSpecLoc(), DiagID) 4271 << DeclSpec::getSpecifierName(SCS); 4272 } 4273 4274 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4275 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4276 << DeclSpec::getSpecifierName(TSCS); 4277 if (DS.getTypeQualifiers()) { 4278 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4279 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4280 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4281 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4282 // Restrict is covered above. 4283 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4284 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4285 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4286 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4287 } 4288 4289 // Warn about ignored type attributes, for example: 4290 // __attribute__((aligned)) struct A; 4291 // Attributes should be placed after tag to apply to type declaration. 4292 if (!DS.getAttributes().empty()) { 4293 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4294 if (TypeSpecType == DeclSpec::TST_class || 4295 TypeSpecType == DeclSpec::TST_struct || 4296 TypeSpecType == DeclSpec::TST_interface || 4297 TypeSpecType == DeclSpec::TST_union || 4298 TypeSpecType == DeclSpec::TST_enum) { 4299 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4300 attrs = attrs->getNext()) 4301 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4302 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4303 } 4304 } 4305 4306 return TagD; 4307 } 4308 4309 /// We are trying to inject an anonymous member into the given scope; 4310 /// check if there's an existing declaration that can't be overloaded. 4311 /// 4312 /// \return true if this is a forbidden redeclaration 4313 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4314 Scope *S, 4315 DeclContext *Owner, 4316 DeclarationName Name, 4317 SourceLocation NameLoc, 4318 bool IsUnion) { 4319 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4320 Sema::ForRedeclaration); 4321 if (!SemaRef.LookupName(R, S)) return false; 4322 4323 // Pick a representative declaration. 4324 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4325 assert(PrevDecl && "Expected a non-null Decl"); 4326 4327 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4328 return false; 4329 4330 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4331 << IsUnion << Name; 4332 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4333 4334 return true; 4335 } 4336 4337 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4338 /// anonymous struct or union AnonRecord into the owning context Owner 4339 /// and scope S. This routine will be invoked just after we realize 4340 /// that an unnamed union or struct is actually an anonymous union or 4341 /// struct, e.g., 4342 /// 4343 /// @code 4344 /// union { 4345 /// int i; 4346 /// float f; 4347 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4348 /// // f into the surrounding scope.x 4349 /// @endcode 4350 /// 4351 /// This routine is recursive, injecting the names of nested anonymous 4352 /// structs/unions into the owning context and scope as well. 4353 static bool 4354 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4355 RecordDecl *AnonRecord, AccessSpecifier AS, 4356 SmallVectorImpl<NamedDecl *> &Chaining) { 4357 bool Invalid = false; 4358 4359 // Look every FieldDecl and IndirectFieldDecl with a name. 4360 for (auto *D : AnonRecord->decls()) { 4361 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4362 cast<NamedDecl>(D)->getDeclName()) { 4363 ValueDecl *VD = cast<ValueDecl>(D); 4364 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4365 VD->getLocation(), 4366 AnonRecord->isUnion())) { 4367 // C++ [class.union]p2: 4368 // The names of the members of an anonymous union shall be 4369 // distinct from the names of any other entity in the 4370 // scope in which the anonymous union is declared. 4371 Invalid = true; 4372 } else { 4373 // C++ [class.union]p2: 4374 // For the purpose of name lookup, after the anonymous union 4375 // definition, the members of the anonymous union are 4376 // considered to have been defined in the scope in which the 4377 // anonymous union is declared. 4378 unsigned OldChainingSize = Chaining.size(); 4379 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4380 Chaining.append(IF->chain_begin(), IF->chain_end()); 4381 else 4382 Chaining.push_back(VD); 4383 4384 assert(Chaining.size() >= 2); 4385 NamedDecl **NamedChain = 4386 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4387 for (unsigned i = 0; i < Chaining.size(); i++) 4388 NamedChain[i] = Chaining[i]; 4389 4390 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4391 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4392 VD->getType(), {NamedChain, Chaining.size()}); 4393 4394 for (const auto *Attr : VD->attrs()) 4395 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4396 4397 IndirectField->setAccess(AS); 4398 IndirectField->setImplicit(); 4399 SemaRef.PushOnScopeChains(IndirectField, S); 4400 4401 // That includes picking up the appropriate access specifier. 4402 if (AS != AS_none) IndirectField->setAccess(AS); 4403 4404 Chaining.resize(OldChainingSize); 4405 } 4406 } 4407 } 4408 4409 return Invalid; 4410 } 4411 4412 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4413 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4414 /// illegal input values are mapped to SC_None. 4415 static StorageClass 4416 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4417 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4418 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4419 "Parser allowed 'typedef' as storage class VarDecl."); 4420 switch (StorageClassSpec) { 4421 case DeclSpec::SCS_unspecified: return SC_None; 4422 case DeclSpec::SCS_extern: 4423 if (DS.isExternInLinkageSpec()) 4424 return SC_None; 4425 return SC_Extern; 4426 case DeclSpec::SCS_static: return SC_Static; 4427 case DeclSpec::SCS_auto: return SC_Auto; 4428 case DeclSpec::SCS_register: return SC_Register; 4429 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4430 // Illegal SCSs map to None: error reporting is up to the caller. 4431 case DeclSpec::SCS_mutable: // Fall through. 4432 case DeclSpec::SCS_typedef: return SC_None; 4433 } 4434 llvm_unreachable("unknown storage class specifier"); 4435 } 4436 4437 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4438 assert(Record->hasInClassInitializer()); 4439 4440 for (const auto *I : Record->decls()) { 4441 const auto *FD = dyn_cast<FieldDecl>(I); 4442 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4443 FD = IFD->getAnonField(); 4444 if (FD && FD->hasInClassInitializer()) 4445 return FD->getLocation(); 4446 } 4447 4448 llvm_unreachable("couldn't find in-class initializer"); 4449 } 4450 4451 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4452 SourceLocation DefaultInitLoc) { 4453 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4454 return; 4455 4456 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4457 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4458 } 4459 4460 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4461 CXXRecordDecl *AnonUnion) { 4462 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4463 return; 4464 4465 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4466 } 4467 4468 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4469 /// anonymous structure or union. Anonymous unions are a C++ feature 4470 /// (C++ [class.union]) and a C11 feature; anonymous structures 4471 /// are a C11 feature and GNU C++ extension. 4472 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4473 AccessSpecifier AS, 4474 RecordDecl *Record, 4475 const PrintingPolicy &Policy) { 4476 DeclContext *Owner = Record->getDeclContext(); 4477 4478 // Diagnose whether this anonymous struct/union is an extension. 4479 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4480 Diag(Record->getLocation(), diag::ext_anonymous_union); 4481 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4482 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4483 else if (!Record->isUnion() && !getLangOpts().C11) 4484 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4485 4486 // C and C++ require different kinds of checks for anonymous 4487 // structs/unions. 4488 bool Invalid = false; 4489 if (getLangOpts().CPlusPlus) { 4490 const char *PrevSpec = nullptr; 4491 unsigned DiagID; 4492 if (Record->isUnion()) { 4493 // C++ [class.union]p6: 4494 // Anonymous unions declared in a named namespace or in the 4495 // global namespace shall be declared static. 4496 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4497 (isa<TranslationUnitDecl>(Owner) || 4498 (isa<NamespaceDecl>(Owner) && 4499 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4500 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4501 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4502 4503 // Recover by adding 'static'. 4504 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4505 PrevSpec, DiagID, Policy); 4506 } 4507 // C++ [class.union]p6: 4508 // A storage class is not allowed in a declaration of an 4509 // anonymous union in a class scope. 4510 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4511 isa<RecordDecl>(Owner)) { 4512 Diag(DS.getStorageClassSpecLoc(), 4513 diag::err_anonymous_union_with_storage_spec) 4514 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4515 4516 // Recover by removing the storage specifier. 4517 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4518 SourceLocation(), 4519 PrevSpec, DiagID, Context.getPrintingPolicy()); 4520 } 4521 } 4522 4523 // Ignore const/volatile/restrict qualifiers. 4524 if (DS.getTypeQualifiers()) { 4525 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4526 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4527 << Record->isUnion() << "const" 4528 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4529 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4530 Diag(DS.getVolatileSpecLoc(), 4531 diag::ext_anonymous_struct_union_qualified) 4532 << Record->isUnion() << "volatile" 4533 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4534 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4535 Diag(DS.getRestrictSpecLoc(), 4536 diag::ext_anonymous_struct_union_qualified) 4537 << Record->isUnion() << "restrict" 4538 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4539 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4540 Diag(DS.getAtomicSpecLoc(), 4541 diag::ext_anonymous_struct_union_qualified) 4542 << Record->isUnion() << "_Atomic" 4543 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4544 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4545 Diag(DS.getUnalignedSpecLoc(), 4546 diag::ext_anonymous_struct_union_qualified) 4547 << Record->isUnion() << "__unaligned" 4548 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4549 4550 DS.ClearTypeQualifiers(); 4551 } 4552 4553 // C++ [class.union]p2: 4554 // The member-specification of an anonymous union shall only 4555 // define non-static data members. [Note: nested types and 4556 // functions cannot be declared within an anonymous union. ] 4557 for (auto *Mem : Record->decls()) { 4558 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4559 // C++ [class.union]p3: 4560 // An anonymous union shall not have private or protected 4561 // members (clause 11). 4562 assert(FD->getAccess() != AS_none); 4563 if (FD->getAccess() != AS_public) { 4564 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4565 << Record->isUnion() << (FD->getAccess() == AS_protected); 4566 Invalid = true; 4567 } 4568 4569 // C++ [class.union]p1 4570 // An object of a class with a non-trivial constructor, a non-trivial 4571 // copy constructor, a non-trivial destructor, or a non-trivial copy 4572 // assignment operator cannot be a member of a union, nor can an 4573 // array of such objects. 4574 if (CheckNontrivialField(FD)) 4575 Invalid = true; 4576 } else if (Mem->isImplicit()) { 4577 // Any implicit members are fine. 4578 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4579 // This is a type that showed up in an 4580 // elaborated-type-specifier inside the anonymous struct or 4581 // union, but which actually declares a type outside of the 4582 // anonymous struct or union. It's okay. 4583 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4584 if (!MemRecord->isAnonymousStructOrUnion() && 4585 MemRecord->getDeclName()) { 4586 // Visual C++ allows type definition in anonymous struct or union. 4587 if (getLangOpts().MicrosoftExt) 4588 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4589 << Record->isUnion(); 4590 else { 4591 // This is a nested type declaration. 4592 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4593 << Record->isUnion(); 4594 Invalid = true; 4595 } 4596 } else { 4597 // This is an anonymous type definition within another anonymous type. 4598 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4599 // not part of standard C++. 4600 Diag(MemRecord->getLocation(), 4601 diag::ext_anonymous_record_with_anonymous_type) 4602 << Record->isUnion(); 4603 } 4604 } else if (isa<AccessSpecDecl>(Mem)) { 4605 // Any access specifier is fine. 4606 } else if (isa<StaticAssertDecl>(Mem)) { 4607 // In C++1z, static_assert declarations are also fine. 4608 } else { 4609 // We have something that isn't a non-static data 4610 // member. Complain about it. 4611 unsigned DK = diag::err_anonymous_record_bad_member; 4612 if (isa<TypeDecl>(Mem)) 4613 DK = diag::err_anonymous_record_with_type; 4614 else if (isa<FunctionDecl>(Mem)) 4615 DK = diag::err_anonymous_record_with_function; 4616 else if (isa<VarDecl>(Mem)) 4617 DK = diag::err_anonymous_record_with_static; 4618 4619 // Visual C++ allows type definition in anonymous struct or union. 4620 if (getLangOpts().MicrosoftExt && 4621 DK == diag::err_anonymous_record_with_type) 4622 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4623 << Record->isUnion(); 4624 else { 4625 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4626 Invalid = true; 4627 } 4628 } 4629 } 4630 4631 // C++11 [class.union]p8 (DR1460): 4632 // At most one variant member of a union may have a 4633 // brace-or-equal-initializer. 4634 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4635 Owner->isRecord()) 4636 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4637 cast<CXXRecordDecl>(Record)); 4638 } 4639 4640 if (!Record->isUnion() && !Owner->isRecord()) { 4641 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4642 << getLangOpts().CPlusPlus; 4643 Invalid = true; 4644 } 4645 4646 // Mock up a declarator. 4647 Declarator Dc(DS, Declarator::MemberContext); 4648 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4649 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4650 4651 // Create a declaration for this anonymous struct/union. 4652 NamedDecl *Anon = nullptr; 4653 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4654 Anon = FieldDecl::Create(Context, OwningClass, 4655 DS.getLocStart(), 4656 Record->getLocation(), 4657 /*IdentifierInfo=*/nullptr, 4658 Context.getTypeDeclType(Record), 4659 TInfo, 4660 /*BitWidth=*/nullptr, /*Mutable=*/false, 4661 /*InitStyle=*/ICIS_NoInit); 4662 Anon->setAccess(AS); 4663 if (getLangOpts().CPlusPlus) 4664 FieldCollector->Add(cast<FieldDecl>(Anon)); 4665 } else { 4666 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4667 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4668 if (SCSpec == DeclSpec::SCS_mutable) { 4669 // mutable can only appear on non-static class members, so it's always 4670 // an error here 4671 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4672 Invalid = true; 4673 SC = SC_None; 4674 } 4675 4676 Anon = VarDecl::Create(Context, Owner, 4677 DS.getLocStart(), 4678 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4679 Context.getTypeDeclType(Record), 4680 TInfo, SC); 4681 4682 // Default-initialize the implicit variable. This initialization will be 4683 // trivial in almost all cases, except if a union member has an in-class 4684 // initializer: 4685 // union { int n = 0; }; 4686 ActOnUninitializedDecl(Anon); 4687 } 4688 Anon->setImplicit(); 4689 4690 // Mark this as an anonymous struct/union type. 4691 Record->setAnonymousStructOrUnion(true); 4692 4693 // Add the anonymous struct/union object to the current 4694 // context. We'll be referencing this object when we refer to one of 4695 // its members. 4696 Owner->addDecl(Anon); 4697 4698 // Inject the members of the anonymous struct/union into the owning 4699 // context and into the identifier resolver chain for name lookup 4700 // purposes. 4701 SmallVector<NamedDecl*, 2> Chain; 4702 Chain.push_back(Anon); 4703 4704 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4705 Invalid = true; 4706 4707 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4708 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4709 Decl *ManglingContextDecl; 4710 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4711 NewVD->getDeclContext(), ManglingContextDecl)) { 4712 Context.setManglingNumber( 4713 NewVD, MCtx->getManglingNumber( 4714 NewVD, getMSManglingNumber(getLangOpts(), S))); 4715 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4716 } 4717 } 4718 } 4719 4720 if (Invalid) 4721 Anon->setInvalidDecl(); 4722 4723 return Anon; 4724 } 4725 4726 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4727 /// Microsoft C anonymous structure. 4728 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4729 /// Example: 4730 /// 4731 /// struct A { int a; }; 4732 /// struct B { struct A; int b; }; 4733 /// 4734 /// void foo() { 4735 /// B var; 4736 /// var.a = 3; 4737 /// } 4738 /// 4739 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4740 RecordDecl *Record) { 4741 assert(Record && "expected a record!"); 4742 4743 // Mock up a declarator. 4744 Declarator Dc(DS, Declarator::TypeNameContext); 4745 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4746 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4747 4748 auto *ParentDecl = cast<RecordDecl>(CurContext); 4749 QualType RecTy = Context.getTypeDeclType(Record); 4750 4751 // Create a declaration for this anonymous struct. 4752 NamedDecl *Anon = FieldDecl::Create(Context, 4753 ParentDecl, 4754 DS.getLocStart(), 4755 DS.getLocStart(), 4756 /*IdentifierInfo=*/nullptr, 4757 RecTy, 4758 TInfo, 4759 /*BitWidth=*/nullptr, /*Mutable=*/false, 4760 /*InitStyle=*/ICIS_NoInit); 4761 Anon->setImplicit(); 4762 4763 // Add the anonymous struct object to the current context. 4764 CurContext->addDecl(Anon); 4765 4766 // Inject the members of the anonymous struct into the current 4767 // context and into the identifier resolver chain for name lookup 4768 // purposes. 4769 SmallVector<NamedDecl*, 2> Chain; 4770 Chain.push_back(Anon); 4771 4772 RecordDecl *RecordDef = Record->getDefinition(); 4773 if (RequireCompleteType(Anon->getLocation(), RecTy, 4774 diag::err_field_incomplete) || 4775 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4776 AS_none, Chain)) { 4777 Anon->setInvalidDecl(); 4778 ParentDecl->setInvalidDecl(); 4779 } 4780 4781 return Anon; 4782 } 4783 4784 /// GetNameForDeclarator - Determine the full declaration name for the 4785 /// given Declarator. 4786 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4787 return GetNameFromUnqualifiedId(D.getName()); 4788 } 4789 4790 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4791 DeclarationNameInfo 4792 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4793 DeclarationNameInfo NameInfo; 4794 NameInfo.setLoc(Name.StartLocation); 4795 4796 switch (Name.getKind()) { 4797 4798 case UnqualifiedId::IK_ImplicitSelfParam: 4799 case UnqualifiedId::IK_Identifier: 4800 NameInfo.setName(Name.Identifier); 4801 NameInfo.setLoc(Name.StartLocation); 4802 return NameInfo; 4803 4804 case UnqualifiedId::IK_DeductionGuideName: { 4805 // C++ [temp.deduct.guide]p3: 4806 // The simple-template-id shall name a class template specialization. 4807 // The template-name shall be the same identifier as the template-name 4808 // of the simple-template-id. 4809 // These together intend to imply that the template-name shall name a 4810 // class template. 4811 // FIXME: template<typename T> struct X {}; 4812 // template<typename T> using Y = X<T>; 4813 // Y(int) -> Y<int>; 4814 // satisfies these rules but does not name a class template. 4815 TemplateName TN = Name.TemplateName.get().get(); 4816 auto *Template = TN.getAsTemplateDecl(); 4817 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4818 Diag(Name.StartLocation, 4819 diag::err_deduction_guide_name_not_class_template) 4820 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4821 if (Template) 4822 Diag(Template->getLocation(), diag::note_template_decl_here); 4823 return DeclarationNameInfo(); 4824 } 4825 4826 NameInfo.setName( 4827 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4828 NameInfo.setLoc(Name.StartLocation); 4829 return NameInfo; 4830 } 4831 4832 case UnqualifiedId::IK_OperatorFunctionId: 4833 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4834 Name.OperatorFunctionId.Operator)); 4835 NameInfo.setLoc(Name.StartLocation); 4836 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4837 = Name.OperatorFunctionId.SymbolLocations[0]; 4838 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4839 = Name.EndLocation.getRawEncoding(); 4840 return NameInfo; 4841 4842 case UnqualifiedId::IK_LiteralOperatorId: 4843 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4844 Name.Identifier)); 4845 NameInfo.setLoc(Name.StartLocation); 4846 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4847 return NameInfo; 4848 4849 case UnqualifiedId::IK_ConversionFunctionId: { 4850 TypeSourceInfo *TInfo; 4851 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4852 if (Ty.isNull()) 4853 return DeclarationNameInfo(); 4854 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4855 Context.getCanonicalType(Ty))); 4856 NameInfo.setLoc(Name.StartLocation); 4857 NameInfo.setNamedTypeInfo(TInfo); 4858 return NameInfo; 4859 } 4860 4861 case UnqualifiedId::IK_ConstructorName: { 4862 TypeSourceInfo *TInfo; 4863 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4864 if (Ty.isNull()) 4865 return DeclarationNameInfo(); 4866 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4867 Context.getCanonicalType(Ty))); 4868 NameInfo.setLoc(Name.StartLocation); 4869 NameInfo.setNamedTypeInfo(TInfo); 4870 return NameInfo; 4871 } 4872 4873 case UnqualifiedId::IK_ConstructorTemplateId: { 4874 // In well-formed code, we can only have a constructor 4875 // template-id that refers to the current context, so go there 4876 // to find the actual type being constructed. 4877 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4878 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4879 return DeclarationNameInfo(); 4880 4881 // Determine the type of the class being constructed. 4882 QualType CurClassType = Context.getTypeDeclType(CurClass); 4883 4884 // FIXME: Check two things: that the template-id names the same type as 4885 // CurClassType, and that the template-id does not occur when the name 4886 // was qualified. 4887 4888 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4889 Context.getCanonicalType(CurClassType))); 4890 NameInfo.setLoc(Name.StartLocation); 4891 // FIXME: should we retrieve TypeSourceInfo? 4892 NameInfo.setNamedTypeInfo(nullptr); 4893 return NameInfo; 4894 } 4895 4896 case UnqualifiedId::IK_DestructorName: { 4897 TypeSourceInfo *TInfo; 4898 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4899 if (Ty.isNull()) 4900 return DeclarationNameInfo(); 4901 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4902 Context.getCanonicalType(Ty))); 4903 NameInfo.setLoc(Name.StartLocation); 4904 NameInfo.setNamedTypeInfo(TInfo); 4905 return NameInfo; 4906 } 4907 4908 case UnqualifiedId::IK_TemplateId: { 4909 TemplateName TName = Name.TemplateId->Template.get(); 4910 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4911 return Context.getNameForTemplate(TName, TNameLoc); 4912 } 4913 4914 } // switch (Name.getKind()) 4915 4916 llvm_unreachable("Unknown name kind"); 4917 } 4918 4919 static QualType getCoreType(QualType Ty) { 4920 do { 4921 if (Ty->isPointerType() || Ty->isReferenceType()) 4922 Ty = Ty->getPointeeType(); 4923 else if (Ty->isArrayType()) 4924 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4925 else 4926 return Ty.withoutLocalFastQualifiers(); 4927 } while (true); 4928 } 4929 4930 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4931 /// and Definition have "nearly" matching parameters. This heuristic is 4932 /// used to improve diagnostics in the case where an out-of-line function 4933 /// definition doesn't match any declaration within the class or namespace. 4934 /// Also sets Params to the list of indices to the parameters that differ 4935 /// between the declaration and the definition. If hasSimilarParameters 4936 /// returns true and Params is empty, then all of the parameters match. 4937 static bool hasSimilarParameters(ASTContext &Context, 4938 FunctionDecl *Declaration, 4939 FunctionDecl *Definition, 4940 SmallVectorImpl<unsigned> &Params) { 4941 Params.clear(); 4942 if (Declaration->param_size() != Definition->param_size()) 4943 return false; 4944 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4945 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4946 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4947 4948 // The parameter types are identical 4949 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4950 continue; 4951 4952 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4953 QualType DefParamBaseTy = getCoreType(DefParamTy); 4954 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4955 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4956 4957 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4958 (DeclTyName && DeclTyName == DefTyName)) 4959 Params.push_back(Idx); 4960 else // The two parameters aren't even close 4961 return false; 4962 } 4963 4964 return true; 4965 } 4966 4967 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4968 /// declarator needs to be rebuilt in the current instantiation. 4969 /// Any bits of declarator which appear before the name are valid for 4970 /// consideration here. That's specifically the type in the decl spec 4971 /// and the base type in any member-pointer chunks. 4972 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4973 DeclarationName Name) { 4974 // The types we specifically need to rebuild are: 4975 // - typenames, typeofs, and decltypes 4976 // - types which will become injected class names 4977 // Of course, we also need to rebuild any type referencing such a 4978 // type. It's safest to just say "dependent", but we call out a 4979 // few cases here. 4980 4981 DeclSpec &DS = D.getMutableDeclSpec(); 4982 switch (DS.getTypeSpecType()) { 4983 case DeclSpec::TST_typename: 4984 case DeclSpec::TST_typeofType: 4985 case DeclSpec::TST_underlyingType: 4986 case DeclSpec::TST_atomic: { 4987 // Grab the type from the parser. 4988 TypeSourceInfo *TSI = nullptr; 4989 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4990 if (T.isNull() || !T->isDependentType()) break; 4991 4992 // Make sure there's a type source info. This isn't really much 4993 // of a waste; most dependent types should have type source info 4994 // attached already. 4995 if (!TSI) 4996 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4997 4998 // Rebuild the type in the current instantiation. 4999 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5000 if (!TSI) return true; 5001 5002 // Store the new type back in the decl spec. 5003 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5004 DS.UpdateTypeRep(LocType); 5005 break; 5006 } 5007 5008 case DeclSpec::TST_decltype: 5009 case DeclSpec::TST_typeofExpr: { 5010 Expr *E = DS.getRepAsExpr(); 5011 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5012 if (Result.isInvalid()) return true; 5013 DS.UpdateExprRep(Result.get()); 5014 break; 5015 } 5016 5017 default: 5018 // Nothing to do for these decl specs. 5019 break; 5020 } 5021 5022 // It doesn't matter what order we do this in. 5023 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5024 DeclaratorChunk &Chunk = D.getTypeObject(I); 5025 5026 // The only type information in the declarator which can come 5027 // before the declaration name is the base type of a member 5028 // pointer. 5029 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5030 continue; 5031 5032 // Rebuild the scope specifier in-place. 5033 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5034 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5035 return true; 5036 } 5037 5038 return false; 5039 } 5040 5041 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5042 D.setFunctionDefinitionKind(FDK_Declaration); 5043 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5044 5045 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5046 Dcl && Dcl->getDeclContext()->isFileContext()) 5047 Dcl->setTopLevelDeclInObjCContainer(); 5048 5049 if (getLangOpts().OpenCL) 5050 setCurrentOpenCLExtensionForDecl(Dcl); 5051 5052 return Dcl; 5053 } 5054 5055 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5056 /// If T is the name of a class, then each of the following shall have a 5057 /// name different from T: 5058 /// - every static data member of class T; 5059 /// - every member function of class T 5060 /// - every member of class T that is itself a type; 5061 /// \returns true if the declaration name violates these rules. 5062 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5063 DeclarationNameInfo NameInfo) { 5064 DeclarationName Name = NameInfo.getName(); 5065 5066 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5067 while (Record && Record->isAnonymousStructOrUnion()) 5068 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5069 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5070 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5071 return true; 5072 } 5073 5074 return false; 5075 } 5076 5077 /// \brief Diagnose a declaration whose declarator-id has the given 5078 /// nested-name-specifier. 5079 /// 5080 /// \param SS The nested-name-specifier of the declarator-id. 5081 /// 5082 /// \param DC The declaration context to which the nested-name-specifier 5083 /// resolves. 5084 /// 5085 /// \param Name The name of the entity being declared. 5086 /// 5087 /// \param Loc The location of the name of the entity being declared. 5088 /// 5089 /// \returns true if we cannot safely recover from this error, false otherwise. 5090 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5091 DeclarationName Name, 5092 SourceLocation Loc) { 5093 DeclContext *Cur = CurContext; 5094 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5095 Cur = Cur->getParent(); 5096 5097 // If the user provided a superfluous scope specifier that refers back to the 5098 // class in which the entity is already declared, diagnose and ignore it. 5099 // 5100 // class X { 5101 // void X::f(); 5102 // }; 5103 // 5104 // Note, it was once ill-formed to give redundant qualification in all 5105 // contexts, but that rule was removed by DR482. 5106 if (Cur->Equals(DC)) { 5107 if (Cur->isRecord()) { 5108 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5109 : diag::err_member_extra_qualification) 5110 << Name << FixItHint::CreateRemoval(SS.getRange()); 5111 SS.clear(); 5112 } else { 5113 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5114 } 5115 return false; 5116 } 5117 5118 // Check whether the qualifying scope encloses the scope of the original 5119 // declaration. 5120 if (!Cur->Encloses(DC)) { 5121 if (Cur->isRecord()) 5122 Diag(Loc, diag::err_member_qualification) 5123 << Name << SS.getRange(); 5124 else if (isa<TranslationUnitDecl>(DC)) 5125 Diag(Loc, diag::err_invalid_declarator_global_scope) 5126 << Name << SS.getRange(); 5127 else if (isa<FunctionDecl>(Cur)) 5128 Diag(Loc, diag::err_invalid_declarator_in_function) 5129 << Name << SS.getRange(); 5130 else if (isa<BlockDecl>(Cur)) 5131 Diag(Loc, diag::err_invalid_declarator_in_block) 5132 << Name << SS.getRange(); 5133 else 5134 Diag(Loc, diag::err_invalid_declarator_scope) 5135 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5136 5137 return true; 5138 } 5139 5140 if (Cur->isRecord()) { 5141 // Cannot qualify members within a class. 5142 Diag(Loc, diag::err_member_qualification) 5143 << Name << SS.getRange(); 5144 SS.clear(); 5145 5146 // C++ constructors and destructors with incorrect scopes can break 5147 // our AST invariants by having the wrong underlying types. If 5148 // that's the case, then drop this declaration entirely. 5149 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5150 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5151 !Context.hasSameType(Name.getCXXNameType(), 5152 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5153 return true; 5154 5155 return false; 5156 } 5157 5158 // C++11 [dcl.meaning]p1: 5159 // [...] "The nested-name-specifier of the qualified declarator-id shall 5160 // not begin with a decltype-specifer" 5161 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5162 while (SpecLoc.getPrefix()) 5163 SpecLoc = SpecLoc.getPrefix(); 5164 if (dyn_cast_or_null<DecltypeType>( 5165 SpecLoc.getNestedNameSpecifier()->getAsType())) 5166 Diag(Loc, diag::err_decltype_in_declarator) 5167 << SpecLoc.getTypeLoc().getSourceRange(); 5168 5169 return false; 5170 } 5171 5172 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5173 MultiTemplateParamsArg TemplateParamLists) { 5174 // TODO: consider using NameInfo for diagnostic. 5175 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5176 DeclarationName Name = NameInfo.getName(); 5177 5178 // All of these full declarators require an identifier. If it doesn't have 5179 // one, the ParsedFreeStandingDeclSpec action should be used. 5180 if (D.isDecompositionDeclarator()) { 5181 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5182 } else if (!Name) { 5183 if (!D.isInvalidType()) // Reject this if we think it is valid. 5184 Diag(D.getDeclSpec().getLocStart(), 5185 diag::err_declarator_need_ident) 5186 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5187 return nullptr; 5188 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5189 return nullptr; 5190 5191 // The scope passed in may not be a decl scope. Zip up the scope tree until 5192 // we find one that is. 5193 while ((S->getFlags() & Scope::DeclScope) == 0 || 5194 (S->getFlags() & Scope::TemplateParamScope) != 0) 5195 S = S->getParent(); 5196 5197 DeclContext *DC = CurContext; 5198 if (D.getCXXScopeSpec().isInvalid()) 5199 D.setInvalidType(); 5200 else if (D.getCXXScopeSpec().isSet()) { 5201 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5202 UPPC_DeclarationQualifier)) 5203 return nullptr; 5204 5205 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5206 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5207 if (!DC || isa<EnumDecl>(DC)) { 5208 // If we could not compute the declaration context, it's because the 5209 // declaration context is dependent but does not refer to a class, 5210 // class template, or class template partial specialization. Complain 5211 // and return early, to avoid the coming semantic disaster. 5212 Diag(D.getIdentifierLoc(), 5213 diag::err_template_qualified_declarator_no_match) 5214 << D.getCXXScopeSpec().getScopeRep() 5215 << D.getCXXScopeSpec().getRange(); 5216 return nullptr; 5217 } 5218 bool IsDependentContext = DC->isDependentContext(); 5219 5220 if (!IsDependentContext && 5221 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5222 return nullptr; 5223 5224 // If a class is incomplete, do not parse entities inside it. 5225 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5226 Diag(D.getIdentifierLoc(), 5227 diag::err_member_def_undefined_record) 5228 << Name << DC << D.getCXXScopeSpec().getRange(); 5229 return nullptr; 5230 } 5231 if (!D.getDeclSpec().isFriendSpecified()) { 5232 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5233 Name, D.getIdentifierLoc())) { 5234 if (DC->isRecord()) 5235 return nullptr; 5236 5237 D.setInvalidType(); 5238 } 5239 } 5240 5241 // Check whether we need to rebuild the type of the given 5242 // declaration in the current instantiation. 5243 if (EnteringContext && IsDependentContext && 5244 TemplateParamLists.size() != 0) { 5245 ContextRAII SavedContext(*this, DC); 5246 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5247 D.setInvalidType(); 5248 } 5249 } 5250 5251 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5252 QualType R = TInfo->getType(); 5253 5254 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5255 // If this is a typedef, we'll end up spewing multiple diagnostics. 5256 // Just return early; it's safer. If this is a function, let the 5257 // "constructor cannot have a return type" diagnostic handle it. 5258 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5259 return nullptr; 5260 5261 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5262 UPPC_DeclarationType)) 5263 D.setInvalidType(); 5264 5265 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5266 ForRedeclaration); 5267 5268 // See if this is a redefinition of a variable in the same scope. 5269 if (!D.getCXXScopeSpec().isSet()) { 5270 bool IsLinkageLookup = false; 5271 bool CreateBuiltins = false; 5272 5273 // If the declaration we're planning to build will be a function 5274 // or object with linkage, then look for another declaration with 5275 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5276 // 5277 // If the declaration we're planning to build will be declared with 5278 // external linkage in the translation unit, create any builtin with 5279 // the same name. 5280 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5281 /* Do nothing*/; 5282 else if (CurContext->isFunctionOrMethod() && 5283 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5284 R->isFunctionType())) { 5285 IsLinkageLookup = true; 5286 CreateBuiltins = 5287 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5288 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5289 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5290 CreateBuiltins = true; 5291 5292 if (IsLinkageLookup) 5293 Previous.clear(LookupRedeclarationWithLinkage); 5294 5295 LookupName(Previous, S, CreateBuiltins); 5296 } else { // Something like "int foo::x;" 5297 LookupQualifiedName(Previous, DC); 5298 5299 // C++ [dcl.meaning]p1: 5300 // When the declarator-id is qualified, the declaration shall refer to a 5301 // previously declared member of the class or namespace to which the 5302 // qualifier refers (or, in the case of a namespace, of an element of the 5303 // inline namespace set of that namespace (7.3.1)) or to a specialization 5304 // thereof; [...] 5305 // 5306 // Note that we already checked the context above, and that we do not have 5307 // enough information to make sure that Previous contains the declaration 5308 // we want to match. For example, given: 5309 // 5310 // class X { 5311 // void f(); 5312 // void f(float); 5313 // }; 5314 // 5315 // void X::f(int) { } // ill-formed 5316 // 5317 // In this case, Previous will point to the overload set 5318 // containing the two f's declared in X, but neither of them 5319 // matches. 5320 5321 // C++ [dcl.meaning]p1: 5322 // [...] the member shall not merely have been introduced by a 5323 // using-declaration in the scope of the class or namespace nominated by 5324 // the nested-name-specifier of the declarator-id. 5325 RemoveUsingDecls(Previous); 5326 } 5327 5328 if (Previous.isSingleResult() && 5329 Previous.getFoundDecl()->isTemplateParameter()) { 5330 // Maybe we will complain about the shadowed template parameter. 5331 if (!D.isInvalidType()) 5332 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5333 Previous.getFoundDecl()); 5334 5335 // Just pretend that we didn't see the previous declaration. 5336 Previous.clear(); 5337 } 5338 5339 // In C++, the previous declaration we find might be a tag type 5340 // (class or enum). In this case, the new declaration will hide the 5341 // tag type. Note that this does does not apply if we're declaring a 5342 // typedef (C++ [dcl.typedef]p4). 5343 if (Previous.isSingleTagDecl() && 5344 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5345 Previous.clear(); 5346 5347 // Check that there are no default arguments other than in the parameters 5348 // of a function declaration (C++ only). 5349 if (getLangOpts().CPlusPlus) 5350 CheckExtraCXXDefaultArguments(D); 5351 5352 if (D.getDeclSpec().isConceptSpecified()) { 5353 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5354 // applied only to the definition of a function template or variable 5355 // template, declared in namespace scope 5356 if (!TemplateParamLists.size()) { 5357 Diag(D.getDeclSpec().getConceptSpecLoc(), 5358 diag:: err_concept_wrong_decl_kind); 5359 return nullptr; 5360 } 5361 5362 if (!DC->getRedeclContext()->isFileContext()) { 5363 Diag(D.getIdentifierLoc(), 5364 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5365 return nullptr; 5366 } 5367 } 5368 5369 NamedDecl *New; 5370 5371 bool AddToScope = true; 5372 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5373 if (TemplateParamLists.size()) { 5374 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5375 return nullptr; 5376 } 5377 5378 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5379 } else if (R->isFunctionType()) { 5380 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5381 TemplateParamLists, 5382 AddToScope); 5383 } else { 5384 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5385 AddToScope); 5386 } 5387 5388 if (!New) 5389 return nullptr; 5390 5391 // If this has an identifier and is not a function template specialization, 5392 // add it to the scope stack. 5393 if (New->getDeclName() && AddToScope) { 5394 // Only make a locally-scoped extern declaration visible if it is the first 5395 // declaration of this entity. Qualified lookup for such an entity should 5396 // only find this declaration if there is no visible declaration of it. 5397 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5398 PushOnScopeChains(New, S, AddToContext); 5399 if (!AddToContext) 5400 CurContext->addHiddenDecl(New); 5401 } 5402 5403 if (isInOpenMPDeclareTargetContext()) 5404 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5405 5406 return New; 5407 } 5408 5409 /// Helper method to turn variable array types into constant array 5410 /// types in certain situations which would otherwise be errors (for 5411 /// GCC compatibility). 5412 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5413 ASTContext &Context, 5414 bool &SizeIsNegative, 5415 llvm::APSInt &Oversized) { 5416 // This method tries to turn a variable array into a constant 5417 // array even when the size isn't an ICE. This is necessary 5418 // for compatibility with code that depends on gcc's buggy 5419 // constant expression folding, like struct {char x[(int)(char*)2];} 5420 SizeIsNegative = false; 5421 Oversized = 0; 5422 5423 if (T->isDependentType()) 5424 return QualType(); 5425 5426 QualifierCollector Qs; 5427 const Type *Ty = Qs.strip(T); 5428 5429 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5430 QualType Pointee = PTy->getPointeeType(); 5431 QualType FixedType = 5432 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5433 Oversized); 5434 if (FixedType.isNull()) return FixedType; 5435 FixedType = Context.getPointerType(FixedType); 5436 return Qs.apply(Context, FixedType); 5437 } 5438 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5439 QualType Inner = PTy->getInnerType(); 5440 QualType FixedType = 5441 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5442 Oversized); 5443 if (FixedType.isNull()) return FixedType; 5444 FixedType = Context.getParenType(FixedType); 5445 return Qs.apply(Context, FixedType); 5446 } 5447 5448 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5449 if (!VLATy) 5450 return QualType(); 5451 // FIXME: We should probably handle this case 5452 if (VLATy->getElementType()->isVariablyModifiedType()) 5453 return QualType(); 5454 5455 llvm::APSInt Res; 5456 if (!VLATy->getSizeExpr() || 5457 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5458 return QualType(); 5459 5460 // Check whether the array size is negative. 5461 if (Res.isSigned() && Res.isNegative()) { 5462 SizeIsNegative = true; 5463 return QualType(); 5464 } 5465 5466 // Check whether the array is too large to be addressed. 5467 unsigned ActiveSizeBits 5468 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5469 Res); 5470 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5471 Oversized = Res; 5472 return QualType(); 5473 } 5474 5475 return Context.getConstantArrayType(VLATy->getElementType(), 5476 Res, ArrayType::Normal, 0); 5477 } 5478 5479 static void 5480 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5481 SrcTL = SrcTL.getUnqualifiedLoc(); 5482 DstTL = DstTL.getUnqualifiedLoc(); 5483 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5484 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5485 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5486 DstPTL.getPointeeLoc()); 5487 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5488 return; 5489 } 5490 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5491 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5492 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5493 DstPTL.getInnerLoc()); 5494 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5495 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5496 return; 5497 } 5498 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5499 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5500 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5501 TypeLoc DstElemTL = DstATL.getElementLoc(); 5502 DstElemTL.initializeFullCopy(SrcElemTL); 5503 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5504 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5505 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5506 } 5507 5508 /// Helper method to turn variable array types into constant array 5509 /// types in certain situations which would otherwise be errors (for 5510 /// GCC compatibility). 5511 static TypeSourceInfo* 5512 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5513 ASTContext &Context, 5514 bool &SizeIsNegative, 5515 llvm::APSInt &Oversized) { 5516 QualType FixedTy 5517 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5518 SizeIsNegative, Oversized); 5519 if (FixedTy.isNull()) 5520 return nullptr; 5521 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5522 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5523 FixedTInfo->getTypeLoc()); 5524 return FixedTInfo; 5525 } 5526 5527 /// \brief Register the given locally-scoped extern "C" declaration so 5528 /// that it can be found later for redeclarations. We include any extern "C" 5529 /// declaration that is not visible in the translation unit here, not just 5530 /// function-scope declarations. 5531 void 5532 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5533 if (!getLangOpts().CPlusPlus && 5534 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5535 // Don't need to track declarations in the TU in C. 5536 return; 5537 5538 // Note that we have a locally-scoped external with this name. 5539 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5540 } 5541 5542 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5543 // FIXME: We can have multiple results via __attribute__((overloadable)). 5544 auto Result = Context.getExternCContextDecl()->lookup(Name); 5545 return Result.empty() ? nullptr : *Result.begin(); 5546 } 5547 5548 /// \brief Diagnose function specifiers on a declaration of an identifier that 5549 /// does not identify a function. 5550 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5551 // FIXME: We should probably indicate the identifier in question to avoid 5552 // confusion for constructs like "virtual int a(), b;" 5553 if (DS.isVirtualSpecified()) 5554 Diag(DS.getVirtualSpecLoc(), 5555 diag::err_virtual_non_function); 5556 5557 if (DS.isExplicitSpecified()) 5558 Diag(DS.getExplicitSpecLoc(), 5559 diag::err_explicit_non_function); 5560 5561 if (DS.isNoreturnSpecified()) 5562 Diag(DS.getNoreturnSpecLoc(), 5563 diag::err_noreturn_non_function); 5564 } 5565 5566 NamedDecl* 5567 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5568 TypeSourceInfo *TInfo, LookupResult &Previous) { 5569 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5570 if (D.getCXXScopeSpec().isSet()) { 5571 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5572 << D.getCXXScopeSpec().getRange(); 5573 D.setInvalidType(); 5574 // Pretend we didn't see the scope specifier. 5575 DC = CurContext; 5576 Previous.clear(); 5577 } 5578 5579 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5580 5581 if (D.getDeclSpec().isInlineSpecified()) 5582 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5583 << getLangOpts().CPlusPlus1z; 5584 if (D.getDeclSpec().isConstexprSpecified()) 5585 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5586 << 1; 5587 if (D.getDeclSpec().isConceptSpecified()) 5588 Diag(D.getDeclSpec().getConceptSpecLoc(), 5589 diag::err_concept_wrong_decl_kind); 5590 5591 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5592 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName) 5593 Diag(D.getName().StartLocation, 5594 diag::err_deduction_guide_invalid_specifier) 5595 << "typedef"; 5596 else 5597 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5598 << D.getName().getSourceRange(); 5599 return nullptr; 5600 } 5601 5602 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5603 if (!NewTD) return nullptr; 5604 5605 // Handle attributes prior to checking for duplicates in MergeVarDecl 5606 ProcessDeclAttributes(S, NewTD, D); 5607 5608 CheckTypedefForVariablyModifiedType(S, NewTD); 5609 5610 bool Redeclaration = D.isRedeclaration(); 5611 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5612 D.setRedeclaration(Redeclaration); 5613 return ND; 5614 } 5615 5616 void 5617 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5618 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5619 // then it shall have block scope. 5620 // Note that variably modified types must be fixed before merging the decl so 5621 // that redeclarations will match. 5622 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5623 QualType T = TInfo->getType(); 5624 if (T->isVariablyModifiedType()) { 5625 getCurFunction()->setHasBranchProtectedScope(); 5626 5627 if (S->getFnParent() == nullptr) { 5628 bool SizeIsNegative; 5629 llvm::APSInt Oversized; 5630 TypeSourceInfo *FixedTInfo = 5631 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5632 SizeIsNegative, 5633 Oversized); 5634 if (FixedTInfo) { 5635 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5636 NewTD->setTypeSourceInfo(FixedTInfo); 5637 } else { 5638 if (SizeIsNegative) 5639 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5640 else if (T->isVariableArrayType()) 5641 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5642 else if (Oversized.getBoolValue()) 5643 Diag(NewTD->getLocation(), diag::err_array_too_large) 5644 << Oversized.toString(10); 5645 else 5646 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5647 NewTD->setInvalidDecl(); 5648 } 5649 } 5650 } 5651 } 5652 5653 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5654 /// declares a typedef-name, either using the 'typedef' type specifier or via 5655 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5656 NamedDecl* 5657 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5658 LookupResult &Previous, bool &Redeclaration) { 5659 5660 // Find the shadowed declaration before filtering for scope. 5661 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5662 5663 // Merge the decl with the existing one if appropriate. If the decl is 5664 // in an outer scope, it isn't the same thing. 5665 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5666 /*AllowInlineNamespace*/false); 5667 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5668 if (!Previous.empty()) { 5669 Redeclaration = true; 5670 MergeTypedefNameDecl(S, NewTD, Previous); 5671 } 5672 5673 if (ShadowedDecl && !Redeclaration) 5674 CheckShadow(NewTD, ShadowedDecl, Previous); 5675 5676 // If this is the C FILE type, notify the AST context. 5677 if (IdentifierInfo *II = NewTD->getIdentifier()) 5678 if (!NewTD->isInvalidDecl() && 5679 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5680 if (II->isStr("FILE")) 5681 Context.setFILEDecl(NewTD); 5682 else if (II->isStr("jmp_buf")) 5683 Context.setjmp_bufDecl(NewTD); 5684 else if (II->isStr("sigjmp_buf")) 5685 Context.setsigjmp_bufDecl(NewTD); 5686 else if (II->isStr("ucontext_t")) 5687 Context.setucontext_tDecl(NewTD); 5688 } 5689 5690 return NewTD; 5691 } 5692 5693 /// \brief Determines whether the given declaration is an out-of-scope 5694 /// previous declaration. 5695 /// 5696 /// This routine should be invoked when name lookup has found a 5697 /// previous declaration (PrevDecl) that is not in the scope where a 5698 /// new declaration by the same name is being introduced. If the new 5699 /// declaration occurs in a local scope, previous declarations with 5700 /// linkage may still be considered previous declarations (C99 5701 /// 6.2.2p4-5, C++ [basic.link]p6). 5702 /// 5703 /// \param PrevDecl the previous declaration found by name 5704 /// lookup 5705 /// 5706 /// \param DC the context in which the new declaration is being 5707 /// declared. 5708 /// 5709 /// \returns true if PrevDecl is an out-of-scope previous declaration 5710 /// for a new delcaration with the same name. 5711 static bool 5712 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5713 ASTContext &Context) { 5714 if (!PrevDecl) 5715 return false; 5716 5717 if (!PrevDecl->hasLinkage()) 5718 return false; 5719 5720 if (Context.getLangOpts().CPlusPlus) { 5721 // C++ [basic.link]p6: 5722 // If there is a visible declaration of an entity with linkage 5723 // having the same name and type, ignoring entities declared 5724 // outside the innermost enclosing namespace scope, the block 5725 // scope declaration declares that same entity and receives the 5726 // linkage of the previous declaration. 5727 DeclContext *OuterContext = DC->getRedeclContext(); 5728 if (!OuterContext->isFunctionOrMethod()) 5729 // This rule only applies to block-scope declarations. 5730 return false; 5731 5732 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5733 if (PrevOuterContext->isRecord()) 5734 // We found a member function: ignore it. 5735 return false; 5736 5737 // Find the innermost enclosing namespace for the new and 5738 // previous declarations. 5739 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5740 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5741 5742 // The previous declaration is in a different namespace, so it 5743 // isn't the same function. 5744 if (!OuterContext->Equals(PrevOuterContext)) 5745 return false; 5746 } 5747 5748 return true; 5749 } 5750 5751 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5752 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5753 if (!SS.isSet()) return; 5754 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5755 } 5756 5757 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5758 QualType type = decl->getType(); 5759 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5760 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5761 // Various kinds of declaration aren't allowed to be __autoreleasing. 5762 unsigned kind = -1U; 5763 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5764 if (var->hasAttr<BlocksAttr>()) 5765 kind = 0; // __block 5766 else if (!var->hasLocalStorage()) 5767 kind = 1; // global 5768 } else if (isa<ObjCIvarDecl>(decl)) { 5769 kind = 3; // ivar 5770 } else if (isa<FieldDecl>(decl)) { 5771 kind = 2; // field 5772 } 5773 5774 if (kind != -1U) { 5775 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5776 << kind; 5777 } 5778 } else if (lifetime == Qualifiers::OCL_None) { 5779 // Try to infer lifetime. 5780 if (!type->isObjCLifetimeType()) 5781 return false; 5782 5783 lifetime = type->getObjCARCImplicitLifetime(); 5784 type = Context.getLifetimeQualifiedType(type, lifetime); 5785 decl->setType(type); 5786 } 5787 5788 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5789 // Thread-local variables cannot have lifetime. 5790 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5791 var->getTLSKind()) { 5792 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5793 << var->getType(); 5794 return true; 5795 } 5796 } 5797 5798 return false; 5799 } 5800 5801 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5802 // Ensure that an auto decl is deduced otherwise the checks below might cache 5803 // the wrong linkage. 5804 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5805 5806 // 'weak' only applies to declarations with external linkage. 5807 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5808 if (!ND.isExternallyVisible()) { 5809 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5810 ND.dropAttr<WeakAttr>(); 5811 } 5812 } 5813 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5814 if (ND.isExternallyVisible()) { 5815 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5816 ND.dropAttr<WeakRefAttr>(); 5817 ND.dropAttr<AliasAttr>(); 5818 } 5819 } 5820 5821 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5822 if (VD->hasInit()) { 5823 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5824 assert(VD->isThisDeclarationADefinition() && 5825 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5826 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5827 VD->dropAttr<AliasAttr>(); 5828 } 5829 } 5830 } 5831 5832 // 'selectany' only applies to externally visible variable declarations. 5833 // It does not apply to functions. 5834 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5835 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5836 S.Diag(Attr->getLocation(), 5837 diag::err_attribute_selectany_non_extern_data); 5838 ND.dropAttr<SelectAnyAttr>(); 5839 } 5840 } 5841 5842 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5843 // dll attributes require external linkage. Static locals may have external 5844 // linkage but still cannot be explicitly imported or exported. 5845 auto *VD = dyn_cast<VarDecl>(&ND); 5846 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5847 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5848 << &ND << Attr; 5849 ND.setInvalidDecl(); 5850 } 5851 } 5852 5853 // Virtual functions cannot be marked as 'notail'. 5854 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5855 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5856 if (MD->isVirtual()) { 5857 S.Diag(ND.getLocation(), 5858 diag::err_invalid_attribute_on_virtual_function) 5859 << Attr; 5860 ND.dropAttr<NotTailCalledAttr>(); 5861 } 5862 } 5863 5864 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5865 NamedDecl *NewDecl, 5866 bool IsSpecialization, 5867 bool IsDefinition) { 5868 if (OldDecl->isInvalidDecl()) 5869 return; 5870 5871 bool IsTemplate = false; 5872 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5873 OldDecl = OldTD->getTemplatedDecl(); 5874 IsTemplate = true; 5875 if (!IsSpecialization) 5876 IsDefinition = false; 5877 } 5878 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5879 NewDecl = NewTD->getTemplatedDecl(); 5880 IsTemplate = true; 5881 } 5882 5883 if (!OldDecl || !NewDecl) 5884 return; 5885 5886 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5887 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5888 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5889 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5890 5891 // dllimport and dllexport are inheritable attributes so we have to exclude 5892 // inherited attribute instances. 5893 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5894 (NewExportAttr && !NewExportAttr->isInherited()); 5895 5896 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5897 // the only exception being explicit specializations. 5898 // Implicitly generated declarations are also excluded for now because there 5899 // is no other way to switch these to use dllimport or dllexport. 5900 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5901 5902 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5903 // Allow with a warning for free functions and global variables. 5904 bool JustWarn = false; 5905 if (!OldDecl->isCXXClassMember()) { 5906 auto *VD = dyn_cast<VarDecl>(OldDecl); 5907 if (VD && !VD->getDescribedVarTemplate()) 5908 JustWarn = true; 5909 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5910 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5911 JustWarn = true; 5912 } 5913 5914 // We cannot change a declaration that's been used because IR has already 5915 // been emitted. Dllimported functions will still work though (modulo 5916 // address equality) as they can use the thunk. 5917 if (OldDecl->isUsed()) 5918 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5919 JustWarn = false; 5920 5921 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5922 : diag::err_attribute_dll_redeclaration; 5923 S.Diag(NewDecl->getLocation(), DiagID) 5924 << NewDecl 5925 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5926 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5927 if (!JustWarn) { 5928 NewDecl->setInvalidDecl(); 5929 return; 5930 } 5931 } 5932 5933 // A redeclaration is not allowed to drop a dllimport attribute, the only 5934 // exceptions being inline function definitions (except for function 5935 // templates), local extern declarations, qualified friend declarations or 5936 // special MSVC extension: in the last case, the declaration is treated as if 5937 // it were marked dllexport. 5938 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5939 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5940 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5941 // Ignore static data because out-of-line definitions are diagnosed 5942 // separately. 5943 IsStaticDataMember = VD->isStaticDataMember(); 5944 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5945 VarDecl::DeclarationOnly; 5946 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5947 IsInline = FD->isInlined(); 5948 IsQualifiedFriend = FD->getQualifier() && 5949 FD->getFriendObjectKind() == Decl::FOK_Declared; 5950 } 5951 5952 if (OldImportAttr && !HasNewAttr && 5953 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 5954 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5955 if (IsMicrosoft && IsDefinition) { 5956 S.Diag(NewDecl->getLocation(), 5957 diag::warn_redeclaration_without_import_attribute) 5958 << NewDecl; 5959 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5960 NewDecl->dropAttr<DLLImportAttr>(); 5961 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5962 NewImportAttr->getRange(), S.Context, 5963 NewImportAttr->getSpellingListIndex())); 5964 } else { 5965 S.Diag(NewDecl->getLocation(), 5966 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5967 << NewDecl << OldImportAttr; 5968 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5969 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5970 OldDecl->dropAttr<DLLImportAttr>(); 5971 NewDecl->dropAttr<DLLImportAttr>(); 5972 } 5973 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5974 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5975 OldDecl->dropAttr<DLLImportAttr>(); 5976 NewDecl->dropAttr<DLLImportAttr>(); 5977 S.Diag(NewDecl->getLocation(), 5978 diag::warn_dllimport_dropped_from_inline_function) 5979 << NewDecl << OldImportAttr; 5980 } 5981 } 5982 5983 /// Given that we are within the definition of the given function, 5984 /// will that definition behave like C99's 'inline', where the 5985 /// definition is discarded except for optimization purposes? 5986 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5987 // Try to avoid calling GetGVALinkageForFunction. 5988 5989 // All cases of this require the 'inline' keyword. 5990 if (!FD->isInlined()) return false; 5991 5992 // This is only possible in C++ with the gnu_inline attribute. 5993 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5994 return false; 5995 5996 // Okay, go ahead and call the relatively-more-expensive function. 5997 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5998 } 5999 6000 /// Determine whether a variable is extern "C" prior to attaching 6001 /// an initializer. We can't just call isExternC() here, because that 6002 /// will also compute and cache whether the declaration is externally 6003 /// visible, which might change when we attach the initializer. 6004 /// 6005 /// This can only be used if the declaration is known to not be a 6006 /// redeclaration of an internal linkage declaration. 6007 /// 6008 /// For instance: 6009 /// 6010 /// auto x = []{}; 6011 /// 6012 /// Attaching the initializer here makes this declaration not externally 6013 /// visible, because its type has internal linkage. 6014 /// 6015 /// FIXME: This is a hack. 6016 template<typename T> 6017 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6018 if (S.getLangOpts().CPlusPlus) { 6019 // In C++, the overloadable attribute negates the effects of extern "C". 6020 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6021 return false; 6022 6023 // So do CUDA's host/device attributes. 6024 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6025 D->template hasAttr<CUDAHostAttr>())) 6026 return false; 6027 } 6028 return D->isExternC(); 6029 } 6030 6031 static bool shouldConsiderLinkage(const VarDecl *VD) { 6032 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6033 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6034 return VD->hasExternalStorage(); 6035 if (DC->isFileContext()) 6036 return true; 6037 if (DC->isRecord()) 6038 return false; 6039 llvm_unreachable("Unexpected context"); 6040 } 6041 6042 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6043 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6044 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6045 isa<OMPDeclareReductionDecl>(DC)) 6046 return true; 6047 if (DC->isRecord()) 6048 return false; 6049 llvm_unreachable("Unexpected context"); 6050 } 6051 6052 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6053 AttributeList::Kind Kind) { 6054 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6055 if (L->getKind() == Kind) 6056 return true; 6057 return false; 6058 } 6059 6060 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6061 AttributeList::Kind Kind) { 6062 // Check decl attributes on the DeclSpec. 6063 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6064 return true; 6065 6066 // Walk the declarator structure, checking decl attributes that were in a type 6067 // position to the decl itself. 6068 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6069 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6070 return true; 6071 } 6072 6073 // Finally, check attributes on the decl itself. 6074 return hasParsedAttr(S, PD.getAttributes(), Kind); 6075 } 6076 6077 /// Adjust the \c DeclContext for a function or variable that might be a 6078 /// function-local external declaration. 6079 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6080 if (!DC->isFunctionOrMethod()) 6081 return false; 6082 6083 // If this is a local extern function or variable declared within a function 6084 // template, don't add it into the enclosing namespace scope until it is 6085 // instantiated; it might have a dependent type right now. 6086 if (DC->isDependentContext()) 6087 return true; 6088 6089 // C++11 [basic.link]p7: 6090 // When a block scope declaration of an entity with linkage is not found to 6091 // refer to some other declaration, then that entity is a member of the 6092 // innermost enclosing namespace. 6093 // 6094 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6095 // semantically-enclosing namespace, not a lexically-enclosing one. 6096 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6097 DC = DC->getParent(); 6098 return true; 6099 } 6100 6101 /// \brief Returns true if given declaration has external C language linkage. 6102 static bool isDeclExternC(const Decl *D) { 6103 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6104 return FD->isExternC(); 6105 if (const auto *VD = dyn_cast<VarDecl>(D)) 6106 return VD->isExternC(); 6107 6108 llvm_unreachable("Unknown type of decl!"); 6109 } 6110 6111 NamedDecl *Sema::ActOnVariableDeclarator( 6112 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6113 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6114 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6115 QualType R = TInfo->getType(); 6116 DeclarationName Name = GetNameForDeclarator(D).getName(); 6117 6118 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6119 6120 if (D.isDecompositionDeclarator()) { 6121 AddToScope = false; 6122 // Take the name of the first declarator as our name for diagnostic 6123 // purposes. 6124 auto &Decomp = D.getDecompositionDeclarator(); 6125 if (!Decomp.bindings().empty()) { 6126 II = Decomp.bindings()[0].Name; 6127 Name = II; 6128 } 6129 } else if (!II) { 6130 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6131 return nullptr; 6132 } 6133 6134 if (getLangOpts().OpenCL) { 6135 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6136 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6137 // argument. 6138 if (R->isImageType() || R->isPipeType()) { 6139 Diag(D.getIdentifierLoc(), 6140 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6141 << R; 6142 D.setInvalidType(); 6143 return nullptr; 6144 } 6145 6146 // OpenCL v1.2 s6.9.r: 6147 // The event type cannot be used to declare a program scope variable. 6148 // OpenCL v2.0 s6.9.q: 6149 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6150 if (NULL == S->getParent()) { 6151 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6152 Diag(D.getIdentifierLoc(), 6153 diag::err_invalid_type_for_program_scope_var) << R; 6154 D.setInvalidType(); 6155 return nullptr; 6156 } 6157 } 6158 6159 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6160 QualType NR = R; 6161 while (NR->isPointerType()) { 6162 if (NR->isFunctionPointerType()) { 6163 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 6164 D.setInvalidType(); 6165 break; 6166 } 6167 NR = NR->getPointeeType(); 6168 } 6169 6170 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6171 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6172 // half array type (unless the cl_khr_fp16 extension is enabled). 6173 if (Context.getBaseElementType(R)->isHalfType()) { 6174 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6175 D.setInvalidType(); 6176 } 6177 } 6178 6179 if (R->isSamplerT()) { 6180 // OpenCL v1.2 s6.9.b p4: 6181 // The sampler type cannot be used with the __local and __global address 6182 // space qualifiers. 6183 if (R.getAddressSpace() == LangAS::opencl_local || 6184 R.getAddressSpace() == LangAS::opencl_global) { 6185 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6186 } 6187 6188 // OpenCL v1.2 s6.12.14.1: 6189 // A global sampler must be declared with either the constant address 6190 // space qualifier or with the const qualifier. 6191 if (DC->isTranslationUnit() && 6192 !(R.getAddressSpace() == LangAS::opencl_constant || 6193 R.isConstQualified())) { 6194 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6195 D.setInvalidType(); 6196 } 6197 } 6198 6199 // OpenCL v1.2 s6.9.r: 6200 // The event type cannot be used with the __local, __constant and __global 6201 // address space qualifiers. 6202 if (R->isEventT()) { 6203 if (R.getAddressSpace()) { 6204 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6205 D.setInvalidType(); 6206 } 6207 } 6208 } 6209 6210 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6211 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6212 6213 // dllimport globals without explicit storage class are treated as extern. We 6214 // have to change the storage class this early to get the right DeclContext. 6215 if (SC == SC_None && !DC->isRecord() && 6216 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6217 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6218 SC = SC_Extern; 6219 6220 DeclContext *OriginalDC = DC; 6221 bool IsLocalExternDecl = SC == SC_Extern && 6222 adjustContextForLocalExternDecl(DC); 6223 6224 if (SCSpec == DeclSpec::SCS_mutable) { 6225 // mutable can only appear on non-static class members, so it's always 6226 // an error here 6227 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6228 D.setInvalidType(); 6229 SC = SC_None; 6230 } 6231 6232 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6233 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6234 D.getDeclSpec().getStorageClassSpecLoc())) { 6235 // In C++11, the 'register' storage class specifier is deprecated. 6236 // Suppress the warning in system macros, it's used in macros in some 6237 // popular C system headers, such as in glibc's htonl() macro. 6238 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6239 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6240 : diag::warn_deprecated_register) 6241 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6242 } 6243 6244 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6245 6246 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6247 // C99 6.9p2: The storage-class specifiers auto and register shall not 6248 // appear in the declaration specifiers in an external declaration. 6249 // Global Register+Asm is a GNU extension we support. 6250 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6251 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6252 D.setInvalidType(); 6253 } 6254 } 6255 6256 bool IsMemberSpecialization = false; 6257 bool IsVariableTemplateSpecialization = false; 6258 bool IsPartialSpecialization = false; 6259 bool IsVariableTemplate = false; 6260 VarDecl *NewVD = nullptr; 6261 VarTemplateDecl *NewTemplate = nullptr; 6262 TemplateParameterList *TemplateParams = nullptr; 6263 if (!getLangOpts().CPlusPlus) { 6264 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6265 D.getIdentifierLoc(), II, 6266 R, TInfo, SC); 6267 6268 if (R->getContainedDeducedType()) 6269 ParsingInitForAutoVars.insert(NewVD); 6270 6271 if (D.isInvalidType()) 6272 NewVD->setInvalidDecl(); 6273 } else { 6274 bool Invalid = false; 6275 6276 if (DC->isRecord() && !CurContext->isRecord()) { 6277 // This is an out-of-line definition of a static data member. 6278 switch (SC) { 6279 case SC_None: 6280 break; 6281 case SC_Static: 6282 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6283 diag::err_static_out_of_line) 6284 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6285 break; 6286 case SC_Auto: 6287 case SC_Register: 6288 case SC_Extern: 6289 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6290 // to names of variables declared in a block or to function parameters. 6291 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6292 // of class members 6293 6294 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6295 diag::err_storage_class_for_static_member) 6296 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6297 break; 6298 case SC_PrivateExtern: 6299 llvm_unreachable("C storage class in c++!"); 6300 } 6301 } 6302 6303 if (SC == SC_Static && CurContext->isRecord()) { 6304 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6305 if (RD->isLocalClass()) 6306 Diag(D.getIdentifierLoc(), 6307 diag::err_static_data_member_not_allowed_in_local_class) 6308 << Name << RD->getDeclName(); 6309 6310 // C++98 [class.union]p1: If a union contains a static data member, 6311 // the program is ill-formed. C++11 drops this restriction. 6312 if (RD->isUnion()) 6313 Diag(D.getIdentifierLoc(), 6314 getLangOpts().CPlusPlus11 6315 ? diag::warn_cxx98_compat_static_data_member_in_union 6316 : diag::ext_static_data_member_in_union) << Name; 6317 // We conservatively disallow static data members in anonymous structs. 6318 else if (!RD->getDeclName()) 6319 Diag(D.getIdentifierLoc(), 6320 diag::err_static_data_member_not_allowed_in_anon_struct) 6321 << Name << RD->isUnion(); 6322 } 6323 } 6324 6325 // Match up the template parameter lists with the scope specifier, then 6326 // determine whether we have a template or a template specialization. 6327 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6328 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6329 D.getCXXScopeSpec(), 6330 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6331 ? D.getName().TemplateId 6332 : nullptr, 6333 TemplateParamLists, 6334 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6335 6336 if (TemplateParams) { 6337 if (!TemplateParams->size() && 6338 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6339 // There is an extraneous 'template<>' for this variable. Complain 6340 // about it, but allow the declaration of the variable. 6341 Diag(TemplateParams->getTemplateLoc(), 6342 diag::err_template_variable_noparams) 6343 << II 6344 << SourceRange(TemplateParams->getTemplateLoc(), 6345 TemplateParams->getRAngleLoc()); 6346 TemplateParams = nullptr; 6347 } else { 6348 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6349 // This is an explicit specialization or a partial specialization. 6350 // FIXME: Check that we can declare a specialization here. 6351 IsVariableTemplateSpecialization = true; 6352 IsPartialSpecialization = TemplateParams->size() > 0; 6353 } else { // if (TemplateParams->size() > 0) 6354 // This is a template declaration. 6355 IsVariableTemplate = true; 6356 6357 // Check that we can declare a template here. 6358 if (CheckTemplateDeclScope(S, TemplateParams)) 6359 return nullptr; 6360 6361 // Only C++1y supports variable templates (N3651). 6362 Diag(D.getIdentifierLoc(), 6363 getLangOpts().CPlusPlus14 6364 ? diag::warn_cxx11_compat_variable_template 6365 : diag::ext_variable_template); 6366 } 6367 } 6368 } else { 6369 assert( 6370 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6371 "should have a 'template<>' for this decl"); 6372 } 6373 6374 if (IsVariableTemplateSpecialization) { 6375 SourceLocation TemplateKWLoc = 6376 TemplateParamLists.size() > 0 6377 ? TemplateParamLists[0]->getTemplateLoc() 6378 : SourceLocation(); 6379 DeclResult Res = ActOnVarTemplateSpecialization( 6380 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6381 IsPartialSpecialization); 6382 if (Res.isInvalid()) 6383 return nullptr; 6384 NewVD = cast<VarDecl>(Res.get()); 6385 AddToScope = false; 6386 } else if (D.isDecompositionDeclarator()) { 6387 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6388 D.getIdentifierLoc(), R, TInfo, SC, 6389 Bindings); 6390 } else 6391 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6392 D.getIdentifierLoc(), II, R, TInfo, SC); 6393 6394 // If this is supposed to be a variable template, create it as such. 6395 if (IsVariableTemplate) { 6396 NewTemplate = 6397 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6398 TemplateParams, NewVD); 6399 NewVD->setDescribedVarTemplate(NewTemplate); 6400 } 6401 6402 // If this decl has an auto type in need of deduction, make a note of the 6403 // Decl so we can diagnose uses of it in its own initializer. 6404 if (R->getContainedDeducedType()) 6405 ParsingInitForAutoVars.insert(NewVD); 6406 6407 if (D.isInvalidType() || Invalid) { 6408 NewVD->setInvalidDecl(); 6409 if (NewTemplate) 6410 NewTemplate->setInvalidDecl(); 6411 } 6412 6413 SetNestedNameSpecifier(NewVD, D); 6414 6415 // If we have any template parameter lists that don't directly belong to 6416 // the variable (matching the scope specifier), store them. 6417 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6418 if (TemplateParamLists.size() > VDTemplateParamLists) 6419 NewVD->setTemplateParameterListsInfo( 6420 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6421 6422 if (D.getDeclSpec().isConstexprSpecified()) { 6423 NewVD->setConstexpr(true); 6424 // C++1z [dcl.spec.constexpr]p1: 6425 // A static data member declared with the constexpr specifier is 6426 // implicitly an inline variable. 6427 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6428 NewVD->setImplicitlyInline(); 6429 } 6430 6431 if (D.getDeclSpec().isConceptSpecified()) { 6432 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6433 VTD->setConcept(); 6434 6435 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6436 // be declared with the thread_local, inline, friend, or constexpr 6437 // specifiers, [...] 6438 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6439 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6440 diag::err_concept_decl_invalid_specifiers) 6441 << 0 << 0; 6442 NewVD->setInvalidDecl(true); 6443 } 6444 6445 if (D.getDeclSpec().isConstexprSpecified()) { 6446 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6447 diag::err_concept_decl_invalid_specifiers) 6448 << 0 << 3; 6449 NewVD->setInvalidDecl(true); 6450 } 6451 6452 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6453 // applied only to the definition of a function template or variable 6454 // template, declared in namespace scope. 6455 if (IsVariableTemplateSpecialization) { 6456 Diag(D.getDeclSpec().getConceptSpecLoc(), 6457 diag::err_concept_specified_specialization) 6458 << (IsPartialSpecialization ? 2 : 1); 6459 } 6460 6461 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6462 // following restrictions: 6463 // - The declared type shall have the type bool. 6464 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6465 !NewVD->isInvalidDecl()) { 6466 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6467 NewVD->setInvalidDecl(true); 6468 } 6469 } 6470 } 6471 6472 if (D.getDeclSpec().isInlineSpecified()) { 6473 if (!getLangOpts().CPlusPlus) { 6474 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6475 << 0; 6476 } else if (CurContext->isFunctionOrMethod()) { 6477 // 'inline' is not allowed on block scope variable declaration. 6478 Diag(D.getDeclSpec().getInlineSpecLoc(), 6479 diag::err_inline_declaration_block_scope) << Name 6480 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6481 } else { 6482 Diag(D.getDeclSpec().getInlineSpecLoc(), 6483 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6484 : diag::ext_inline_variable); 6485 NewVD->setInlineSpecified(); 6486 } 6487 } 6488 6489 // Set the lexical context. If the declarator has a C++ scope specifier, the 6490 // lexical context will be different from the semantic context. 6491 NewVD->setLexicalDeclContext(CurContext); 6492 if (NewTemplate) 6493 NewTemplate->setLexicalDeclContext(CurContext); 6494 6495 if (IsLocalExternDecl) { 6496 if (D.isDecompositionDeclarator()) 6497 for (auto *B : Bindings) 6498 B->setLocalExternDecl(); 6499 else 6500 NewVD->setLocalExternDecl(); 6501 } 6502 6503 bool EmitTLSUnsupportedError = false; 6504 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6505 // C++11 [dcl.stc]p4: 6506 // When thread_local is applied to a variable of block scope the 6507 // storage-class-specifier static is implied if it does not appear 6508 // explicitly. 6509 // Core issue: 'static' is not implied if the variable is declared 6510 // 'extern'. 6511 if (NewVD->hasLocalStorage() && 6512 (SCSpec != DeclSpec::SCS_unspecified || 6513 TSCS != DeclSpec::TSCS_thread_local || 6514 !DC->isFunctionOrMethod())) 6515 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6516 diag::err_thread_non_global) 6517 << DeclSpec::getSpecifierName(TSCS); 6518 else if (!Context.getTargetInfo().isTLSSupported()) { 6519 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6520 // Postpone error emission until we've collected attributes required to 6521 // figure out whether it's a host or device variable and whether the 6522 // error should be ignored. 6523 EmitTLSUnsupportedError = true; 6524 // We still need to mark the variable as TLS so it shows up in AST with 6525 // proper storage class for other tools to use even if we're not going 6526 // to emit any code for it. 6527 NewVD->setTSCSpec(TSCS); 6528 } else 6529 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6530 diag::err_thread_unsupported); 6531 } else 6532 NewVD->setTSCSpec(TSCS); 6533 } 6534 6535 // C99 6.7.4p3 6536 // An inline definition of a function with external linkage shall 6537 // not contain a definition of a modifiable object with static or 6538 // thread storage duration... 6539 // We only apply this when the function is required to be defined 6540 // elsewhere, i.e. when the function is not 'extern inline'. Note 6541 // that a local variable with thread storage duration still has to 6542 // be marked 'static'. Also note that it's possible to get these 6543 // semantics in C++ using __attribute__((gnu_inline)). 6544 if (SC == SC_Static && S->getFnParent() != nullptr && 6545 !NewVD->getType().isConstQualified()) { 6546 FunctionDecl *CurFD = getCurFunctionDecl(); 6547 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6548 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6549 diag::warn_static_local_in_extern_inline); 6550 MaybeSuggestAddingStaticToDecl(CurFD); 6551 } 6552 } 6553 6554 if (D.getDeclSpec().isModulePrivateSpecified()) { 6555 if (IsVariableTemplateSpecialization) 6556 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6557 << (IsPartialSpecialization ? 1 : 0) 6558 << FixItHint::CreateRemoval( 6559 D.getDeclSpec().getModulePrivateSpecLoc()); 6560 else if (IsMemberSpecialization) 6561 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6562 << 2 6563 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6564 else if (NewVD->hasLocalStorage()) 6565 Diag(NewVD->getLocation(), diag::err_module_private_local) 6566 << 0 << NewVD->getDeclName() 6567 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6568 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6569 else { 6570 NewVD->setModulePrivate(); 6571 if (NewTemplate) 6572 NewTemplate->setModulePrivate(); 6573 for (auto *B : Bindings) 6574 B->setModulePrivate(); 6575 } 6576 } 6577 6578 // Handle attributes prior to checking for duplicates in MergeVarDecl 6579 ProcessDeclAttributes(S, NewVD, D); 6580 6581 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6582 if (EmitTLSUnsupportedError && 6583 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6584 (getLangOpts().OpenMPIsDevice && 6585 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6586 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6587 diag::err_thread_unsupported); 6588 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6589 // storage [duration]." 6590 if (SC == SC_None && S->getFnParent() != nullptr && 6591 (NewVD->hasAttr<CUDASharedAttr>() || 6592 NewVD->hasAttr<CUDAConstantAttr>())) { 6593 NewVD->setStorageClass(SC_Static); 6594 } 6595 } 6596 6597 // Ensure that dllimport globals without explicit storage class are treated as 6598 // extern. The storage class is set above using parsed attributes. Now we can 6599 // check the VarDecl itself. 6600 assert(!NewVD->hasAttr<DLLImportAttr>() || 6601 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6602 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6603 6604 // In auto-retain/release, infer strong retension for variables of 6605 // retainable type. 6606 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6607 NewVD->setInvalidDecl(); 6608 6609 // Handle GNU asm-label extension (encoded as an attribute). 6610 if (Expr *E = (Expr*)D.getAsmLabel()) { 6611 // The parser guarantees this is a string. 6612 StringLiteral *SE = cast<StringLiteral>(E); 6613 StringRef Label = SE->getString(); 6614 if (S->getFnParent() != nullptr) { 6615 switch (SC) { 6616 case SC_None: 6617 case SC_Auto: 6618 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6619 break; 6620 case SC_Register: 6621 // Local Named register 6622 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6623 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6624 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6625 break; 6626 case SC_Static: 6627 case SC_Extern: 6628 case SC_PrivateExtern: 6629 break; 6630 } 6631 } else if (SC == SC_Register) { 6632 // Global Named register 6633 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6634 const auto &TI = Context.getTargetInfo(); 6635 bool HasSizeMismatch; 6636 6637 if (!TI.isValidGCCRegisterName(Label)) 6638 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6639 else if (!TI.validateGlobalRegisterVariable(Label, 6640 Context.getTypeSize(R), 6641 HasSizeMismatch)) 6642 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6643 else if (HasSizeMismatch) 6644 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6645 } 6646 6647 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6648 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6649 NewVD->setInvalidDecl(true); 6650 } 6651 } 6652 6653 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6654 Context, Label, 0)); 6655 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6656 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6657 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6658 if (I != ExtnameUndeclaredIdentifiers.end()) { 6659 if (isDeclExternC(NewVD)) { 6660 NewVD->addAttr(I->second); 6661 ExtnameUndeclaredIdentifiers.erase(I); 6662 } else 6663 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6664 << /*Variable*/1 << NewVD; 6665 } 6666 } 6667 6668 // Find the shadowed declaration before filtering for scope. 6669 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6670 ? getShadowedDeclaration(NewVD, Previous) 6671 : nullptr; 6672 6673 // Don't consider existing declarations that are in a different 6674 // scope and are out-of-semantic-context declarations (if the new 6675 // declaration has linkage). 6676 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6677 D.getCXXScopeSpec().isNotEmpty() || 6678 IsMemberSpecialization || 6679 IsVariableTemplateSpecialization); 6680 6681 // Check whether the previous declaration is in the same block scope. This 6682 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6683 if (getLangOpts().CPlusPlus && 6684 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6685 NewVD->setPreviousDeclInSameBlockScope( 6686 Previous.isSingleResult() && !Previous.isShadowed() && 6687 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6688 6689 if (!getLangOpts().CPlusPlus) { 6690 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6691 } else { 6692 // If this is an explicit specialization of a static data member, check it. 6693 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6694 CheckMemberSpecialization(NewVD, Previous)) 6695 NewVD->setInvalidDecl(); 6696 6697 // Merge the decl with the existing one if appropriate. 6698 if (!Previous.empty()) { 6699 if (Previous.isSingleResult() && 6700 isa<FieldDecl>(Previous.getFoundDecl()) && 6701 D.getCXXScopeSpec().isSet()) { 6702 // The user tried to define a non-static data member 6703 // out-of-line (C++ [dcl.meaning]p1). 6704 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6705 << D.getCXXScopeSpec().getRange(); 6706 Previous.clear(); 6707 NewVD->setInvalidDecl(); 6708 } 6709 } else if (D.getCXXScopeSpec().isSet()) { 6710 // No previous declaration in the qualifying scope. 6711 Diag(D.getIdentifierLoc(), diag::err_no_member) 6712 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6713 << D.getCXXScopeSpec().getRange(); 6714 NewVD->setInvalidDecl(); 6715 } 6716 6717 if (!IsVariableTemplateSpecialization) 6718 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6719 6720 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6721 // an explicit specialization (14.8.3) or a partial specialization of a 6722 // concept definition. 6723 if (IsVariableTemplateSpecialization && 6724 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6725 Previous.isSingleResult()) { 6726 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6727 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6728 if (VarTmpl->isConcept()) { 6729 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6730 << 1 /*variable*/ 6731 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6732 : 1 /*explicitly specialized*/); 6733 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6734 NewVD->setInvalidDecl(); 6735 } 6736 } 6737 } 6738 6739 if (NewTemplate) { 6740 VarTemplateDecl *PrevVarTemplate = 6741 NewVD->getPreviousDecl() 6742 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6743 : nullptr; 6744 6745 // Check the template parameter list of this declaration, possibly 6746 // merging in the template parameter list from the previous variable 6747 // template declaration. 6748 if (CheckTemplateParameterList( 6749 TemplateParams, 6750 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6751 : nullptr, 6752 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6753 DC->isDependentContext()) 6754 ? TPC_ClassTemplateMember 6755 : TPC_VarTemplate)) 6756 NewVD->setInvalidDecl(); 6757 6758 // If we are providing an explicit specialization of a static variable 6759 // template, make a note of that. 6760 if (PrevVarTemplate && 6761 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6762 PrevVarTemplate->setMemberSpecialization(); 6763 } 6764 } 6765 6766 // Diagnose shadowed variables iff this isn't a redeclaration. 6767 if (ShadowedDecl && !D.isRedeclaration()) 6768 CheckShadow(NewVD, ShadowedDecl, Previous); 6769 6770 ProcessPragmaWeak(S, NewVD); 6771 6772 // If this is the first declaration of an extern C variable, update 6773 // the map of such variables. 6774 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6775 isIncompleteDeclExternC(*this, NewVD)) 6776 RegisterLocallyScopedExternCDecl(NewVD, S); 6777 6778 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6779 Decl *ManglingContextDecl; 6780 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6781 NewVD->getDeclContext(), ManglingContextDecl)) { 6782 Context.setManglingNumber( 6783 NewVD, MCtx->getManglingNumber( 6784 NewVD, getMSManglingNumber(getLangOpts(), S))); 6785 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6786 } 6787 } 6788 6789 // Special handling of variable named 'main'. 6790 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6791 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6792 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6793 6794 // C++ [basic.start.main]p3 6795 // A program that declares a variable main at global scope is ill-formed. 6796 if (getLangOpts().CPlusPlus) 6797 Diag(D.getLocStart(), diag::err_main_global_variable); 6798 6799 // In C, and external-linkage variable named main results in undefined 6800 // behavior. 6801 else if (NewVD->hasExternalFormalLinkage()) 6802 Diag(D.getLocStart(), diag::warn_main_redefined); 6803 } 6804 6805 if (D.isRedeclaration() && !Previous.empty()) { 6806 checkDLLAttributeRedeclaration( 6807 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6808 IsMemberSpecialization, D.isFunctionDefinition()); 6809 } 6810 6811 if (NewTemplate) { 6812 if (NewVD->isInvalidDecl()) 6813 NewTemplate->setInvalidDecl(); 6814 ActOnDocumentableDecl(NewTemplate); 6815 return NewTemplate; 6816 } 6817 6818 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6819 CompleteMemberSpecialization(NewVD, Previous); 6820 6821 return NewVD; 6822 } 6823 6824 /// Enum describing the %select options in diag::warn_decl_shadow. 6825 enum ShadowedDeclKind { 6826 SDK_Local, 6827 SDK_Global, 6828 SDK_StaticMember, 6829 SDK_Field, 6830 SDK_Typedef, 6831 SDK_Using 6832 }; 6833 6834 /// Determine what kind of declaration we're shadowing. 6835 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6836 const DeclContext *OldDC) { 6837 if (isa<TypeAliasDecl>(ShadowedDecl)) 6838 return SDK_Using; 6839 else if (isa<TypedefDecl>(ShadowedDecl)) 6840 return SDK_Typedef; 6841 else if (isa<RecordDecl>(OldDC)) 6842 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6843 6844 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6845 } 6846 6847 /// Return the location of the capture if the given lambda captures the given 6848 /// variable \p VD, or an invalid source location otherwise. 6849 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6850 const VarDecl *VD) { 6851 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6852 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6853 return Capture.getLocation(); 6854 } 6855 return SourceLocation(); 6856 } 6857 6858 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6859 const LookupResult &R) { 6860 // Only diagnose if we're shadowing an unambiguous field or variable. 6861 if (R.getResultKind() != LookupResult::Found) 6862 return false; 6863 6864 // Return false if warning is ignored. 6865 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6866 } 6867 6868 /// \brief Return the declaration shadowed by the given variable \p D, or null 6869 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6870 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6871 const LookupResult &R) { 6872 if (!shouldWarnIfShadowedDecl(Diags, R)) 6873 return nullptr; 6874 6875 // Don't diagnose declarations at file scope. 6876 if (D->hasGlobalStorage()) 6877 return nullptr; 6878 6879 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6880 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6881 ? ShadowedDecl 6882 : nullptr; 6883 } 6884 6885 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6886 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6887 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6888 const LookupResult &R) { 6889 // Don't warn if typedef declaration is part of a class 6890 if (D->getDeclContext()->isRecord()) 6891 return nullptr; 6892 6893 if (!shouldWarnIfShadowedDecl(Diags, R)) 6894 return nullptr; 6895 6896 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6897 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6898 } 6899 6900 /// \brief Diagnose variable or built-in function shadowing. Implements 6901 /// -Wshadow. 6902 /// 6903 /// This method is called whenever a VarDecl is added to a "useful" 6904 /// scope. 6905 /// 6906 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6907 /// \param R the lookup of the name 6908 /// 6909 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 6910 const LookupResult &R) { 6911 DeclContext *NewDC = D->getDeclContext(); 6912 6913 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6914 // Fields are not shadowed by variables in C++ static methods. 6915 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6916 if (MD->isStatic()) 6917 return; 6918 6919 // Fields shadowed by constructor parameters are a special case. Usually 6920 // the constructor initializes the field with the parameter. 6921 if (isa<CXXConstructorDecl>(NewDC)) 6922 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 6923 // Remember that this was shadowed so we can either warn about its 6924 // modification or its existence depending on warning settings. 6925 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 6926 return; 6927 } 6928 } 6929 6930 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6931 if (shadowedVar->isExternC()) { 6932 // For shadowing external vars, make sure that we point to the global 6933 // declaration, not a locally scoped extern declaration. 6934 for (auto I : shadowedVar->redecls()) 6935 if (I->isFileVarDecl()) { 6936 ShadowedDecl = I; 6937 break; 6938 } 6939 } 6940 6941 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 6942 6943 unsigned WarningDiag = diag::warn_decl_shadow; 6944 SourceLocation CaptureLoc; 6945 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 6946 isa<CXXMethodDecl>(NewDC)) { 6947 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6948 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6949 if (RD->getLambdaCaptureDefault() == LCD_None) { 6950 // Try to avoid warnings for lambdas with an explicit capture list. 6951 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6952 // Warn only when the lambda captures the shadowed decl explicitly. 6953 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 6954 if (CaptureLoc.isInvalid()) 6955 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 6956 } else { 6957 // Remember that this was shadowed so we can avoid the warning if the 6958 // shadowed decl isn't captured and the warning settings allow it. 6959 cast<LambdaScopeInfo>(getCurFunction()) 6960 ->ShadowingDecls.push_back( 6961 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 6962 return; 6963 } 6964 } 6965 } 6966 } 6967 6968 // Only warn about certain kinds of shadowing for class members. 6969 if (NewDC && NewDC->isRecord()) { 6970 // In particular, don't warn about shadowing non-class members. 6971 if (!OldDC->isRecord()) 6972 return; 6973 6974 // TODO: should we warn about static data members shadowing 6975 // static data members from base classes? 6976 6977 // TODO: don't diagnose for inaccessible shadowed members. 6978 // This is hard to do perfectly because we might friend the 6979 // shadowing context, but that's just a false negative. 6980 } 6981 6982 6983 DeclarationName Name = R.getLookupName(); 6984 6985 // Emit warning and note. 6986 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6987 return; 6988 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6989 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 6990 if (!CaptureLoc.isInvalid()) 6991 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6992 << Name << /*explicitly*/ 1; 6993 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6994 } 6995 6996 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 6997 /// when these variables are captured by the lambda. 6998 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 6999 for (const auto &Shadow : LSI->ShadowingDecls) { 7000 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7001 // Try to avoid the warning when the shadowed decl isn't captured. 7002 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7003 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7004 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7005 ? diag::warn_decl_shadow_uncaptured_local 7006 : diag::warn_decl_shadow) 7007 << Shadow.VD->getDeclName() 7008 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7009 if (!CaptureLoc.isInvalid()) 7010 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7011 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7012 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7013 } 7014 } 7015 7016 /// \brief Check -Wshadow without the advantage of a previous lookup. 7017 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7018 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7019 return; 7020 7021 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7022 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 7023 LookupName(R, S); 7024 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7025 CheckShadow(D, ShadowedDecl, R); 7026 } 7027 7028 /// Check if 'E', which is an expression that is about to be modified, refers 7029 /// to a constructor parameter that shadows a field. 7030 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7031 // Quickly ignore expressions that can't be shadowing ctor parameters. 7032 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7033 return; 7034 E = E->IgnoreParenImpCasts(); 7035 auto *DRE = dyn_cast<DeclRefExpr>(E); 7036 if (!DRE) 7037 return; 7038 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7039 auto I = ShadowingDecls.find(D); 7040 if (I == ShadowingDecls.end()) 7041 return; 7042 const NamedDecl *ShadowedDecl = I->second; 7043 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7044 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7045 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7046 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7047 7048 // Avoid issuing multiple warnings about the same decl. 7049 ShadowingDecls.erase(I); 7050 } 7051 7052 /// Check for conflict between this global or extern "C" declaration and 7053 /// previous global or extern "C" declarations. This is only used in C++. 7054 template<typename T> 7055 static bool checkGlobalOrExternCConflict( 7056 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7057 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7058 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7059 7060 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7061 // The common case: this global doesn't conflict with any extern "C" 7062 // declaration. 7063 return false; 7064 } 7065 7066 if (Prev) { 7067 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7068 // Both the old and new declarations have C language linkage. This is a 7069 // redeclaration. 7070 Previous.clear(); 7071 Previous.addDecl(Prev); 7072 return true; 7073 } 7074 7075 // This is a global, non-extern "C" declaration, and there is a previous 7076 // non-global extern "C" declaration. Diagnose if this is a variable 7077 // declaration. 7078 if (!isa<VarDecl>(ND)) 7079 return false; 7080 } else { 7081 // The declaration is extern "C". Check for any declaration in the 7082 // translation unit which might conflict. 7083 if (IsGlobal) { 7084 // We have already performed the lookup into the translation unit. 7085 IsGlobal = false; 7086 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7087 I != E; ++I) { 7088 if (isa<VarDecl>(*I)) { 7089 Prev = *I; 7090 break; 7091 } 7092 } 7093 } else { 7094 DeclContext::lookup_result R = 7095 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7096 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7097 I != E; ++I) { 7098 if (isa<VarDecl>(*I)) { 7099 Prev = *I; 7100 break; 7101 } 7102 // FIXME: If we have any other entity with this name in global scope, 7103 // the declaration is ill-formed, but that is a defect: it breaks the 7104 // 'stat' hack, for instance. Only variables can have mangled name 7105 // clashes with extern "C" declarations, so only they deserve a 7106 // diagnostic. 7107 } 7108 } 7109 7110 if (!Prev) 7111 return false; 7112 } 7113 7114 // Use the first declaration's location to ensure we point at something which 7115 // is lexically inside an extern "C" linkage-spec. 7116 assert(Prev && "should have found a previous declaration to diagnose"); 7117 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7118 Prev = FD->getFirstDecl(); 7119 else 7120 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7121 7122 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7123 << IsGlobal << ND; 7124 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7125 << IsGlobal; 7126 return false; 7127 } 7128 7129 /// Apply special rules for handling extern "C" declarations. Returns \c true 7130 /// if we have found that this is a redeclaration of some prior entity. 7131 /// 7132 /// Per C++ [dcl.link]p6: 7133 /// Two declarations [for a function or variable] with C language linkage 7134 /// with the same name that appear in different scopes refer to the same 7135 /// [entity]. An entity with C language linkage shall not be declared with 7136 /// the same name as an entity in global scope. 7137 template<typename T> 7138 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7139 LookupResult &Previous) { 7140 if (!S.getLangOpts().CPlusPlus) { 7141 // In C, when declaring a global variable, look for a corresponding 'extern' 7142 // variable declared in function scope. We don't need this in C++, because 7143 // we find local extern decls in the surrounding file-scope DeclContext. 7144 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7145 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7146 Previous.clear(); 7147 Previous.addDecl(Prev); 7148 return true; 7149 } 7150 } 7151 return false; 7152 } 7153 7154 // A declaration in the translation unit can conflict with an extern "C" 7155 // declaration. 7156 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7157 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7158 7159 // An extern "C" declaration can conflict with a declaration in the 7160 // translation unit or can be a redeclaration of an extern "C" declaration 7161 // in another scope. 7162 if (isIncompleteDeclExternC(S,ND)) 7163 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7164 7165 // Neither global nor extern "C": nothing to do. 7166 return false; 7167 } 7168 7169 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7170 // If the decl is already known invalid, don't check it. 7171 if (NewVD->isInvalidDecl()) 7172 return; 7173 7174 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7175 QualType T = TInfo->getType(); 7176 7177 // Defer checking an 'auto' type until its initializer is attached. 7178 if (T->isUndeducedType()) 7179 return; 7180 7181 if (NewVD->hasAttrs()) 7182 CheckAlignasUnderalignment(NewVD); 7183 7184 if (T->isObjCObjectType()) { 7185 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7186 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7187 T = Context.getObjCObjectPointerType(T); 7188 NewVD->setType(T); 7189 } 7190 7191 // Emit an error if an address space was applied to decl with local storage. 7192 // This includes arrays of objects with address space qualifiers, but not 7193 // automatic variables that point to other address spaces. 7194 // ISO/IEC TR 18037 S5.1.2 7195 if (!getLangOpts().OpenCL 7196 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 7197 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7198 NewVD->setInvalidDecl(); 7199 return; 7200 } 7201 7202 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7203 // scope. 7204 if (getLangOpts().OpenCLVersion == 120 && 7205 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7206 NewVD->isStaticLocal()) { 7207 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7208 NewVD->setInvalidDecl(); 7209 return; 7210 } 7211 7212 if (getLangOpts().OpenCL) { 7213 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7214 if (NewVD->hasAttr<BlocksAttr>()) { 7215 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7216 return; 7217 } 7218 7219 if (T->isBlockPointerType()) { 7220 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7221 // can't use 'extern' storage class. 7222 if (!T.isConstQualified()) { 7223 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7224 << 0 /*const*/; 7225 NewVD->setInvalidDecl(); 7226 return; 7227 } 7228 if (NewVD->hasExternalStorage()) { 7229 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7230 NewVD->setInvalidDecl(); 7231 return; 7232 } 7233 } 7234 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7235 // __constant address space. 7236 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7237 // variables inside a function can also be declared in the global 7238 // address space. 7239 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7240 NewVD->hasExternalStorage()) { 7241 if (!T->isSamplerT() && 7242 !(T.getAddressSpace() == LangAS::opencl_constant || 7243 (T.getAddressSpace() == LangAS::opencl_global && 7244 getLangOpts().OpenCLVersion == 200))) { 7245 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7246 if (getLangOpts().OpenCLVersion == 200) 7247 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7248 << Scope << "global or constant"; 7249 else 7250 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7251 << Scope << "constant"; 7252 NewVD->setInvalidDecl(); 7253 return; 7254 } 7255 } else { 7256 if (T.getAddressSpace() == LangAS::opencl_global) { 7257 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7258 << 1 /*is any function*/ << "global"; 7259 NewVD->setInvalidDecl(); 7260 return; 7261 } 7262 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 7263 // in functions. 7264 if (T.getAddressSpace() == LangAS::opencl_constant || 7265 T.getAddressSpace() == LangAS::opencl_local) { 7266 FunctionDecl *FD = getCurFunctionDecl(); 7267 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7268 if (T.getAddressSpace() == LangAS::opencl_constant) 7269 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7270 << 0 /*non-kernel only*/ << "constant"; 7271 else 7272 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7273 << 0 /*non-kernel only*/ << "local"; 7274 NewVD->setInvalidDecl(); 7275 return; 7276 } 7277 } else if (T.getAddressSpace() != LangAS::Default) { 7278 // Do not allow other address spaces on automatic variable. 7279 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7280 NewVD->setInvalidDecl(); 7281 return; 7282 } 7283 } 7284 } 7285 7286 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7287 && !NewVD->hasAttr<BlocksAttr>()) { 7288 if (getLangOpts().getGC() != LangOptions::NonGC) 7289 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7290 else { 7291 assert(!getLangOpts().ObjCAutoRefCount); 7292 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7293 } 7294 } 7295 7296 bool isVM = T->isVariablyModifiedType(); 7297 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7298 NewVD->hasAttr<BlocksAttr>()) 7299 getCurFunction()->setHasBranchProtectedScope(); 7300 7301 if ((isVM && NewVD->hasLinkage()) || 7302 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7303 bool SizeIsNegative; 7304 llvm::APSInt Oversized; 7305 TypeSourceInfo *FixedTInfo = 7306 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7307 SizeIsNegative, Oversized); 7308 if (!FixedTInfo && T->isVariableArrayType()) { 7309 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7310 // FIXME: This won't give the correct result for 7311 // int a[10][n]; 7312 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7313 7314 if (NewVD->isFileVarDecl()) 7315 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7316 << SizeRange; 7317 else if (NewVD->isStaticLocal()) 7318 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7319 << SizeRange; 7320 else 7321 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7322 << SizeRange; 7323 NewVD->setInvalidDecl(); 7324 return; 7325 } 7326 7327 if (!FixedTInfo) { 7328 if (NewVD->isFileVarDecl()) 7329 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7330 else 7331 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7332 NewVD->setInvalidDecl(); 7333 return; 7334 } 7335 7336 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7337 NewVD->setType(FixedTInfo->getType()); 7338 NewVD->setTypeSourceInfo(FixedTInfo); 7339 } 7340 7341 if (T->isVoidType()) { 7342 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7343 // of objects and functions. 7344 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7345 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7346 << T; 7347 NewVD->setInvalidDecl(); 7348 return; 7349 } 7350 } 7351 7352 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7353 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7354 NewVD->setInvalidDecl(); 7355 return; 7356 } 7357 7358 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7359 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7360 NewVD->setInvalidDecl(); 7361 return; 7362 } 7363 7364 if (NewVD->isConstexpr() && !T->isDependentType() && 7365 RequireLiteralType(NewVD->getLocation(), T, 7366 diag::err_constexpr_var_non_literal)) { 7367 NewVD->setInvalidDecl(); 7368 return; 7369 } 7370 } 7371 7372 /// \brief Perform semantic checking on a newly-created variable 7373 /// declaration. 7374 /// 7375 /// This routine performs all of the type-checking required for a 7376 /// variable declaration once it has been built. It is used both to 7377 /// check variables after they have been parsed and their declarators 7378 /// have been translated into a declaration, and to check variables 7379 /// that have been instantiated from a template. 7380 /// 7381 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7382 /// 7383 /// Returns true if the variable declaration is a redeclaration. 7384 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7385 CheckVariableDeclarationType(NewVD); 7386 7387 // If the decl is already known invalid, don't check it. 7388 if (NewVD->isInvalidDecl()) 7389 return false; 7390 7391 // If we did not find anything by this name, look for a non-visible 7392 // extern "C" declaration with the same name. 7393 if (Previous.empty() && 7394 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7395 Previous.setShadowed(); 7396 7397 if (!Previous.empty()) { 7398 MergeVarDecl(NewVD, Previous); 7399 return true; 7400 } 7401 return false; 7402 } 7403 7404 namespace { 7405 struct FindOverriddenMethod { 7406 Sema *S; 7407 CXXMethodDecl *Method; 7408 7409 /// Member lookup function that determines whether a given C++ 7410 /// method overrides a method in a base class, to be used with 7411 /// CXXRecordDecl::lookupInBases(). 7412 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7413 RecordDecl *BaseRecord = 7414 Specifier->getType()->getAs<RecordType>()->getDecl(); 7415 7416 DeclarationName Name = Method->getDeclName(); 7417 7418 // FIXME: Do we care about other names here too? 7419 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7420 // We really want to find the base class destructor here. 7421 QualType T = S->Context.getTypeDeclType(BaseRecord); 7422 CanQualType CT = S->Context.getCanonicalType(T); 7423 7424 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7425 } 7426 7427 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7428 Path.Decls = Path.Decls.slice(1)) { 7429 NamedDecl *D = Path.Decls.front(); 7430 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7431 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7432 return true; 7433 } 7434 } 7435 7436 return false; 7437 } 7438 }; 7439 7440 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7441 } // end anonymous namespace 7442 7443 /// \brief Report an error regarding overriding, along with any relevant 7444 /// overriden methods. 7445 /// 7446 /// \param DiagID the primary error to report. 7447 /// \param MD the overriding method. 7448 /// \param OEK which overrides to include as notes. 7449 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7450 OverrideErrorKind OEK = OEK_All) { 7451 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7452 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7453 E = MD->end_overridden_methods(); 7454 I != E; ++I) { 7455 // This check (& the OEK parameter) could be replaced by a predicate, but 7456 // without lambdas that would be overkill. This is still nicer than writing 7457 // out the diag loop 3 times. 7458 if ((OEK == OEK_All) || 7459 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7460 (OEK == OEK_Deleted && (*I)->isDeleted())) 7461 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7462 } 7463 } 7464 7465 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7466 /// and if so, check that it's a valid override and remember it. 7467 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7468 // Look for methods in base classes that this method might override. 7469 CXXBasePaths Paths; 7470 FindOverriddenMethod FOM; 7471 FOM.Method = MD; 7472 FOM.S = this; 7473 bool hasDeletedOverridenMethods = false; 7474 bool hasNonDeletedOverridenMethods = false; 7475 bool AddedAny = false; 7476 if (DC->lookupInBases(FOM, Paths)) { 7477 for (auto *I : Paths.found_decls()) { 7478 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7479 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7480 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7481 !CheckOverridingFunctionAttributes(MD, OldMD) && 7482 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7483 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7484 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7485 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7486 AddedAny = true; 7487 } 7488 } 7489 } 7490 } 7491 7492 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7493 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7494 } 7495 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7496 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7497 } 7498 7499 return AddedAny; 7500 } 7501 7502 namespace { 7503 // Struct for holding all of the extra arguments needed by 7504 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7505 struct ActOnFDArgs { 7506 Scope *S; 7507 Declarator &D; 7508 MultiTemplateParamsArg TemplateParamLists; 7509 bool AddToScope; 7510 }; 7511 } // end anonymous namespace 7512 7513 namespace { 7514 7515 // Callback to only accept typo corrections that have a non-zero edit distance. 7516 // Also only accept corrections that have the same parent decl. 7517 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7518 public: 7519 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7520 CXXRecordDecl *Parent) 7521 : Context(Context), OriginalFD(TypoFD), 7522 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7523 7524 bool ValidateCandidate(const TypoCorrection &candidate) override { 7525 if (candidate.getEditDistance() == 0) 7526 return false; 7527 7528 SmallVector<unsigned, 1> MismatchedParams; 7529 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7530 CDeclEnd = candidate.end(); 7531 CDecl != CDeclEnd; ++CDecl) { 7532 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7533 7534 if (FD && !FD->hasBody() && 7535 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7536 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7537 CXXRecordDecl *Parent = MD->getParent(); 7538 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7539 return true; 7540 } else if (!ExpectedParent) { 7541 return true; 7542 } 7543 } 7544 } 7545 7546 return false; 7547 } 7548 7549 private: 7550 ASTContext &Context; 7551 FunctionDecl *OriginalFD; 7552 CXXRecordDecl *ExpectedParent; 7553 }; 7554 7555 } // end anonymous namespace 7556 7557 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7558 TypoCorrectedFunctionDefinitions.insert(F); 7559 } 7560 7561 /// \brief Generate diagnostics for an invalid function redeclaration. 7562 /// 7563 /// This routine handles generating the diagnostic messages for an invalid 7564 /// function redeclaration, including finding possible similar declarations 7565 /// or performing typo correction if there are no previous declarations with 7566 /// the same name. 7567 /// 7568 /// Returns a NamedDecl iff typo correction was performed and substituting in 7569 /// the new declaration name does not cause new errors. 7570 static NamedDecl *DiagnoseInvalidRedeclaration( 7571 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7572 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7573 DeclarationName Name = NewFD->getDeclName(); 7574 DeclContext *NewDC = NewFD->getDeclContext(); 7575 SmallVector<unsigned, 1> MismatchedParams; 7576 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7577 TypoCorrection Correction; 7578 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7579 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7580 : diag::err_member_decl_does_not_match; 7581 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7582 IsLocalFriend ? Sema::LookupLocalFriendName 7583 : Sema::LookupOrdinaryName, 7584 Sema::ForRedeclaration); 7585 7586 NewFD->setInvalidDecl(); 7587 if (IsLocalFriend) 7588 SemaRef.LookupName(Prev, S); 7589 else 7590 SemaRef.LookupQualifiedName(Prev, NewDC); 7591 assert(!Prev.isAmbiguous() && 7592 "Cannot have an ambiguity in previous-declaration lookup"); 7593 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7594 if (!Prev.empty()) { 7595 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7596 Func != FuncEnd; ++Func) { 7597 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7598 if (FD && 7599 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7600 // Add 1 to the index so that 0 can mean the mismatch didn't 7601 // involve a parameter 7602 unsigned ParamNum = 7603 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7604 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7605 } 7606 } 7607 // If the qualified name lookup yielded nothing, try typo correction 7608 } else if ((Correction = SemaRef.CorrectTypo( 7609 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7610 &ExtraArgs.D.getCXXScopeSpec(), 7611 llvm::make_unique<DifferentNameValidatorCCC>( 7612 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7613 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7614 // Set up everything for the call to ActOnFunctionDeclarator 7615 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7616 ExtraArgs.D.getIdentifierLoc()); 7617 Previous.clear(); 7618 Previous.setLookupName(Correction.getCorrection()); 7619 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7620 CDeclEnd = Correction.end(); 7621 CDecl != CDeclEnd; ++CDecl) { 7622 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7623 if (FD && !FD->hasBody() && 7624 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7625 Previous.addDecl(FD); 7626 } 7627 } 7628 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7629 7630 NamedDecl *Result; 7631 // Retry building the function declaration with the new previous 7632 // declarations, and with errors suppressed. 7633 { 7634 // Trap errors. 7635 Sema::SFINAETrap Trap(SemaRef); 7636 7637 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7638 // pieces need to verify the typo-corrected C++ declaration and hopefully 7639 // eliminate the need for the parameter pack ExtraArgs. 7640 Result = SemaRef.ActOnFunctionDeclarator( 7641 ExtraArgs.S, ExtraArgs.D, 7642 Correction.getCorrectionDecl()->getDeclContext(), 7643 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7644 ExtraArgs.AddToScope); 7645 7646 if (Trap.hasErrorOccurred()) 7647 Result = nullptr; 7648 } 7649 7650 if (Result) { 7651 // Determine which correction we picked. 7652 Decl *Canonical = Result->getCanonicalDecl(); 7653 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7654 I != E; ++I) 7655 if ((*I)->getCanonicalDecl() == Canonical) 7656 Correction.setCorrectionDecl(*I); 7657 7658 // Let Sema know about the correction. 7659 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7660 SemaRef.diagnoseTypo( 7661 Correction, 7662 SemaRef.PDiag(IsLocalFriend 7663 ? diag::err_no_matching_local_friend_suggest 7664 : diag::err_member_decl_does_not_match_suggest) 7665 << Name << NewDC << IsDefinition); 7666 return Result; 7667 } 7668 7669 // Pretend the typo correction never occurred 7670 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7671 ExtraArgs.D.getIdentifierLoc()); 7672 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7673 Previous.clear(); 7674 Previous.setLookupName(Name); 7675 } 7676 7677 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7678 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7679 7680 bool NewFDisConst = false; 7681 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7682 NewFDisConst = NewMD->isConst(); 7683 7684 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7685 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7686 NearMatch != NearMatchEnd; ++NearMatch) { 7687 FunctionDecl *FD = NearMatch->first; 7688 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7689 bool FDisConst = MD && MD->isConst(); 7690 bool IsMember = MD || !IsLocalFriend; 7691 7692 // FIXME: These notes are poorly worded for the local friend case. 7693 if (unsigned Idx = NearMatch->second) { 7694 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7695 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7696 if (Loc.isInvalid()) Loc = FD->getLocation(); 7697 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7698 : diag::note_local_decl_close_param_match) 7699 << Idx << FDParam->getType() 7700 << NewFD->getParamDecl(Idx - 1)->getType(); 7701 } else if (FDisConst != NewFDisConst) { 7702 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7703 << NewFDisConst << FD->getSourceRange().getEnd(); 7704 } else 7705 SemaRef.Diag(FD->getLocation(), 7706 IsMember ? diag::note_member_def_close_match 7707 : diag::note_local_decl_close_match); 7708 } 7709 return nullptr; 7710 } 7711 7712 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7713 switch (D.getDeclSpec().getStorageClassSpec()) { 7714 default: llvm_unreachable("Unknown storage class!"); 7715 case DeclSpec::SCS_auto: 7716 case DeclSpec::SCS_register: 7717 case DeclSpec::SCS_mutable: 7718 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7719 diag::err_typecheck_sclass_func); 7720 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7721 D.setInvalidType(); 7722 break; 7723 case DeclSpec::SCS_unspecified: break; 7724 case DeclSpec::SCS_extern: 7725 if (D.getDeclSpec().isExternInLinkageSpec()) 7726 return SC_None; 7727 return SC_Extern; 7728 case DeclSpec::SCS_static: { 7729 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7730 // C99 6.7.1p5: 7731 // The declaration of an identifier for a function that has 7732 // block scope shall have no explicit storage-class specifier 7733 // other than extern 7734 // See also (C++ [dcl.stc]p4). 7735 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7736 diag::err_static_block_func); 7737 break; 7738 } else 7739 return SC_Static; 7740 } 7741 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7742 } 7743 7744 // No explicit storage class has already been returned 7745 return SC_None; 7746 } 7747 7748 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7749 DeclContext *DC, QualType &R, 7750 TypeSourceInfo *TInfo, 7751 StorageClass SC, 7752 bool &IsVirtualOkay) { 7753 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7754 DeclarationName Name = NameInfo.getName(); 7755 7756 FunctionDecl *NewFD = nullptr; 7757 bool isInline = D.getDeclSpec().isInlineSpecified(); 7758 7759 if (!SemaRef.getLangOpts().CPlusPlus) { 7760 // Determine whether the function was written with a 7761 // prototype. This true when: 7762 // - there is a prototype in the declarator, or 7763 // - the type R of the function is some kind of typedef or other non- 7764 // attributed reference to a type name (which eventually refers to a 7765 // function type). 7766 bool HasPrototype = 7767 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7768 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7769 7770 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7771 D.getLocStart(), NameInfo, R, 7772 TInfo, SC, isInline, 7773 HasPrototype, false); 7774 if (D.isInvalidType()) 7775 NewFD->setInvalidDecl(); 7776 7777 return NewFD; 7778 } 7779 7780 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7781 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7782 7783 // Check that the return type is not an abstract class type. 7784 // For record types, this is done by the AbstractClassUsageDiagnoser once 7785 // the class has been completely parsed. 7786 if (!DC->isRecord() && 7787 SemaRef.RequireNonAbstractType( 7788 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7789 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7790 D.setInvalidType(); 7791 7792 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7793 // This is a C++ constructor declaration. 7794 assert(DC->isRecord() && 7795 "Constructors can only be declared in a member context"); 7796 7797 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7798 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7799 D.getLocStart(), NameInfo, 7800 R, TInfo, isExplicit, isInline, 7801 /*isImplicitlyDeclared=*/false, 7802 isConstexpr); 7803 7804 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7805 // This is a C++ destructor declaration. 7806 if (DC->isRecord()) { 7807 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7808 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7809 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7810 SemaRef.Context, Record, 7811 D.getLocStart(), 7812 NameInfo, R, TInfo, isInline, 7813 /*isImplicitlyDeclared=*/false); 7814 7815 // If the class is complete, then we now create the implicit exception 7816 // specification. If the class is incomplete or dependent, we can't do 7817 // it yet. 7818 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7819 Record->getDefinition() && !Record->isBeingDefined() && 7820 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7821 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7822 } 7823 7824 IsVirtualOkay = true; 7825 return NewDD; 7826 7827 } else { 7828 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7829 D.setInvalidType(); 7830 7831 // Create a FunctionDecl to satisfy the function definition parsing 7832 // code path. 7833 return FunctionDecl::Create(SemaRef.Context, DC, 7834 D.getLocStart(), 7835 D.getIdentifierLoc(), Name, R, TInfo, 7836 SC, isInline, 7837 /*hasPrototype=*/true, isConstexpr); 7838 } 7839 7840 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7841 if (!DC->isRecord()) { 7842 SemaRef.Diag(D.getIdentifierLoc(), 7843 diag::err_conv_function_not_member); 7844 return nullptr; 7845 } 7846 7847 SemaRef.CheckConversionDeclarator(D, R, SC); 7848 IsVirtualOkay = true; 7849 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7850 D.getLocStart(), NameInfo, 7851 R, TInfo, isInline, isExplicit, 7852 isConstexpr, SourceLocation()); 7853 7854 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7855 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7856 7857 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7858 isExplicit, NameInfo, R, TInfo, 7859 D.getLocEnd()); 7860 } else if (DC->isRecord()) { 7861 // If the name of the function is the same as the name of the record, 7862 // then this must be an invalid constructor that has a return type. 7863 // (The parser checks for a return type and makes the declarator a 7864 // constructor if it has no return type). 7865 if (Name.getAsIdentifierInfo() && 7866 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7867 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7868 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7869 << SourceRange(D.getIdentifierLoc()); 7870 return nullptr; 7871 } 7872 7873 // This is a C++ method declaration. 7874 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7875 cast<CXXRecordDecl>(DC), 7876 D.getLocStart(), NameInfo, R, 7877 TInfo, SC, isInline, 7878 isConstexpr, SourceLocation()); 7879 IsVirtualOkay = !Ret->isStatic(); 7880 return Ret; 7881 } else { 7882 bool isFriend = 7883 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7884 if (!isFriend && SemaRef.CurContext->isRecord()) 7885 return nullptr; 7886 7887 // Determine whether the function was written with a 7888 // prototype. This true when: 7889 // - we're in C++ (where every function has a prototype), 7890 return FunctionDecl::Create(SemaRef.Context, DC, 7891 D.getLocStart(), 7892 NameInfo, R, TInfo, SC, isInline, 7893 true/*HasPrototype*/, isConstexpr); 7894 } 7895 } 7896 7897 enum OpenCLParamType { 7898 ValidKernelParam, 7899 PtrPtrKernelParam, 7900 PtrKernelParam, 7901 InvalidAddrSpacePtrKernelParam, 7902 InvalidKernelParam, 7903 RecordKernelParam 7904 }; 7905 7906 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7907 if (PT->isPointerType()) { 7908 QualType PointeeType = PT->getPointeeType(); 7909 if (PointeeType->isPointerType()) 7910 return PtrPtrKernelParam; 7911 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7912 PointeeType.getAddressSpace() == 0) 7913 return InvalidAddrSpacePtrKernelParam; 7914 return PtrKernelParam; 7915 } 7916 7917 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7918 // be used as builtin types. 7919 7920 if (PT->isImageType()) 7921 return PtrKernelParam; 7922 7923 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 7924 return InvalidKernelParam; 7925 7926 // OpenCL extension spec v1.2 s9.5: 7927 // This extension adds support for half scalar and vector types as built-in 7928 // types that can be used for arithmetic operations, conversions etc. 7929 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 7930 return InvalidKernelParam; 7931 7932 if (PT->isRecordType()) 7933 return RecordKernelParam; 7934 7935 return ValidKernelParam; 7936 } 7937 7938 static void checkIsValidOpenCLKernelParameter( 7939 Sema &S, 7940 Declarator &D, 7941 ParmVarDecl *Param, 7942 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7943 QualType PT = Param->getType(); 7944 7945 // Cache the valid types we encounter to avoid rechecking structs that are 7946 // used again 7947 if (ValidTypes.count(PT.getTypePtr())) 7948 return; 7949 7950 switch (getOpenCLKernelParameterType(S, PT)) { 7951 case PtrPtrKernelParam: 7952 // OpenCL v1.2 s6.9.a: 7953 // A kernel function argument cannot be declared as a 7954 // pointer to a pointer type. 7955 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7956 D.setInvalidType(); 7957 return; 7958 7959 case InvalidAddrSpacePtrKernelParam: 7960 // OpenCL v1.0 s6.5: 7961 // __kernel function arguments declared to be a pointer of a type can point 7962 // to one of the following address spaces only : __global, __local or 7963 // __constant. 7964 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 7965 D.setInvalidType(); 7966 return; 7967 7968 // OpenCL v1.2 s6.9.k: 7969 // Arguments to kernel functions in a program cannot be declared with the 7970 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7971 // uintptr_t or a struct and/or union that contain fields declared to be 7972 // one of these built-in scalar types. 7973 7974 case InvalidKernelParam: 7975 // OpenCL v1.2 s6.8 n: 7976 // A kernel function argument cannot be declared 7977 // of event_t type. 7978 // Do not diagnose half type since it is diagnosed as invalid argument 7979 // type for any function elsewhere. 7980 if (!PT->isHalfType()) 7981 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7982 D.setInvalidType(); 7983 return; 7984 7985 case PtrKernelParam: 7986 case ValidKernelParam: 7987 ValidTypes.insert(PT.getTypePtr()); 7988 return; 7989 7990 case RecordKernelParam: 7991 break; 7992 } 7993 7994 // Track nested structs we will inspect 7995 SmallVector<const Decl *, 4> VisitStack; 7996 7997 // Track where we are in the nested structs. Items will migrate from 7998 // VisitStack to HistoryStack as we do the DFS for bad field. 7999 SmallVector<const FieldDecl *, 4> HistoryStack; 8000 HistoryStack.push_back(nullptr); 8001 8002 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8003 VisitStack.push_back(PD); 8004 8005 assert(VisitStack.back() && "First decl null?"); 8006 8007 do { 8008 const Decl *Next = VisitStack.pop_back_val(); 8009 if (!Next) { 8010 assert(!HistoryStack.empty()); 8011 // Found a marker, we have gone up a level 8012 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8013 ValidTypes.insert(Hist->getType().getTypePtr()); 8014 8015 continue; 8016 } 8017 8018 // Adds everything except the original parameter declaration (which is not a 8019 // field itself) to the history stack. 8020 const RecordDecl *RD; 8021 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8022 HistoryStack.push_back(Field); 8023 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8024 } else { 8025 RD = cast<RecordDecl>(Next); 8026 } 8027 8028 // Add a null marker so we know when we've gone back up a level 8029 VisitStack.push_back(nullptr); 8030 8031 for (const auto *FD : RD->fields()) { 8032 QualType QT = FD->getType(); 8033 8034 if (ValidTypes.count(QT.getTypePtr())) 8035 continue; 8036 8037 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8038 if (ParamType == ValidKernelParam) 8039 continue; 8040 8041 if (ParamType == RecordKernelParam) { 8042 VisitStack.push_back(FD); 8043 continue; 8044 } 8045 8046 // OpenCL v1.2 s6.9.p: 8047 // Arguments to kernel functions that are declared to be a struct or union 8048 // do not allow OpenCL objects to be passed as elements of the struct or 8049 // union. 8050 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8051 ParamType == InvalidAddrSpacePtrKernelParam) { 8052 S.Diag(Param->getLocation(), 8053 diag::err_record_with_pointers_kernel_param) 8054 << PT->isUnionType() 8055 << PT; 8056 } else { 8057 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8058 } 8059 8060 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8061 << PD->getDeclName(); 8062 8063 // We have an error, now let's go back up through history and show where 8064 // the offending field came from 8065 for (ArrayRef<const FieldDecl *>::const_iterator 8066 I = HistoryStack.begin() + 1, 8067 E = HistoryStack.end(); 8068 I != E; ++I) { 8069 const FieldDecl *OuterField = *I; 8070 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8071 << OuterField->getType(); 8072 } 8073 8074 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8075 << QT->isPointerType() 8076 << QT; 8077 D.setInvalidType(); 8078 return; 8079 } 8080 } while (!VisitStack.empty()); 8081 } 8082 8083 /// Find the DeclContext in which a tag is implicitly declared if we see an 8084 /// elaborated type specifier in the specified context, and lookup finds 8085 /// nothing. 8086 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8087 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8088 DC = DC->getParent(); 8089 return DC; 8090 } 8091 8092 /// Find the Scope in which a tag is implicitly declared if we see an 8093 /// elaborated type specifier in the specified context, and lookup finds 8094 /// nothing. 8095 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8096 while (S->isClassScope() || 8097 (LangOpts.CPlusPlus && 8098 S->isFunctionPrototypeScope()) || 8099 ((S->getFlags() & Scope::DeclScope) == 0) || 8100 (S->getEntity() && S->getEntity()->isTransparentContext())) 8101 S = S->getParent(); 8102 return S; 8103 } 8104 8105 NamedDecl* 8106 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8107 TypeSourceInfo *TInfo, LookupResult &Previous, 8108 MultiTemplateParamsArg TemplateParamLists, 8109 bool &AddToScope) { 8110 QualType R = TInfo->getType(); 8111 8112 assert(R.getTypePtr()->isFunctionType()); 8113 8114 // TODO: consider using NameInfo for diagnostic. 8115 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8116 DeclarationName Name = NameInfo.getName(); 8117 StorageClass SC = getFunctionStorageClass(*this, D); 8118 8119 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8120 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8121 diag::err_invalid_thread) 8122 << DeclSpec::getSpecifierName(TSCS); 8123 8124 if (D.isFirstDeclarationOfMember()) 8125 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8126 D.getIdentifierLoc()); 8127 8128 bool isFriend = false; 8129 FunctionTemplateDecl *FunctionTemplate = nullptr; 8130 bool isMemberSpecialization = false; 8131 bool isFunctionTemplateSpecialization = false; 8132 8133 bool isDependentClassScopeExplicitSpecialization = false; 8134 bool HasExplicitTemplateArgs = false; 8135 TemplateArgumentListInfo TemplateArgs; 8136 8137 bool isVirtualOkay = false; 8138 8139 DeclContext *OriginalDC = DC; 8140 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8141 8142 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8143 isVirtualOkay); 8144 if (!NewFD) return nullptr; 8145 8146 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8147 NewFD->setTopLevelDeclInObjCContainer(); 8148 8149 // Set the lexical context. If this is a function-scope declaration, or has a 8150 // C++ scope specifier, or is the object of a friend declaration, the lexical 8151 // context will be different from the semantic context. 8152 NewFD->setLexicalDeclContext(CurContext); 8153 8154 if (IsLocalExternDecl) 8155 NewFD->setLocalExternDecl(); 8156 8157 if (getLangOpts().CPlusPlus) { 8158 bool isInline = D.getDeclSpec().isInlineSpecified(); 8159 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8160 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8161 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8162 bool isConcept = D.getDeclSpec().isConceptSpecified(); 8163 isFriend = D.getDeclSpec().isFriendSpecified(); 8164 if (isFriend && !isInline && D.isFunctionDefinition()) { 8165 // C++ [class.friend]p5 8166 // A function can be defined in a friend declaration of a 8167 // class . . . . Such a function is implicitly inline. 8168 NewFD->setImplicitlyInline(); 8169 } 8170 8171 // If this is a method defined in an __interface, and is not a constructor 8172 // or an overloaded operator, then set the pure flag (isVirtual will already 8173 // return true). 8174 if (const CXXRecordDecl *Parent = 8175 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8176 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8177 NewFD->setPure(true); 8178 8179 // C++ [class.union]p2 8180 // A union can have member functions, but not virtual functions. 8181 if (isVirtual && Parent->isUnion()) 8182 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8183 } 8184 8185 SetNestedNameSpecifier(NewFD, D); 8186 isMemberSpecialization = false; 8187 isFunctionTemplateSpecialization = false; 8188 if (D.isInvalidType()) 8189 NewFD->setInvalidDecl(); 8190 8191 // Match up the template parameter lists with the scope specifier, then 8192 // determine whether we have a template or a template specialization. 8193 bool Invalid = false; 8194 if (TemplateParameterList *TemplateParams = 8195 MatchTemplateParametersToScopeSpecifier( 8196 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8197 D.getCXXScopeSpec(), 8198 D.getName().getKind() == UnqualifiedId::IK_TemplateId 8199 ? D.getName().TemplateId 8200 : nullptr, 8201 TemplateParamLists, isFriend, isMemberSpecialization, 8202 Invalid)) { 8203 if (TemplateParams->size() > 0) { 8204 // This is a function template 8205 8206 // Check that we can declare a template here. 8207 if (CheckTemplateDeclScope(S, TemplateParams)) 8208 NewFD->setInvalidDecl(); 8209 8210 // A destructor cannot be a template. 8211 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8212 Diag(NewFD->getLocation(), diag::err_destructor_template); 8213 NewFD->setInvalidDecl(); 8214 } 8215 8216 // If we're adding a template to a dependent context, we may need to 8217 // rebuilding some of the types used within the template parameter list, 8218 // now that we know what the current instantiation is. 8219 if (DC->isDependentContext()) { 8220 ContextRAII SavedContext(*this, DC); 8221 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8222 Invalid = true; 8223 } 8224 8225 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8226 NewFD->getLocation(), 8227 Name, TemplateParams, 8228 NewFD); 8229 FunctionTemplate->setLexicalDeclContext(CurContext); 8230 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8231 8232 // For source fidelity, store the other template param lists. 8233 if (TemplateParamLists.size() > 1) { 8234 NewFD->setTemplateParameterListsInfo(Context, 8235 TemplateParamLists.drop_back(1)); 8236 } 8237 } else { 8238 // This is a function template specialization. 8239 isFunctionTemplateSpecialization = true; 8240 // For source fidelity, store all the template param lists. 8241 if (TemplateParamLists.size() > 0) 8242 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8243 8244 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8245 if (isFriend) { 8246 // We want to remove the "template<>", found here. 8247 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8248 8249 // If we remove the template<> and the name is not a 8250 // template-id, we're actually silently creating a problem: 8251 // the friend declaration will refer to an untemplated decl, 8252 // and clearly the user wants a template specialization. So 8253 // we need to insert '<>' after the name. 8254 SourceLocation InsertLoc; 8255 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8256 InsertLoc = D.getName().getSourceRange().getEnd(); 8257 InsertLoc = getLocForEndOfToken(InsertLoc); 8258 } 8259 8260 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8261 << Name << RemoveRange 8262 << FixItHint::CreateRemoval(RemoveRange) 8263 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8264 } 8265 } 8266 } 8267 else { 8268 // All template param lists were matched against the scope specifier: 8269 // this is NOT (an explicit specialization of) a template. 8270 if (TemplateParamLists.size() > 0) 8271 // For source fidelity, store all the template param lists. 8272 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8273 } 8274 8275 if (Invalid) { 8276 NewFD->setInvalidDecl(); 8277 if (FunctionTemplate) 8278 FunctionTemplate->setInvalidDecl(); 8279 } 8280 8281 // C++ [dcl.fct.spec]p5: 8282 // The virtual specifier shall only be used in declarations of 8283 // nonstatic class member functions that appear within a 8284 // member-specification of a class declaration; see 10.3. 8285 // 8286 if (isVirtual && !NewFD->isInvalidDecl()) { 8287 if (!isVirtualOkay) { 8288 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8289 diag::err_virtual_non_function); 8290 } else if (!CurContext->isRecord()) { 8291 // 'virtual' was specified outside of the class. 8292 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8293 diag::err_virtual_out_of_class) 8294 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8295 } else if (NewFD->getDescribedFunctionTemplate()) { 8296 // C++ [temp.mem]p3: 8297 // A member function template shall not be virtual. 8298 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8299 diag::err_virtual_member_function_template) 8300 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8301 } else { 8302 // Okay: Add virtual to the method. 8303 NewFD->setVirtualAsWritten(true); 8304 } 8305 8306 if (getLangOpts().CPlusPlus14 && 8307 NewFD->getReturnType()->isUndeducedType()) 8308 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8309 } 8310 8311 if (getLangOpts().CPlusPlus14 && 8312 (NewFD->isDependentContext() || 8313 (isFriend && CurContext->isDependentContext())) && 8314 NewFD->getReturnType()->isUndeducedType()) { 8315 // If the function template is referenced directly (for instance, as a 8316 // member of the current instantiation), pretend it has a dependent type. 8317 // This is not really justified by the standard, but is the only sane 8318 // thing to do. 8319 // FIXME: For a friend function, we have not marked the function as being 8320 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8321 const FunctionProtoType *FPT = 8322 NewFD->getType()->castAs<FunctionProtoType>(); 8323 QualType Result = 8324 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8325 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8326 FPT->getExtProtoInfo())); 8327 } 8328 8329 // C++ [dcl.fct.spec]p3: 8330 // The inline specifier shall not appear on a block scope function 8331 // declaration. 8332 if (isInline && !NewFD->isInvalidDecl()) { 8333 if (CurContext->isFunctionOrMethod()) { 8334 // 'inline' is not allowed on block scope function declaration. 8335 Diag(D.getDeclSpec().getInlineSpecLoc(), 8336 diag::err_inline_declaration_block_scope) << Name 8337 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8338 } 8339 } 8340 8341 // C++ [dcl.fct.spec]p6: 8342 // The explicit specifier shall be used only in the declaration of a 8343 // constructor or conversion function within its class definition; 8344 // see 12.3.1 and 12.3.2. 8345 if (isExplicit && !NewFD->isInvalidDecl() && 8346 !isa<CXXDeductionGuideDecl>(NewFD)) { 8347 if (!CurContext->isRecord()) { 8348 // 'explicit' was specified outside of the class. 8349 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8350 diag::err_explicit_out_of_class) 8351 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8352 } else if (!isa<CXXConstructorDecl>(NewFD) && 8353 !isa<CXXConversionDecl>(NewFD)) { 8354 // 'explicit' was specified on a function that wasn't a constructor 8355 // or conversion function. 8356 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8357 diag::err_explicit_non_ctor_or_conv_function) 8358 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8359 } 8360 } 8361 8362 if (isConstexpr) { 8363 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8364 // are implicitly inline. 8365 NewFD->setImplicitlyInline(); 8366 8367 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8368 // be either constructors or to return a literal type. Therefore, 8369 // destructors cannot be declared constexpr. 8370 if (isa<CXXDestructorDecl>(NewFD)) 8371 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8372 } 8373 8374 if (isConcept) { 8375 // This is a function concept. 8376 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8377 FTD->setConcept(); 8378 8379 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8380 // applied only to the definition of a function template [...] 8381 if (!D.isFunctionDefinition()) { 8382 Diag(D.getDeclSpec().getConceptSpecLoc(), 8383 diag::err_function_concept_not_defined); 8384 NewFD->setInvalidDecl(); 8385 } 8386 8387 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8388 // have no exception-specification and is treated as if it were specified 8389 // with noexcept(true) (15.4). [...] 8390 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8391 if (FPT->hasExceptionSpec()) { 8392 SourceRange Range; 8393 if (D.isFunctionDeclarator()) 8394 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8395 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8396 << FixItHint::CreateRemoval(Range); 8397 NewFD->setInvalidDecl(); 8398 } else { 8399 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8400 } 8401 8402 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8403 // following restrictions: 8404 // - The declared return type shall have the type bool. 8405 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8406 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8407 NewFD->setInvalidDecl(); 8408 } 8409 8410 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8411 // following restrictions: 8412 // - The declaration's parameter list shall be equivalent to an empty 8413 // parameter list. 8414 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8415 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8416 } 8417 8418 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8419 // implicity defined to be a constexpr declaration (implicitly inline) 8420 NewFD->setImplicitlyInline(); 8421 8422 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8423 // be declared with the thread_local, inline, friend, or constexpr 8424 // specifiers, [...] 8425 if (isInline) { 8426 Diag(D.getDeclSpec().getInlineSpecLoc(), 8427 diag::err_concept_decl_invalid_specifiers) 8428 << 1 << 1; 8429 NewFD->setInvalidDecl(true); 8430 } 8431 8432 if (isFriend) { 8433 Diag(D.getDeclSpec().getFriendSpecLoc(), 8434 diag::err_concept_decl_invalid_specifiers) 8435 << 1 << 2; 8436 NewFD->setInvalidDecl(true); 8437 } 8438 8439 if (isConstexpr) { 8440 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8441 diag::err_concept_decl_invalid_specifiers) 8442 << 1 << 3; 8443 NewFD->setInvalidDecl(true); 8444 } 8445 8446 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8447 // applied only to the definition of a function template or variable 8448 // template, declared in namespace scope. 8449 if (isFunctionTemplateSpecialization) { 8450 Diag(D.getDeclSpec().getConceptSpecLoc(), 8451 diag::err_concept_specified_specialization) << 1; 8452 NewFD->setInvalidDecl(true); 8453 return NewFD; 8454 } 8455 } 8456 8457 // If __module_private__ was specified, mark the function accordingly. 8458 if (D.getDeclSpec().isModulePrivateSpecified()) { 8459 if (isFunctionTemplateSpecialization) { 8460 SourceLocation ModulePrivateLoc 8461 = D.getDeclSpec().getModulePrivateSpecLoc(); 8462 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8463 << 0 8464 << FixItHint::CreateRemoval(ModulePrivateLoc); 8465 } else { 8466 NewFD->setModulePrivate(); 8467 if (FunctionTemplate) 8468 FunctionTemplate->setModulePrivate(); 8469 } 8470 } 8471 8472 if (isFriend) { 8473 if (FunctionTemplate) { 8474 FunctionTemplate->setObjectOfFriendDecl(); 8475 FunctionTemplate->setAccess(AS_public); 8476 } 8477 NewFD->setObjectOfFriendDecl(); 8478 NewFD->setAccess(AS_public); 8479 } 8480 8481 // If a function is defined as defaulted or deleted, mark it as such now. 8482 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8483 // definition kind to FDK_Definition. 8484 switch (D.getFunctionDefinitionKind()) { 8485 case FDK_Declaration: 8486 case FDK_Definition: 8487 break; 8488 8489 case FDK_Defaulted: 8490 NewFD->setDefaulted(); 8491 break; 8492 8493 case FDK_Deleted: 8494 NewFD->setDeletedAsWritten(); 8495 break; 8496 } 8497 8498 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8499 D.isFunctionDefinition()) { 8500 // C++ [class.mfct]p2: 8501 // A member function may be defined (8.4) in its class definition, in 8502 // which case it is an inline member function (7.1.2) 8503 NewFD->setImplicitlyInline(); 8504 } 8505 8506 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8507 !CurContext->isRecord()) { 8508 // C++ [class.static]p1: 8509 // A data or function member of a class may be declared static 8510 // in a class definition, in which case it is a static member of 8511 // the class. 8512 8513 // Complain about the 'static' specifier if it's on an out-of-line 8514 // member function definition. 8515 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8516 diag::err_static_out_of_line) 8517 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8518 } 8519 8520 // C++11 [except.spec]p15: 8521 // A deallocation function with no exception-specification is treated 8522 // as if it were specified with noexcept(true). 8523 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8524 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8525 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8526 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8527 NewFD->setType(Context.getFunctionType( 8528 FPT->getReturnType(), FPT->getParamTypes(), 8529 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8530 } 8531 8532 // Filter out previous declarations that don't match the scope. 8533 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8534 D.getCXXScopeSpec().isNotEmpty() || 8535 isMemberSpecialization || 8536 isFunctionTemplateSpecialization); 8537 8538 // Handle GNU asm-label extension (encoded as an attribute). 8539 if (Expr *E = (Expr*) D.getAsmLabel()) { 8540 // The parser guarantees this is a string. 8541 StringLiteral *SE = cast<StringLiteral>(E); 8542 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8543 SE->getString(), 0)); 8544 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8545 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8546 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8547 if (I != ExtnameUndeclaredIdentifiers.end()) { 8548 if (isDeclExternC(NewFD)) { 8549 NewFD->addAttr(I->second); 8550 ExtnameUndeclaredIdentifiers.erase(I); 8551 } else 8552 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8553 << /*Variable*/0 << NewFD; 8554 } 8555 } 8556 8557 // Copy the parameter declarations from the declarator D to the function 8558 // declaration NewFD, if they are available. First scavenge them into Params. 8559 SmallVector<ParmVarDecl*, 16> Params; 8560 unsigned FTIIdx; 8561 if (D.isFunctionDeclarator(FTIIdx)) { 8562 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8563 8564 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8565 // function that takes no arguments, not a function that takes a 8566 // single void argument. 8567 // We let through "const void" here because Sema::GetTypeForDeclarator 8568 // already checks for that case. 8569 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8570 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8571 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8572 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8573 Param->setDeclContext(NewFD); 8574 Params.push_back(Param); 8575 8576 if (Param->isInvalidDecl()) 8577 NewFD->setInvalidDecl(); 8578 } 8579 } 8580 8581 if (!getLangOpts().CPlusPlus) { 8582 // In C, find all the tag declarations from the prototype and move them 8583 // into the function DeclContext. Remove them from the surrounding tag 8584 // injection context of the function, which is typically but not always 8585 // the TU. 8586 DeclContext *PrototypeTagContext = 8587 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8588 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8589 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8590 8591 // We don't want to reparent enumerators. Look at their parent enum 8592 // instead. 8593 if (!TD) { 8594 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8595 TD = cast<EnumDecl>(ECD->getDeclContext()); 8596 } 8597 if (!TD) 8598 continue; 8599 DeclContext *TagDC = TD->getLexicalDeclContext(); 8600 if (!TagDC->containsDecl(TD)) 8601 continue; 8602 TagDC->removeDecl(TD); 8603 TD->setDeclContext(NewFD); 8604 NewFD->addDecl(TD); 8605 8606 // Preserve the lexical DeclContext if it is not the surrounding tag 8607 // injection context of the FD. In this example, the semantic context of 8608 // E will be f and the lexical context will be S, while both the 8609 // semantic and lexical contexts of S will be f: 8610 // void f(struct S { enum E { a } f; } s); 8611 if (TagDC != PrototypeTagContext) 8612 TD->setLexicalDeclContext(TagDC); 8613 } 8614 } 8615 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8616 // When we're declaring a function with a typedef, typeof, etc as in the 8617 // following example, we'll need to synthesize (unnamed) 8618 // parameters for use in the declaration. 8619 // 8620 // @code 8621 // typedef void fn(int); 8622 // fn f; 8623 // @endcode 8624 8625 // Synthesize a parameter for each argument type. 8626 for (const auto &AI : FT->param_types()) { 8627 ParmVarDecl *Param = 8628 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8629 Param->setScopeInfo(0, Params.size()); 8630 Params.push_back(Param); 8631 } 8632 } else { 8633 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8634 "Should not need args for typedef of non-prototype fn"); 8635 } 8636 8637 // Finally, we know we have the right number of parameters, install them. 8638 NewFD->setParams(Params); 8639 8640 if (D.getDeclSpec().isNoreturnSpecified()) 8641 NewFD->addAttr( 8642 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8643 Context, 0)); 8644 8645 // Functions returning a variably modified type violate C99 6.7.5.2p2 8646 // because all functions have linkage. 8647 if (!NewFD->isInvalidDecl() && 8648 NewFD->getReturnType()->isVariablyModifiedType()) { 8649 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8650 NewFD->setInvalidDecl(); 8651 } 8652 8653 // Apply an implicit SectionAttr if #pragma code_seg is active. 8654 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8655 !NewFD->hasAttr<SectionAttr>()) { 8656 NewFD->addAttr( 8657 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8658 CodeSegStack.CurrentValue->getString(), 8659 CodeSegStack.CurrentPragmaLocation)); 8660 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8661 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8662 ASTContext::PSF_Read, 8663 NewFD)) 8664 NewFD->dropAttr<SectionAttr>(); 8665 } 8666 8667 // Handle attributes. 8668 ProcessDeclAttributes(S, NewFD, D); 8669 8670 if (getLangOpts().OpenCL) { 8671 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8672 // type declaration will generate a compilation error. 8673 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8674 if (AddressSpace == LangAS::opencl_local || 8675 AddressSpace == LangAS::opencl_global || 8676 AddressSpace == LangAS::opencl_constant) { 8677 Diag(NewFD->getLocation(), 8678 diag::err_opencl_return_value_with_address_space); 8679 NewFD->setInvalidDecl(); 8680 } 8681 } 8682 8683 if (!getLangOpts().CPlusPlus) { 8684 // Perform semantic checking on the function declaration. 8685 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8686 CheckMain(NewFD, D.getDeclSpec()); 8687 8688 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8689 CheckMSVCRTEntryPoint(NewFD); 8690 8691 if (!NewFD->isInvalidDecl()) 8692 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8693 isMemberSpecialization)); 8694 else if (!Previous.empty()) 8695 // Recover gracefully from an invalid redeclaration. 8696 D.setRedeclaration(true); 8697 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8698 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8699 "previous declaration set still overloaded"); 8700 8701 // Diagnose no-prototype function declarations with calling conventions that 8702 // don't support variadic calls. Only do this in C and do it after merging 8703 // possibly prototyped redeclarations. 8704 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8705 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8706 CallingConv CC = FT->getExtInfo().getCC(); 8707 if (!supportsVariadicCall(CC)) { 8708 // Windows system headers sometimes accidentally use stdcall without 8709 // (void) parameters, so we relax this to a warning. 8710 int DiagID = 8711 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8712 Diag(NewFD->getLocation(), DiagID) 8713 << FunctionType::getNameForCallConv(CC); 8714 } 8715 } 8716 } else { 8717 // C++11 [replacement.functions]p3: 8718 // The program's definitions shall not be specified as inline. 8719 // 8720 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8721 // 8722 // Suppress the diagnostic if the function is __attribute__((used)), since 8723 // that forces an external definition to be emitted. 8724 if (D.getDeclSpec().isInlineSpecified() && 8725 NewFD->isReplaceableGlobalAllocationFunction() && 8726 !NewFD->hasAttr<UsedAttr>()) 8727 Diag(D.getDeclSpec().getInlineSpecLoc(), 8728 diag::ext_operator_new_delete_declared_inline) 8729 << NewFD->getDeclName(); 8730 8731 // If the declarator is a template-id, translate the parser's template 8732 // argument list into our AST format. 8733 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8734 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8735 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8736 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8737 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8738 TemplateId->NumArgs); 8739 translateTemplateArguments(TemplateArgsPtr, 8740 TemplateArgs); 8741 8742 HasExplicitTemplateArgs = true; 8743 8744 if (NewFD->isInvalidDecl()) { 8745 HasExplicitTemplateArgs = false; 8746 } else if (FunctionTemplate) { 8747 // Function template with explicit template arguments. 8748 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8749 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8750 8751 HasExplicitTemplateArgs = false; 8752 } else { 8753 assert((isFunctionTemplateSpecialization || 8754 D.getDeclSpec().isFriendSpecified()) && 8755 "should have a 'template<>' for this decl"); 8756 // "friend void foo<>(int);" is an implicit specialization decl. 8757 isFunctionTemplateSpecialization = true; 8758 } 8759 } else if (isFriend && isFunctionTemplateSpecialization) { 8760 // This combination is only possible in a recovery case; the user 8761 // wrote something like: 8762 // template <> friend void foo(int); 8763 // which we're recovering from as if the user had written: 8764 // friend void foo<>(int); 8765 // Go ahead and fake up a template id. 8766 HasExplicitTemplateArgs = true; 8767 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8768 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8769 } 8770 8771 // We do not add HD attributes to specializations here because 8772 // they may have different constexpr-ness compared to their 8773 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8774 // may end up with different effective targets. Instead, a 8775 // specialization inherits its target attributes from its template 8776 // in the CheckFunctionTemplateSpecialization() call below. 8777 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8778 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8779 8780 // If it's a friend (and only if it's a friend), it's possible 8781 // that either the specialized function type or the specialized 8782 // template is dependent, and therefore matching will fail. In 8783 // this case, don't check the specialization yet. 8784 bool InstantiationDependent = false; 8785 if (isFunctionTemplateSpecialization && isFriend && 8786 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8787 TemplateSpecializationType::anyDependentTemplateArguments( 8788 TemplateArgs, 8789 InstantiationDependent))) { 8790 assert(HasExplicitTemplateArgs && 8791 "friend function specialization without template args"); 8792 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8793 Previous)) 8794 NewFD->setInvalidDecl(); 8795 } else if (isFunctionTemplateSpecialization) { 8796 if (CurContext->isDependentContext() && CurContext->isRecord() 8797 && !isFriend) { 8798 isDependentClassScopeExplicitSpecialization = true; 8799 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8800 diag::ext_function_specialization_in_class : 8801 diag::err_function_specialization_in_class) 8802 << NewFD->getDeclName(); 8803 } else if (CheckFunctionTemplateSpecialization(NewFD, 8804 (HasExplicitTemplateArgs ? &TemplateArgs 8805 : nullptr), 8806 Previous)) 8807 NewFD->setInvalidDecl(); 8808 8809 // C++ [dcl.stc]p1: 8810 // A storage-class-specifier shall not be specified in an explicit 8811 // specialization (14.7.3) 8812 FunctionTemplateSpecializationInfo *Info = 8813 NewFD->getTemplateSpecializationInfo(); 8814 if (Info && SC != SC_None) { 8815 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8816 Diag(NewFD->getLocation(), 8817 diag::err_explicit_specialization_inconsistent_storage_class) 8818 << SC 8819 << FixItHint::CreateRemoval( 8820 D.getDeclSpec().getStorageClassSpecLoc()); 8821 8822 else 8823 Diag(NewFD->getLocation(), 8824 diag::ext_explicit_specialization_storage_class) 8825 << FixItHint::CreateRemoval( 8826 D.getDeclSpec().getStorageClassSpecLoc()); 8827 } 8828 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8829 if (CheckMemberSpecialization(NewFD, Previous)) 8830 NewFD->setInvalidDecl(); 8831 } 8832 8833 // Perform semantic checking on the function declaration. 8834 if (!isDependentClassScopeExplicitSpecialization) { 8835 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8836 CheckMain(NewFD, D.getDeclSpec()); 8837 8838 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8839 CheckMSVCRTEntryPoint(NewFD); 8840 8841 if (!NewFD->isInvalidDecl()) 8842 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8843 isMemberSpecialization)); 8844 else if (!Previous.empty()) 8845 // Recover gracefully from an invalid redeclaration. 8846 D.setRedeclaration(true); 8847 } 8848 8849 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8850 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8851 "previous declaration set still overloaded"); 8852 8853 NamedDecl *PrincipalDecl = (FunctionTemplate 8854 ? cast<NamedDecl>(FunctionTemplate) 8855 : NewFD); 8856 8857 if (isFriend && NewFD->getPreviousDecl()) { 8858 AccessSpecifier Access = AS_public; 8859 if (!NewFD->isInvalidDecl()) 8860 Access = NewFD->getPreviousDecl()->getAccess(); 8861 8862 NewFD->setAccess(Access); 8863 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8864 } 8865 8866 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8867 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8868 PrincipalDecl->setNonMemberOperator(); 8869 8870 // If we have a function template, check the template parameter 8871 // list. This will check and merge default template arguments. 8872 if (FunctionTemplate) { 8873 FunctionTemplateDecl *PrevTemplate = 8874 FunctionTemplate->getPreviousDecl(); 8875 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8876 PrevTemplate ? PrevTemplate->getTemplateParameters() 8877 : nullptr, 8878 D.getDeclSpec().isFriendSpecified() 8879 ? (D.isFunctionDefinition() 8880 ? TPC_FriendFunctionTemplateDefinition 8881 : TPC_FriendFunctionTemplate) 8882 : (D.getCXXScopeSpec().isSet() && 8883 DC && DC->isRecord() && 8884 DC->isDependentContext()) 8885 ? TPC_ClassTemplateMember 8886 : TPC_FunctionTemplate); 8887 } 8888 8889 if (NewFD->isInvalidDecl()) { 8890 // Ignore all the rest of this. 8891 } else if (!D.isRedeclaration()) { 8892 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8893 AddToScope }; 8894 // Fake up an access specifier if it's supposed to be a class member. 8895 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8896 NewFD->setAccess(AS_public); 8897 8898 // Qualified decls generally require a previous declaration. 8899 if (D.getCXXScopeSpec().isSet()) { 8900 // ...with the major exception of templated-scope or 8901 // dependent-scope friend declarations. 8902 8903 // TODO: we currently also suppress this check in dependent 8904 // contexts because (1) the parameter depth will be off when 8905 // matching friend templates and (2) we might actually be 8906 // selecting a friend based on a dependent factor. But there 8907 // are situations where these conditions don't apply and we 8908 // can actually do this check immediately. 8909 if (isFriend && 8910 (TemplateParamLists.size() || 8911 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8912 CurContext->isDependentContext())) { 8913 // ignore these 8914 } else { 8915 // The user tried to provide an out-of-line definition for a 8916 // function that is a member of a class or namespace, but there 8917 // was no such member function declared (C++ [class.mfct]p2, 8918 // C++ [namespace.memdef]p2). For example: 8919 // 8920 // class X { 8921 // void f() const; 8922 // }; 8923 // 8924 // void X::f() { } // ill-formed 8925 // 8926 // Complain about this problem, and attempt to suggest close 8927 // matches (e.g., those that differ only in cv-qualifiers and 8928 // whether the parameter types are references). 8929 8930 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8931 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8932 AddToScope = ExtraArgs.AddToScope; 8933 return Result; 8934 } 8935 } 8936 8937 // Unqualified local friend declarations are required to resolve 8938 // to something. 8939 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8940 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8941 *this, Previous, NewFD, ExtraArgs, true, S)) { 8942 AddToScope = ExtraArgs.AddToScope; 8943 return Result; 8944 } 8945 } 8946 } else if (!D.isFunctionDefinition() && 8947 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8948 !isFriend && !isFunctionTemplateSpecialization && 8949 !isMemberSpecialization) { 8950 // An out-of-line member function declaration must also be a 8951 // definition (C++ [class.mfct]p2). 8952 // Note that this is not the case for explicit specializations of 8953 // function templates or member functions of class templates, per 8954 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8955 // extension for compatibility with old SWIG code which likes to 8956 // generate them. 8957 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8958 << D.getCXXScopeSpec().getRange(); 8959 } 8960 } 8961 8962 ProcessPragmaWeak(S, NewFD); 8963 checkAttributesAfterMerging(*this, *NewFD); 8964 8965 AddKnownFunctionAttributes(NewFD); 8966 8967 if (NewFD->hasAttr<OverloadableAttr>() && 8968 !NewFD->getType()->getAs<FunctionProtoType>()) { 8969 Diag(NewFD->getLocation(), 8970 diag::err_attribute_overloadable_no_prototype) 8971 << NewFD; 8972 8973 // Turn this into a variadic function with no parameters. 8974 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8975 FunctionProtoType::ExtProtoInfo EPI( 8976 Context.getDefaultCallingConvention(true, false)); 8977 EPI.Variadic = true; 8978 EPI.ExtInfo = FT->getExtInfo(); 8979 8980 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8981 NewFD->setType(R); 8982 } 8983 8984 // If there's a #pragma GCC visibility in scope, and this isn't a class 8985 // member, set the visibility of this function. 8986 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8987 AddPushedVisibilityAttribute(NewFD); 8988 8989 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8990 // marking the function. 8991 AddCFAuditedAttribute(NewFD); 8992 8993 // If this is a function definition, check if we have to apply optnone due to 8994 // a pragma. 8995 if(D.isFunctionDefinition()) 8996 AddRangeBasedOptnone(NewFD); 8997 8998 // If this is the first declaration of an extern C variable, update 8999 // the map of such variables. 9000 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9001 isIncompleteDeclExternC(*this, NewFD)) 9002 RegisterLocallyScopedExternCDecl(NewFD, S); 9003 9004 // Set this FunctionDecl's range up to the right paren. 9005 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9006 9007 if (D.isRedeclaration() && !Previous.empty()) { 9008 checkDLLAttributeRedeclaration( 9009 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 9010 isMemberSpecialization || isFunctionTemplateSpecialization, 9011 D.isFunctionDefinition()); 9012 } 9013 9014 if (getLangOpts().CUDA) { 9015 IdentifierInfo *II = NewFD->getIdentifier(); 9016 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 9017 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9018 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9019 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9020 9021 Context.setcudaConfigureCallDecl(NewFD); 9022 } 9023 9024 // Variadic functions, other than a *declaration* of printf, are not allowed 9025 // in device-side CUDA code, unless someone passed 9026 // -fcuda-allow-variadic-functions. 9027 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9028 (NewFD->hasAttr<CUDADeviceAttr>() || 9029 NewFD->hasAttr<CUDAGlobalAttr>()) && 9030 !(II && II->isStr("printf") && NewFD->isExternC() && 9031 !D.isFunctionDefinition())) { 9032 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9033 } 9034 } 9035 9036 MarkUnusedFileScopedDecl(NewFD); 9037 9038 if (getLangOpts().CPlusPlus) { 9039 if (FunctionTemplate) { 9040 if (NewFD->isInvalidDecl()) 9041 FunctionTemplate->setInvalidDecl(); 9042 return FunctionTemplate; 9043 } 9044 9045 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9046 CompleteMemberSpecialization(NewFD, Previous); 9047 } 9048 9049 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9050 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9051 if ((getLangOpts().OpenCLVersion >= 120) 9052 && (SC == SC_Static)) { 9053 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9054 D.setInvalidType(); 9055 } 9056 9057 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9058 if (!NewFD->getReturnType()->isVoidType()) { 9059 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9060 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9061 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9062 : FixItHint()); 9063 D.setInvalidType(); 9064 } 9065 9066 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9067 for (auto Param : NewFD->parameters()) 9068 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9069 } 9070 for (const ParmVarDecl *Param : NewFD->parameters()) { 9071 QualType PT = Param->getType(); 9072 9073 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9074 // types. 9075 if (getLangOpts().OpenCLVersion >= 200) { 9076 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9077 QualType ElemTy = PipeTy->getElementType(); 9078 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9079 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9080 D.setInvalidType(); 9081 } 9082 } 9083 } 9084 } 9085 9086 // Here we have an function template explicit specialization at class scope. 9087 // The actually specialization will be postponed to template instatiation 9088 // time via the ClassScopeFunctionSpecializationDecl node. 9089 if (isDependentClassScopeExplicitSpecialization) { 9090 ClassScopeFunctionSpecializationDecl *NewSpec = 9091 ClassScopeFunctionSpecializationDecl::Create( 9092 Context, CurContext, SourceLocation(), 9093 cast<CXXMethodDecl>(NewFD), 9094 HasExplicitTemplateArgs, TemplateArgs); 9095 CurContext->addDecl(NewSpec); 9096 AddToScope = false; 9097 } 9098 9099 return NewFD; 9100 } 9101 9102 /// \brief Checks if the new declaration declared in dependent context must be 9103 /// put in the same redeclaration chain as the specified declaration. 9104 /// 9105 /// \param D Declaration that is checked. 9106 /// \param PrevDecl Previous declaration found with proper lookup method for the 9107 /// same declaration name. 9108 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9109 /// belongs to. 9110 /// 9111 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9112 // Any declarations should be put into redeclaration chains except for 9113 // friend declaration in a dependent context that names a function in 9114 // namespace scope. 9115 // 9116 // This allows to compile code like: 9117 // 9118 // void func(); 9119 // template<typename T> class C1 { friend void func() { } }; 9120 // template<typename T> class C2 { friend void func() { } }; 9121 // 9122 // This code snippet is a valid code unless both templates are instantiated. 9123 return !(D->getLexicalDeclContext()->isDependentContext() && 9124 D->getDeclContext()->isFileContext() && 9125 D->getFriendObjectKind() != Decl::FOK_None); 9126 } 9127 9128 /// \brief Perform semantic checking of a new function declaration. 9129 /// 9130 /// Performs semantic analysis of the new function declaration 9131 /// NewFD. This routine performs all semantic checking that does not 9132 /// require the actual declarator involved in the declaration, and is 9133 /// used both for the declaration of functions as they are parsed 9134 /// (called via ActOnDeclarator) and for the declaration of functions 9135 /// that have been instantiated via C++ template instantiation (called 9136 /// via InstantiateDecl). 9137 /// 9138 /// \param IsMemberSpecialization whether this new function declaration is 9139 /// a member specialization (that replaces any definition provided by the 9140 /// previous declaration). 9141 /// 9142 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9143 /// 9144 /// \returns true if the function declaration is a redeclaration. 9145 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9146 LookupResult &Previous, 9147 bool IsMemberSpecialization) { 9148 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9149 "Variably modified return types are not handled here"); 9150 9151 // Determine whether the type of this function should be merged with 9152 // a previous visible declaration. This never happens for functions in C++, 9153 // and always happens in C if the previous declaration was visible. 9154 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9155 !Previous.isShadowed(); 9156 9157 bool Redeclaration = false; 9158 NamedDecl *OldDecl = nullptr; 9159 9160 // Merge or overload the declaration with an existing declaration of 9161 // the same name, if appropriate. 9162 if (!Previous.empty()) { 9163 // Determine whether NewFD is an overload of PrevDecl or 9164 // a declaration that requires merging. If it's an overload, 9165 // there's no more work to do here; we'll just add the new 9166 // function to the scope. 9167 if (!AllowOverloadingOfFunction(Previous, Context)) { 9168 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9169 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9170 Redeclaration = true; 9171 OldDecl = Candidate; 9172 } 9173 } else { 9174 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9175 /*NewIsUsingDecl*/ false)) { 9176 case Ovl_Match: 9177 Redeclaration = true; 9178 break; 9179 9180 case Ovl_NonFunction: 9181 Redeclaration = true; 9182 break; 9183 9184 case Ovl_Overload: 9185 Redeclaration = false; 9186 break; 9187 } 9188 9189 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 9190 // If a function name is overloadable in C, then every function 9191 // with that name must be marked "overloadable". 9192 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 9193 << Redeclaration << NewFD; 9194 NamedDecl *OverloadedDecl = 9195 Redeclaration ? OldDecl : Previous.getRepresentativeDecl(); 9196 Diag(OverloadedDecl->getLocation(), 9197 diag::note_attribute_overloadable_prev_overload); 9198 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9199 } 9200 } 9201 } 9202 9203 // Check for a previous extern "C" declaration with this name. 9204 if (!Redeclaration && 9205 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9206 if (!Previous.empty()) { 9207 // This is an extern "C" declaration with the same name as a previous 9208 // declaration, and thus redeclares that entity... 9209 Redeclaration = true; 9210 OldDecl = Previous.getFoundDecl(); 9211 MergeTypeWithPrevious = false; 9212 9213 // ... except in the presence of __attribute__((overloadable)). 9214 if (OldDecl->hasAttr<OverloadableAttr>()) { 9215 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 9216 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 9217 << Redeclaration << NewFD; 9218 Diag(Previous.getFoundDecl()->getLocation(), 9219 diag::note_attribute_overloadable_prev_overload); 9220 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9221 } 9222 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9223 Redeclaration = false; 9224 OldDecl = nullptr; 9225 } 9226 } 9227 } 9228 } 9229 9230 // C++11 [dcl.constexpr]p8: 9231 // A constexpr specifier for a non-static member function that is not 9232 // a constructor declares that member function to be const. 9233 // 9234 // This needs to be delayed until we know whether this is an out-of-line 9235 // definition of a static member function. 9236 // 9237 // This rule is not present in C++1y, so we produce a backwards 9238 // compatibility warning whenever it happens in C++11. 9239 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9240 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9241 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9242 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9243 CXXMethodDecl *OldMD = nullptr; 9244 if (OldDecl) 9245 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9246 if (!OldMD || !OldMD->isStatic()) { 9247 const FunctionProtoType *FPT = 9248 MD->getType()->castAs<FunctionProtoType>(); 9249 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9250 EPI.TypeQuals |= Qualifiers::Const; 9251 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9252 FPT->getParamTypes(), EPI)); 9253 9254 // Warn that we did this, if we're not performing template instantiation. 9255 // In that case, we'll have warned already when the template was defined. 9256 if (!inTemplateInstantiation()) { 9257 SourceLocation AddConstLoc; 9258 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9259 .IgnoreParens().getAs<FunctionTypeLoc>()) 9260 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9261 9262 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9263 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9264 } 9265 } 9266 } 9267 9268 if (Redeclaration) { 9269 // NewFD and OldDecl represent declarations that need to be 9270 // merged. 9271 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9272 NewFD->setInvalidDecl(); 9273 return Redeclaration; 9274 } 9275 9276 Previous.clear(); 9277 Previous.addDecl(OldDecl); 9278 9279 if (FunctionTemplateDecl *OldTemplateDecl 9280 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9281 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9282 FunctionTemplateDecl *NewTemplateDecl 9283 = NewFD->getDescribedFunctionTemplate(); 9284 assert(NewTemplateDecl && "Template/non-template mismatch"); 9285 if (CXXMethodDecl *Method 9286 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9287 Method->setAccess(OldTemplateDecl->getAccess()); 9288 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9289 } 9290 9291 // If this is an explicit specialization of a member that is a function 9292 // template, mark it as a member specialization. 9293 if (IsMemberSpecialization && 9294 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9295 NewTemplateDecl->setMemberSpecialization(); 9296 assert(OldTemplateDecl->isMemberSpecialization()); 9297 // Explicit specializations of a member template do not inherit deleted 9298 // status from the parent member template that they are specializing. 9299 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9300 FunctionDecl *const OldTemplatedDecl = 9301 OldTemplateDecl->getTemplatedDecl(); 9302 // FIXME: This assert will not hold in the presence of modules. 9303 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9304 // FIXME: We need an update record for this AST mutation. 9305 OldTemplatedDecl->setDeletedAsWritten(false); 9306 } 9307 } 9308 9309 } else { 9310 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9311 // This needs to happen first so that 'inline' propagates. 9312 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9313 if (isa<CXXMethodDecl>(NewFD)) 9314 NewFD->setAccess(OldDecl->getAccess()); 9315 } 9316 } 9317 } 9318 9319 // Semantic checking for this function declaration (in isolation). 9320 9321 if (getLangOpts().CPlusPlus) { 9322 // C++-specific checks. 9323 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9324 CheckConstructor(Constructor); 9325 } else if (CXXDestructorDecl *Destructor = 9326 dyn_cast<CXXDestructorDecl>(NewFD)) { 9327 CXXRecordDecl *Record = Destructor->getParent(); 9328 QualType ClassType = Context.getTypeDeclType(Record); 9329 9330 // FIXME: Shouldn't we be able to perform this check even when the class 9331 // type is dependent? Both gcc and edg can handle that. 9332 if (!ClassType->isDependentType()) { 9333 DeclarationName Name 9334 = Context.DeclarationNames.getCXXDestructorName( 9335 Context.getCanonicalType(ClassType)); 9336 if (NewFD->getDeclName() != Name) { 9337 Diag(NewFD->getLocation(), diag::err_destructor_name); 9338 NewFD->setInvalidDecl(); 9339 return Redeclaration; 9340 } 9341 } 9342 } else if (CXXConversionDecl *Conversion 9343 = dyn_cast<CXXConversionDecl>(NewFD)) { 9344 ActOnConversionDeclarator(Conversion); 9345 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9346 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9347 CheckDeductionGuideTemplate(TD); 9348 9349 // A deduction guide is not on the list of entities that can be 9350 // explicitly specialized. 9351 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9352 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9353 << /*explicit specialization*/ 1; 9354 } 9355 9356 // Find any virtual functions that this function overrides. 9357 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9358 if (!Method->isFunctionTemplateSpecialization() && 9359 !Method->getDescribedFunctionTemplate() && 9360 Method->isCanonicalDecl()) { 9361 if (AddOverriddenMethods(Method->getParent(), Method)) { 9362 // If the function was marked as "static", we have a problem. 9363 if (NewFD->getStorageClass() == SC_Static) { 9364 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9365 } 9366 } 9367 } 9368 9369 if (Method->isStatic()) 9370 checkThisInStaticMemberFunctionType(Method); 9371 } 9372 9373 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9374 if (NewFD->isOverloadedOperator() && 9375 CheckOverloadedOperatorDeclaration(NewFD)) { 9376 NewFD->setInvalidDecl(); 9377 return Redeclaration; 9378 } 9379 9380 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9381 if (NewFD->getLiteralIdentifier() && 9382 CheckLiteralOperatorDeclaration(NewFD)) { 9383 NewFD->setInvalidDecl(); 9384 return Redeclaration; 9385 } 9386 9387 // In C++, check default arguments now that we have merged decls. Unless 9388 // the lexical context is the class, because in this case this is done 9389 // during delayed parsing anyway. 9390 if (!CurContext->isRecord()) 9391 CheckCXXDefaultArguments(NewFD); 9392 9393 // If this function declares a builtin function, check the type of this 9394 // declaration against the expected type for the builtin. 9395 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9396 ASTContext::GetBuiltinTypeError Error; 9397 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9398 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9399 // If the type of the builtin differs only in its exception 9400 // specification, that's OK. 9401 // FIXME: If the types do differ in this way, it would be better to 9402 // retain the 'noexcept' form of the type. 9403 if (!T.isNull() && 9404 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9405 NewFD->getType())) 9406 // The type of this function differs from the type of the builtin, 9407 // so forget about the builtin entirely. 9408 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9409 } 9410 9411 // If this function is declared as being extern "C", then check to see if 9412 // the function returns a UDT (class, struct, or union type) that is not C 9413 // compatible, and if it does, warn the user. 9414 // But, issue any diagnostic on the first declaration only. 9415 if (Previous.empty() && NewFD->isExternC()) { 9416 QualType R = NewFD->getReturnType(); 9417 if (R->isIncompleteType() && !R->isVoidType()) 9418 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9419 << NewFD << R; 9420 else if (!R.isPODType(Context) && !R->isVoidType() && 9421 !R->isObjCObjectPointerType()) 9422 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9423 } 9424 9425 // C++1z [dcl.fct]p6: 9426 // [...] whether the function has a non-throwing exception-specification 9427 // [is] part of the function type 9428 // 9429 // This results in an ABI break between C++14 and C++17 for functions whose 9430 // declared type includes an exception-specification in a parameter or 9431 // return type. (Exception specifications on the function itself are OK in 9432 // most cases, and exception specifications are not permitted in most other 9433 // contexts where they could make it into a mangling.) 9434 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9435 auto HasNoexcept = [&](QualType T) -> bool { 9436 // Strip off declarator chunks that could be between us and a function 9437 // type. We don't need to look far, exception specifications are very 9438 // restricted prior to C++17. 9439 if (auto *RT = T->getAs<ReferenceType>()) 9440 T = RT->getPointeeType(); 9441 else if (T->isAnyPointerType()) 9442 T = T->getPointeeType(); 9443 else if (auto *MPT = T->getAs<MemberPointerType>()) 9444 T = MPT->getPointeeType(); 9445 if (auto *FPT = T->getAs<FunctionProtoType>()) 9446 if (FPT->isNothrow(Context)) 9447 return true; 9448 return false; 9449 }; 9450 9451 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9452 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9453 for (QualType T : FPT->param_types()) 9454 AnyNoexcept |= HasNoexcept(T); 9455 if (AnyNoexcept) 9456 Diag(NewFD->getLocation(), 9457 diag::warn_cxx1z_compat_exception_spec_in_signature) 9458 << NewFD; 9459 } 9460 9461 if (!Redeclaration && LangOpts.CUDA) 9462 checkCUDATargetOverload(NewFD, Previous); 9463 } 9464 return Redeclaration; 9465 } 9466 9467 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9468 // C++11 [basic.start.main]p3: 9469 // A program that [...] declares main to be inline, static or 9470 // constexpr is ill-formed. 9471 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9472 // appear in a declaration of main. 9473 // static main is not an error under C99, but we should warn about it. 9474 // We accept _Noreturn main as an extension. 9475 if (FD->getStorageClass() == SC_Static) 9476 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9477 ? diag::err_static_main : diag::warn_static_main) 9478 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9479 if (FD->isInlineSpecified()) 9480 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9481 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9482 if (DS.isNoreturnSpecified()) { 9483 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9484 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9485 Diag(NoreturnLoc, diag::ext_noreturn_main); 9486 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9487 << FixItHint::CreateRemoval(NoreturnRange); 9488 } 9489 if (FD->isConstexpr()) { 9490 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9491 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9492 FD->setConstexpr(false); 9493 } 9494 9495 if (getLangOpts().OpenCL) { 9496 Diag(FD->getLocation(), diag::err_opencl_no_main) 9497 << FD->hasAttr<OpenCLKernelAttr>(); 9498 FD->setInvalidDecl(); 9499 return; 9500 } 9501 9502 QualType T = FD->getType(); 9503 assert(T->isFunctionType() && "function decl is not of function type"); 9504 const FunctionType* FT = T->castAs<FunctionType>(); 9505 9506 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9507 // In C with GNU extensions we allow main() to have non-integer return 9508 // type, but we should warn about the extension, and we disable the 9509 // implicit-return-zero rule. 9510 9511 // GCC in C mode accepts qualified 'int'. 9512 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9513 FD->setHasImplicitReturnZero(true); 9514 else { 9515 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9516 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9517 if (RTRange.isValid()) 9518 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9519 << FixItHint::CreateReplacement(RTRange, "int"); 9520 } 9521 } else { 9522 // In C and C++, main magically returns 0 if you fall off the end; 9523 // set the flag which tells us that. 9524 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9525 9526 // All the standards say that main() should return 'int'. 9527 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9528 FD->setHasImplicitReturnZero(true); 9529 else { 9530 // Otherwise, this is just a flat-out error. 9531 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9532 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9533 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9534 : FixItHint()); 9535 FD->setInvalidDecl(true); 9536 } 9537 } 9538 9539 // Treat protoless main() as nullary. 9540 if (isa<FunctionNoProtoType>(FT)) return; 9541 9542 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9543 unsigned nparams = FTP->getNumParams(); 9544 assert(FD->getNumParams() == nparams); 9545 9546 bool HasExtraParameters = (nparams > 3); 9547 9548 if (FTP->isVariadic()) { 9549 Diag(FD->getLocation(), diag::ext_variadic_main); 9550 // FIXME: if we had information about the location of the ellipsis, we 9551 // could add a FixIt hint to remove it as a parameter. 9552 } 9553 9554 // Darwin passes an undocumented fourth argument of type char**. If 9555 // other platforms start sprouting these, the logic below will start 9556 // getting shifty. 9557 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9558 HasExtraParameters = false; 9559 9560 if (HasExtraParameters) { 9561 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9562 FD->setInvalidDecl(true); 9563 nparams = 3; 9564 } 9565 9566 // FIXME: a lot of the following diagnostics would be improved 9567 // if we had some location information about types. 9568 9569 QualType CharPP = 9570 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9571 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9572 9573 for (unsigned i = 0; i < nparams; ++i) { 9574 QualType AT = FTP->getParamType(i); 9575 9576 bool mismatch = true; 9577 9578 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9579 mismatch = false; 9580 else if (Expected[i] == CharPP) { 9581 // As an extension, the following forms are okay: 9582 // char const ** 9583 // char const * const * 9584 // char * const * 9585 9586 QualifierCollector qs; 9587 const PointerType* PT; 9588 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9589 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9590 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9591 Context.CharTy)) { 9592 qs.removeConst(); 9593 mismatch = !qs.empty(); 9594 } 9595 } 9596 9597 if (mismatch) { 9598 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9599 // TODO: suggest replacing given type with expected type 9600 FD->setInvalidDecl(true); 9601 } 9602 } 9603 9604 if (nparams == 1 && !FD->isInvalidDecl()) { 9605 Diag(FD->getLocation(), diag::warn_main_one_arg); 9606 } 9607 9608 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9609 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9610 FD->setInvalidDecl(); 9611 } 9612 } 9613 9614 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9615 QualType T = FD->getType(); 9616 assert(T->isFunctionType() && "function decl is not of function type"); 9617 const FunctionType *FT = T->castAs<FunctionType>(); 9618 9619 // Set an implicit return of 'zero' if the function can return some integral, 9620 // enumeration, pointer or nullptr type. 9621 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9622 FT->getReturnType()->isAnyPointerType() || 9623 FT->getReturnType()->isNullPtrType()) 9624 // DllMain is exempt because a return value of zero means it failed. 9625 if (FD->getName() != "DllMain") 9626 FD->setHasImplicitReturnZero(true); 9627 9628 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9629 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9630 FD->setInvalidDecl(); 9631 } 9632 } 9633 9634 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9635 // FIXME: Need strict checking. In C89, we need to check for 9636 // any assignment, increment, decrement, function-calls, or 9637 // commas outside of a sizeof. In C99, it's the same list, 9638 // except that the aforementioned are allowed in unevaluated 9639 // expressions. Everything else falls under the 9640 // "may accept other forms of constant expressions" exception. 9641 // (We never end up here for C++, so the constant expression 9642 // rules there don't matter.) 9643 const Expr *Culprit; 9644 if (Init->isConstantInitializer(Context, false, &Culprit)) 9645 return false; 9646 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9647 << Culprit->getSourceRange(); 9648 return true; 9649 } 9650 9651 namespace { 9652 // Visits an initialization expression to see if OrigDecl is evaluated in 9653 // its own initialization and throws a warning if it does. 9654 class SelfReferenceChecker 9655 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9656 Sema &S; 9657 Decl *OrigDecl; 9658 bool isRecordType; 9659 bool isPODType; 9660 bool isReferenceType; 9661 9662 bool isInitList; 9663 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9664 9665 public: 9666 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9667 9668 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9669 S(S), OrigDecl(OrigDecl) { 9670 isPODType = false; 9671 isRecordType = false; 9672 isReferenceType = false; 9673 isInitList = false; 9674 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9675 isPODType = VD->getType().isPODType(S.Context); 9676 isRecordType = VD->getType()->isRecordType(); 9677 isReferenceType = VD->getType()->isReferenceType(); 9678 } 9679 } 9680 9681 // For most expressions, just call the visitor. For initializer lists, 9682 // track the index of the field being initialized since fields are 9683 // initialized in order allowing use of previously initialized fields. 9684 void CheckExpr(Expr *E) { 9685 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9686 if (!InitList) { 9687 Visit(E); 9688 return; 9689 } 9690 9691 // Track and increment the index here. 9692 isInitList = true; 9693 InitFieldIndex.push_back(0); 9694 for (auto Child : InitList->children()) { 9695 CheckExpr(cast<Expr>(Child)); 9696 ++InitFieldIndex.back(); 9697 } 9698 InitFieldIndex.pop_back(); 9699 } 9700 9701 // Returns true if MemberExpr is checked and no further checking is needed. 9702 // Returns false if additional checking is required. 9703 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9704 llvm::SmallVector<FieldDecl*, 4> Fields; 9705 Expr *Base = E; 9706 bool ReferenceField = false; 9707 9708 // Get the field memebers used. 9709 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9710 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9711 if (!FD) 9712 return false; 9713 Fields.push_back(FD); 9714 if (FD->getType()->isReferenceType()) 9715 ReferenceField = true; 9716 Base = ME->getBase()->IgnoreParenImpCasts(); 9717 } 9718 9719 // Keep checking only if the base Decl is the same. 9720 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9721 if (!DRE || DRE->getDecl() != OrigDecl) 9722 return false; 9723 9724 // A reference field can be bound to an unininitialized field. 9725 if (CheckReference && !ReferenceField) 9726 return true; 9727 9728 // Convert FieldDecls to their index number. 9729 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9730 for (const FieldDecl *I : llvm::reverse(Fields)) 9731 UsedFieldIndex.push_back(I->getFieldIndex()); 9732 9733 // See if a warning is needed by checking the first difference in index 9734 // numbers. If field being used has index less than the field being 9735 // initialized, then the use is safe. 9736 for (auto UsedIter = UsedFieldIndex.begin(), 9737 UsedEnd = UsedFieldIndex.end(), 9738 OrigIter = InitFieldIndex.begin(), 9739 OrigEnd = InitFieldIndex.end(); 9740 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9741 if (*UsedIter < *OrigIter) 9742 return true; 9743 if (*UsedIter > *OrigIter) 9744 break; 9745 } 9746 9747 // TODO: Add a different warning which will print the field names. 9748 HandleDeclRefExpr(DRE); 9749 return true; 9750 } 9751 9752 // For most expressions, the cast is directly above the DeclRefExpr. 9753 // For conditional operators, the cast can be outside the conditional 9754 // operator if both expressions are DeclRefExpr's. 9755 void HandleValue(Expr *E) { 9756 E = E->IgnoreParens(); 9757 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9758 HandleDeclRefExpr(DRE); 9759 return; 9760 } 9761 9762 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9763 Visit(CO->getCond()); 9764 HandleValue(CO->getTrueExpr()); 9765 HandleValue(CO->getFalseExpr()); 9766 return; 9767 } 9768 9769 if (BinaryConditionalOperator *BCO = 9770 dyn_cast<BinaryConditionalOperator>(E)) { 9771 Visit(BCO->getCond()); 9772 HandleValue(BCO->getFalseExpr()); 9773 return; 9774 } 9775 9776 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9777 HandleValue(OVE->getSourceExpr()); 9778 return; 9779 } 9780 9781 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9782 if (BO->getOpcode() == BO_Comma) { 9783 Visit(BO->getLHS()); 9784 HandleValue(BO->getRHS()); 9785 return; 9786 } 9787 } 9788 9789 if (isa<MemberExpr>(E)) { 9790 if (isInitList) { 9791 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9792 false /*CheckReference*/)) 9793 return; 9794 } 9795 9796 Expr *Base = E->IgnoreParenImpCasts(); 9797 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9798 // Check for static member variables and don't warn on them. 9799 if (!isa<FieldDecl>(ME->getMemberDecl())) 9800 return; 9801 Base = ME->getBase()->IgnoreParenImpCasts(); 9802 } 9803 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9804 HandleDeclRefExpr(DRE); 9805 return; 9806 } 9807 9808 Visit(E); 9809 } 9810 9811 // Reference types not handled in HandleValue are handled here since all 9812 // uses of references are bad, not just r-value uses. 9813 void VisitDeclRefExpr(DeclRefExpr *E) { 9814 if (isReferenceType) 9815 HandleDeclRefExpr(E); 9816 } 9817 9818 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9819 if (E->getCastKind() == CK_LValueToRValue) { 9820 HandleValue(E->getSubExpr()); 9821 return; 9822 } 9823 9824 Inherited::VisitImplicitCastExpr(E); 9825 } 9826 9827 void VisitMemberExpr(MemberExpr *E) { 9828 if (isInitList) { 9829 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9830 return; 9831 } 9832 9833 // Don't warn on arrays since they can be treated as pointers. 9834 if (E->getType()->canDecayToPointerType()) return; 9835 9836 // Warn when a non-static method call is followed by non-static member 9837 // field accesses, which is followed by a DeclRefExpr. 9838 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9839 bool Warn = (MD && !MD->isStatic()); 9840 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9841 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9842 if (!isa<FieldDecl>(ME->getMemberDecl())) 9843 Warn = false; 9844 Base = ME->getBase()->IgnoreParenImpCasts(); 9845 } 9846 9847 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9848 if (Warn) 9849 HandleDeclRefExpr(DRE); 9850 return; 9851 } 9852 9853 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9854 // Visit that expression. 9855 Visit(Base); 9856 } 9857 9858 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9859 Expr *Callee = E->getCallee(); 9860 9861 if (isa<UnresolvedLookupExpr>(Callee)) 9862 return Inherited::VisitCXXOperatorCallExpr(E); 9863 9864 Visit(Callee); 9865 for (auto Arg: E->arguments()) 9866 HandleValue(Arg->IgnoreParenImpCasts()); 9867 } 9868 9869 void VisitUnaryOperator(UnaryOperator *E) { 9870 // For POD record types, addresses of its own members are well-defined. 9871 if (E->getOpcode() == UO_AddrOf && isRecordType && 9872 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9873 if (!isPODType) 9874 HandleValue(E->getSubExpr()); 9875 return; 9876 } 9877 9878 if (E->isIncrementDecrementOp()) { 9879 HandleValue(E->getSubExpr()); 9880 return; 9881 } 9882 9883 Inherited::VisitUnaryOperator(E); 9884 } 9885 9886 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9887 9888 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9889 if (E->getConstructor()->isCopyConstructor()) { 9890 Expr *ArgExpr = E->getArg(0); 9891 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9892 if (ILE->getNumInits() == 1) 9893 ArgExpr = ILE->getInit(0); 9894 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9895 if (ICE->getCastKind() == CK_NoOp) 9896 ArgExpr = ICE->getSubExpr(); 9897 HandleValue(ArgExpr); 9898 return; 9899 } 9900 Inherited::VisitCXXConstructExpr(E); 9901 } 9902 9903 void VisitCallExpr(CallExpr *E) { 9904 // Treat std::move as a use. 9905 if (E->getNumArgs() == 1) { 9906 if (FunctionDecl *FD = E->getDirectCallee()) { 9907 if (FD->isInStdNamespace() && FD->getIdentifier() && 9908 FD->getIdentifier()->isStr("move")) { 9909 HandleValue(E->getArg(0)); 9910 return; 9911 } 9912 } 9913 } 9914 9915 Inherited::VisitCallExpr(E); 9916 } 9917 9918 void VisitBinaryOperator(BinaryOperator *E) { 9919 if (E->isCompoundAssignmentOp()) { 9920 HandleValue(E->getLHS()); 9921 Visit(E->getRHS()); 9922 return; 9923 } 9924 9925 Inherited::VisitBinaryOperator(E); 9926 } 9927 9928 // A custom visitor for BinaryConditionalOperator is needed because the 9929 // regular visitor would check the condition and true expression separately 9930 // but both point to the same place giving duplicate diagnostics. 9931 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9932 Visit(E->getCond()); 9933 Visit(E->getFalseExpr()); 9934 } 9935 9936 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9937 Decl* ReferenceDecl = DRE->getDecl(); 9938 if (OrigDecl != ReferenceDecl) return; 9939 unsigned diag; 9940 if (isReferenceType) { 9941 diag = diag::warn_uninit_self_reference_in_reference_init; 9942 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9943 diag = diag::warn_static_self_reference_in_init; 9944 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9945 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9946 DRE->getDecl()->getType()->isRecordType()) { 9947 diag = diag::warn_uninit_self_reference_in_init; 9948 } else { 9949 // Local variables will be handled by the CFG analysis. 9950 return; 9951 } 9952 9953 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9954 S.PDiag(diag) 9955 << DRE->getNameInfo().getName() 9956 << OrigDecl->getLocation() 9957 << DRE->getSourceRange()); 9958 } 9959 }; 9960 9961 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9962 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9963 bool DirectInit) { 9964 // Parameters arguments are occassionially constructed with itself, 9965 // for instance, in recursive functions. Skip them. 9966 if (isa<ParmVarDecl>(OrigDecl)) 9967 return; 9968 9969 E = E->IgnoreParens(); 9970 9971 // Skip checking T a = a where T is not a record or reference type. 9972 // Doing so is a way to silence uninitialized warnings. 9973 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9974 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9975 if (ICE->getCastKind() == CK_LValueToRValue) 9976 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9977 if (DRE->getDecl() == OrigDecl) 9978 return; 9979 9980 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9981 } 9982 } // end anonymous namespace 9983 9984 namespace { 9985 // Simple wrapper to add the name of a variable or (if no variable is 9986 // available) a DeclarationName into a diagnostic. 9987 struct VarDeclOrName { 9988 VarDecl *VDecl; 9989 DeclarationName Name; 9990 9991 friend const Sema::SemaDiagnosticBuilder & 9992 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 9993 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 9994 } 9995 }; 9996 } // end anonymous namespace 9997 9998 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9999 DeclarationName Name, QualType Type, 10000 TypeSourceInfo *TSI, 10001 SourceRange Range, bool DirectInit, 10002 Expr *Init) { 10003 bool IsInitCapture = !VDecl; 10004 assert((!VDecl || !VDecl->isInitCapture()) && 10005 "init captures are expected to be deduced prior to initialization"); 10006 10007 VarDeclOrName VN{VDecl, Name}; 10008 10009 DeducedType *Deduced = Type->getContainedDeducedType(); 10010 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10011 10012 // C++11 [dcl.spec.auto]p3 10013 if (!Init) { 10014 assert(VDecl && "no init for init capture deduction?"); 10015 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10016 << VDecl->getDeclName() << Type; 10017 return QualType(); 10018 } 10019 10020 ArrayRef<Expr*> DeduceInits = Init; 10021 if (DirectInit) { 10022 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10023 DeduceInits = PL->exprs(); 10024 } 10025 10026 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10027 assert(VDecl && "non-auto type for init capture deduction?"); 10028 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10029 InitializationKind Kind = InitializationKind::CreateForInit( 10030 VDecl->getLocation(), DirectInit, Init); 10031 // FIXME: Initialization should not be taking a mutable list of inits. 10032 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10033 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10034 InitsCopy); 10035 } 10036 10037 if (DirectInit) { 10038 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10039 DeduceInits = IL->inits(); 10040 } 10041 10042 // Deduction only works if we have exactly one source expression. 10043 if (DeduceInits.empty()) { 10044 // It isn't possible to write this directly, but it is possible to 10045 // end up in this situation with "auto x(some_pack...);" 10046 Diag(Init->getLocStart(), IsInitCapture 10047 ? diag::err_init_capture_no_expression 10048 : diag::err_auto_var_init_no_expression) 10049 << VN << Type << Range; 10050 return QualType(); 10051 } 10052 10053 if (DeduceInits.size() > 1) { 10054 Diag(DeduceInits[1]->getLocStart(), 10055 IsInitCapture ? diag::err_init_capture_multiple_expressions 10056 : diag::err_auto_var_init_multiple_expressions) 10057 << VN << Type << Range; 10058 return QualType(); 10059 } 10060 10061 Expr *DeduceInit = DeduceInits[0]; 10062 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10063 Diag(Init->getLocStart(), IsInitCapture 10064 ? diag::err_init_capture_paren_braces 10065 : diag::err_auto_var_init_paren_braces) 10066 << isa<InitListExpr>(Init) << VN << Type << Range; 10067 return QualType(); 10068 } 10069 10070 // Expressions default to 'id' when we're in a debugger. 10071 bool DefaultedAnyToId = false; 10072 if (getLangOpts().DebuggerCastResultToId && 10073 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10074 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10075 if (Result.isInvalid()) { 10076 return QualType(); 10077 } 10078 Init = Result.get(); 10079 DefaultedAnyToId = true; 10080 } 10081 10082 // C++ [dcl.decomp]p1: 10083 // If the assignment-expression [...] has array type A and no ref-qualifier 10084 // is present, e has type cv A 10085 if (VDecl && isa<DecompositionDecl>(VDecl) && 10086 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10087 DeduceInit->getType()->isConstantArrayType()) 10088 return Context.getQualifiedType(DeduceInit->getType(), 10089 Type.getQualifiers()); 10090 10091 QualType DeducedType; 10092 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10093 if (!IsInitCapture) 10094 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10095 else if (isa<InitListExpr>(Init)) 10096 Diag(Range.getBegin(), 10097 diag::err_init_capture_deduction_failure_from_init_list) 10098 << VN 10099 << (DeduceInit->getType().isNull() ? TSI->getType() 10100 : DeduceInit->getType()) 10101 << DeduceInit->getSourceRange(); 10102 else 10103 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10104 << VN << TSI->getType() 10105 << (DeduceInit->getType().isNull() ? TSI->getType() 10106 : DeduceInit->getType()) 10107 << DeduceInit->getSourceRange(); 10108 } 10109 10110 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10111 // 'id' instead of a specific object type prevents most of our usual 10112 // checks. 10113 // We only want to warn outside of template instantiations, though: 10114 // inside a template, the 'id' could have come from a parameter. 10115 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10116 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10117 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10118 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10119 } 10120 10121 return DeducedType; 10122 } 10123 10124 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10125 Expr *Init) { 10126 QualType DeducedType = deduceVarTypeFromInitializer( 10127 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10128 VDecl->getSourceRange(), DirectInit, Init); 10129 if (DeducedType.isNull()) { 10130 VDecl->setInvalidDecl(); 10131 return true; 10132 } 10133 10134 VDecl->setType(DeducedType); 10135 assert(VDecl->isLinkageValid()); 10136 10137 // In ARC, infer lifetime. 10138 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10139 VDecl->setInvalidDecl(); 10140 10141 // If this is a redeclaration, check that the type we just deduced matches 10142 // the previously declared type. 10143 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10144 // We never need to merge the type, because we cannot form an incomplete 10145 // array of auto, nor deduce such a type. 10146 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10147 } 10148 10149 // Check the deduced type is valid for a variable declaration. 10150 CheckVariableDeclarationType(VDecl); 10151 return VDecl->isInvalidDecl(); 10152 } 10153 10154 /// AddInitializerToDecl - Adds the initializer Init to the 10155 /// declaration dcl. If DirectInit is true, this is C++ direct 10156 /// initialization rather than copy initialization. 10157 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10158 // If there is no declaration, there was an error parsing it. Just ignore 10159 // the initializer. 10160 if (!RealDecl || RealDecl->isInvalidDecl()) { 10161 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10162 return; 10163 } 10164 10165 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10166 // Pure-specifiers are handled in ActOnPureSpecifier. 10167 Diag(Method->getLocation(), diag::err_member_function_initialization) 10168 << Method->getDeclName() << Init->getSourceRange(); 10169 Method->setInvalidDecl(); 10170 return; 10171 } 10172 10173 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10174 if (!VDecl) { 10175 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10176 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10177 RealDecl->setInvalidDecl(); 10178 return; 10179 } 10180 10181 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10182 if (VDecl->getType()->isUndeducedType()) { 10183 // Attempt typo correction early so that the type of the init expression can 10184 // be deduced based on the chosen correction if the original init contains a 10185 // TypoExpr. 10186 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10187 if (!Res.isUsable()) { 10188 RealDecl->setInvalidDecl(); 10189 return; 10190 } 10191 Init = Res.get(); 10192 10193 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10194 return; 10195 } 10196 10197 // dllimport cannot be used on variable definitions. 10198 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10199 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10200 VDecl->setInvalidDecl(); 10201 return; 10202 } 10203 10204 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10205 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10206 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10207 VDecl->setInvalidDecl(); 10208 return; 10209 } 10210 10211 if (!VDecl->getType()->isDependentType()) { 10212 // A definition must end up with a complete type, which means it must be 10213 // complete with the restriction that an array type might be completed by 10214 // the initializer; note that later code assumes this restriction. 10215 QualType BaseDeclType = VDecl->getType(); 10216 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10217 BaseDeclType = Array->getElementType(); 10218 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10219 diag::err_typecheck_decl_incomplete_type)) { 10220 RealDecl->setInvalidDecl(); 10221 return; 10222 } 10223 10224 // The variable can not have an abstract class type. 10225 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10226 diag::err_abstract_type_in_decl, 10227 AbstractVariableType)) 10228 VDecl->setInvalidDecl(); 10229 } 10230 10231 // If adding the initializer will turn this declaration into a definition, 10232 // and we already have a definition for this variable, diagnose or otherwise 10233 // handle the situation. 10234 VarDecl *Def; 10235 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10236 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10237 !VDecl->isThisDeclarationADemotedDefinition() && 10238 checkVarDeclRedefinition(Def, VDecl)) 10239 return; 10240 10241 if (getLangOpts().CPlusPlus) { 10242 // C++ [class.static.data]p4 10243 // If a static data member is of const integral or const 10244 // enumeration type, its declaration in the class definition can 10245 // specify a constant-initializer which shall be an integral 10246 // constant expression (5.19). In that case, the member can appear 10247 // in integral constant expressions. The member shall still be 10248 // defined in a namespace scope if it is used in the program and the 10249 // namespace scope definition shall not contain an initializer. 10250 // 10251 // We already performed a redefinition check above, but for static 10252 // data members we also need to check whether there was an in-class 10253 // declaration with an initializer. 10254 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10255 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10256 << VDecl->getDeclName(); 10257 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10258 diag::note_previous_initializer) 10259 << 0; 10260 return; 10261 } 10262 10263 if (VDecl->hasLocalStorage()) 10264 getCurFunction()->setHasBranchProtectedScope(); 10265 10266 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10267 VDecl->setInvalidDecl(); 10268 return; 10269 } 10270 } 10271 10272 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10273 // a kernel function cannot be initialized." 10274 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10275 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10276 VDecl->setInvalidDecl(); 10277 return; 10278 } 10279 10280 // Get the decls type and save a reference for later, since 10281 // CheckInitializerTypes may change it. 10282 QualType DclT = VDecl->getType(), SavT = DclT; 10283 10284 // Expressions default to 'id' when we're in a debugger 10285 // and we are assigning it to a variable of Objective-C pointer type. 10286 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10287 Init->getType() == Context.UnknownAnyTy) { 10288 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10289 if (Result.isInvalid()) { 10290 VDecl->setInvalidDecl(); 10291 return; 10292 } 10293 Init = Result.get(); 10294 } 10295 10296 // Perform the initialization. 10297 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10298 if (!VDecl->isInvalidDecl()) { 10299 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10300 InitializationKind Kind = InitializationKind::CreateForInit( 10301 VDecl->getLocation(), DirectInit, Init); 10302 10303 MultiExprArg Args = Init; 10304 if (CXXDirectInit) 10305 Args = MultiExprArg(CXXDirectInit->getExprs(), 10306 CXXDirectInit->getNumExprs()); 10307 10308 // Try to correct any TypoExprs in the initialization arguments. 10309 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10310 ExprResult Res = CorrectDelayedTyposInExpr( 10311 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10312 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10313 return Init.Failed() ? ExprError() : E; 10314 }); 10315 if (Res.isInvalid()) { 10316 VDecl->setInvalidDecl(); 10317 } else if (Res.get() != Args[Idx]) { 10318 Args[Idx] = Res.get(); 10319 } 10320 } 10321 if (VDecl->isInvalidDecl()) 10322 return; 10323 10324 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10325 /*TopLevelOfInitList=*/false, 10326 /*TreatUnavailableAsInvalid=*/false); 10327 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10328 if (Result.isInvalid()) { 10329 VDecl->setInvalidDecl(); 10330 return; 10331 } 10332 10333 Init = Result.getAs<Expr>(); 10334 } 10335 10336 // Check for self-references within variable initializers. 10337 // Variables declared within a function/method body (except for references) 10338 // are handled by a dataflow analysis. 10339 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10340 VDecl->getType()->isReferenceType()) { 10341 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10342 } 10343 10344 // If the type changed, it means we had an incomplete type that was 10345 // completed by the initializer. For example: 10346 // int ary[] = { 1, 3, 5 }; 10347 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10348 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10349 VDecl->setType(DclT); 10350 10351 if (!VDecl->isInvalidDecl()) { 10352 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10353 10354 if (VDecl->hasAttr<BlocksAttr>()) 10355 checkRetainCycles(VDecl, Init); 10356 10357 // It is safe to assign a weak reference into a strong variable. 10358 // Although this code can still have problems: 10359 // id x = self.weakProp; 10360 // id y = self.weakProp; 10361 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10362 // paths through the function. This should be revisited if 10363 // -Wrepeated-use-of-weak is made flow-sensitive. 10364 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10365 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10366 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10367 Init->getLocStart())) 10368 getCurFunction()->markSafeWeakUse(Init); 10369 } 10370 10371 // The initialization is usually a full-expression. 10372 // 10373 // FIXME: If this is a braced initialization of an aggregate, it is not 10374 // an expression, and each individual field initializer is a separate 10375 // full-expression. For instance, in: 10376 // 10377 // struct Temp { ~Temp(); }; 10378 // struct S { S(Temp); }; 10379 // struct T { S a, b; } t = { Temp(), Temp() } 10380 // 10381 // we should destroy the first Temp before constructing the second. 10382 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10383 false, 10384 VDecl->isConstexpr()); 10385 if (Result.isInvalid()) { 10386 VDecl->setInvalidDecl(); 10387 return; 10388 } 10389 Init = Result.get(); 10390 10391 // Attach the initializer to the decl. 10392 VDecl->setInit(Init); 10393 10394 if (VDecl->isLocalVarDecl()) { 10395 // Don't check the initializer if the declaration is malformed. 10396 if (VDecl->isInvalidDecl()) { 10397 // do nothing 10398 10399 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10400 // This is true even in OpenCL C++. 10401 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10402 CheckForConstantInitializer(Init, DclT); 10403 10404 // Otherwise, C++ does not restrict the initializer. 10405 } else if (getLangOpts().CPlusPlus) { 10406 // do nothing 10407 10408 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10409 // static storage duration shall be constant expressions or string literals. 10410 } else if (VDecl->getStorageClass() == SC_Static) { 10411 CheckForConstantInitializer(Init, DclT); 10412 10413 // C89 is stricter than C99 for aggregate initializers. 10414 // C89 6.5.7p3: All the expressions [...] in an initializer list 10415 // for an object that has aggregate or union type shall be 10416 // constant expressions. 10417 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10418 isa<InitListExpr>(Init)) { 10419 const Expr *Culprit; 10420 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10421 Diag(Culprit->getExprLoc(), 10422 diag::ext_aggregate_init_not_constant) 10423 << Culprit->getSourceRange(); 10424 } 10425 } 10426 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10427 VDecl->getLexicalDeclContext()->isRecord()) { 10428 // This is an in-class initialization for a static data member, e.g., 10429 // 10430 // struct S { 10431 // static const int value = 17; 10432 // }; 10433 10434 // C++ [class.mem]p4: 10435 // A member-declarator can contain a constant-initializer only 10436 // if it declares a static member (9.4) of const integral or 10437 // const enumeration type, see 9.4.2. 10438 // 10439 // C++11 [class.static.data]p3: 10440 // If a non-volatile non-inline const static data member is of integral 10441 // or enumeration type, its declaration in the class definition can 10442 // specify a brace-or-equal-initializer in which every initializer-clause 10443 // that is an assignment-expression is a constant expression. A static 10444 // data member of literal type can be declared in the class definition 10445 // with the constexpr specifier; if so, its declaration shall specify a 10446 // brace-or-equal-initializer in which every initializer-clause that is 10447 // an assignment-expression is a constant expression. 10448 10449 // Do nothing on dependent types. 10450 if (DclT->isDependentType()) { 10451 10452 // Allow any 'static constexpr' members, whether or not they are of literal 10453 // type. We separately check that every constexpr variable is of literal 10454 // type. 10455 } else if (VDecl->isConstexpr()) { 10456 10457 // Require constness. 10458 } else if (!DclT.isConstQualified()) { 10459 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10460 << Init->getSourceRange(); 10461 VDecl->setInvalidDecl(); 10462 10463 // We allow integer constant expressions in all cases. 10464 } else if (DclT->isIntegralOrEnumerationType()) { 10465 // Check whether the expression is a constant expression. 10466 SourceLocation Loc; 10467 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10468 // In C++11, a non-constexpr const static data member with an 10469 // in-class initializer cannot be volatile. 10470 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10471 else if (Init->isValueDependent()) 10472 ; // Nothing to check. 10473 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10474 ; // Ok, it's an ICE! 10475 else if (Init->isEvaluatable(Context)) { 10476 // If we can constant fold the initializer through heroics, accept it, 10477 // but report this as a use of an extension for -pedantic. 10478 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10479 << Init->getSourceRange(); 10480 } else { 10481 // Otherwise, this is some crazy unknown case. Report the issue at the 10482 // location provided by the isIntegerConstantExpr failed check. 10483 Diag(Loc, diag::err_in_class_initializer_non_constant) 10484 << Init->getSourceRange(); 10485 VDecl->setInvalidDecl(); 10486 } 10487 10488 // We allow foldable floating-point constants as an extension. 10489 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10490 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10491 // it anyway and provide a fixit to add the 'constexpr'. 10492 if (getLangOpts().CPlusPlus11) { 10493 Diag(VDecl->getLocation(), 10494 diag::ext_in_class_initializer_float_type_cxx11) 10495 << DclT << Init->getSourceRange(); 10496 Diag(VDecl->getLocStart(), 10497 diag::note_in_class_initializer_float_type_cxx11) 10498 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10499 } else { 10500 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10501 << DclT << Init->getSourceRange(); 10502 10503 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10504 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10505 << Init->getSourceRange(); 10506 VDecl->setInvalidDecl(); 10507 } 10508 } 10509 10510 // Suggest adding 'constexpr' in C++11 for literal types. 10511 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10512 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10513 << DclT << Init->getSourceRange() 10514 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10515 VDecl->setConstexpr(true); 10516 10517 } else { 10518 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10519 << DclT << Init->getSourceRange(); 10520 VDecl->setInvalidDecl(); 10521 } 10522 } else if (VDecl->isFileVarDecl()) { 10523 // In C, extern is typically used to avoid tentative definitions when 10524 // declaring variables in headers, but adding an intializer makes it a 10525 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10526 // In C++, extern is often used to give implictly static const variables 10527 // external linkage, so don't warn in that case. If selectany is present, 10528 // this might be header code intended for C and C++ inclusion, so apply the 10529 // C++ rules. 10530 if (VDecl->getStorageClass() == SC_Extern && 10531 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10532 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10533 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10534 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10535 Diag(VDecl->getLocation(), diag::warn_extern_init); 10536 10537 // C99 6.7.8p4. All file scoped initializers need to be constant. 10538 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10539 CheckForConstantInitializer(Init, DclT); 10540 } 10541 10542 // We will represent direct-initialization similarly to copy-initialization: 10543 // int x(1); -as-> int x = 1; 10544 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10545 // 10546 // Clients that want to distinguish between the two forms, can check for 10547 // direct initializer using VarDecl::getInitStyle(). 10548 // A major benefit is that clients that don't particularly care about which 10549 // exactly form was it (like the CodeGen) can handle both cases without 10550 // special case code. 10551 10552 // C++ 8.5p11: 10553 // The form of initialization (using parentheses or '=') is generally 10554 // insignificant, but does matter when the entity being initialized has a 10555 // class type. 10556 if (CXXDirectInit) { 10557 assert(DirectInit && "Call-style initializer must be direct init."); 10558 VDecl->setInitStyle(VarDecl::CallInit); 10559 } else if (DirectInit) { 10560 // This must be list-initialization. No other way is direct-initialization. 10561 VDecl->setInitStyle(VarDecl::ListInit); 10562 } 10563 10564 CheckCompleteVariableDeclaration(VDecl); 10565 } 10566 10567 /// ActOnInitializerError - Given that there was an error parsing an 10568 /// initializer for the given declaration, try to return to some form 10569 /// of sanity. 10570 void Sema::ActOnInitializerError(Decl *D) { 10571 // Our main concern here is re-establishing invariants like "a 10572 // variable's type is either dependent or complete". 10573 if (!D || D->isInvalidDecl()) return; 10574 10575 VarDecl *VD = dyn_cast<VarDecl>(D); 10576 if (!VD) return; 10577 10578 // Bindings are not usable if we can't make sense of the initializer. 10579 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10580 for (auto *BD : DD->bindings()) 10581 BD->setInvalidDecl(); 10582 10583 // Auto types are meaningless if we can't make sense of the initializer. 10584 if (ParsingInitForAutoVars.count(D)) { 10585 D->setInvalidDecl(); 10586 return; 10587 } 10588 10589 QualType Ty = VD->getType(); 10590 if (Ty->isDependentType()) return; 10591 10592 // Require a complete type. 10593 if (RequireCompleteType(VD->getLocation(), 10594 Context.getBaseElementType(Ty), 10595 diag::err_typecheck_decl_incomplete_type)) { 10596 VD->setInvalidDecl(); 10597 return; 10598 } 10599 10600 // Require a non-abstract type. 10601 if (RequireNonAbstractType(VD->getLocation(), Ty, 10602 diag::err_abstract_type_in_decl, 10603 AbstractVariableType)) { 10604 VD->setInvalidDecl(); 10605 return; 10606 } 10607 10608 // Don't bother complaining about constructors or destructors, 10609 // though. 10610 } 10611 10612 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10613 // If there is no declaration, there was an error parsing it. Just ignore it. 10614 if (!RealDecl) 10615 return; 10616 10617 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10618 QualType Type = Var->getType(); 10619 10620 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10621 if (isa<DecompositionDecl>(RealDecl)) { 10622 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10623 Var->setInvalidDecl(); 10624 return; 10625 } 10626 10627 if (Type->isUndeducedType() && 10628 DeduceVariableDeclarationType(Var, false, nullptr)) 10629 return; 10630 10631 // C++11 [class.static.data]p3: A static data member can be declared with 10632 // the constexpr specifier; if so, its declaration shall specify 10633 // a brace-or-equal-initializer. 10634 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10635 // the definition of a variable [...] or the declaration of a static data 10636 // member. 10637 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10638 !Var->isThisDeclarationADemotedDefinition()) { 10639 if (Var->isStaticDataMember()) { 10640 // C++1z removes the relevant rule; the in-class declaration is always 10641 // a definition there. 10642 if (!getLangOpts().CPlusPlus1z) { 10643 Diag(Var->getLocation(), 10644 diag::err_constexpr_static_mem_var_requires_init) 10645 << Var->getDeclName(); 10646 Var->setInvalidDecl(); 10647 return; 10648 } 10649 } else { 10650 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10651 Var->setInvalidDecl(); 10652 return; 10653 } 10654 } 10655 10656 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10657 // definition having the concept specifier is called a variable concept. A 10658 // concept definition refers to [...] a variable concept and its initializer. 10659 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10660 if (VTD->isConcept()) { 10661 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10662 Var->setInvalidDecl(); 10663 return; 10664 } 10665 } 10666 10667 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10668 // be initialized. 10669 if (!Var->isInvalidDecl() && 10670 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10671 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10672 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10673 Var->setInvalidDecl(); 10674 return; 10675 } 10676 10677 switch (Var->isThisDeclarationADefinition()) { 10678 case VarDecl::Definition: 10679 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10680 break; 10681 10682 // We have an out-of-line definition of a static data member 10683 // that has an in-class initializer, so we type-check this like 10684 // a declaration. 10685 // 10686 // Fall through 10687 10688 case VarDecl::DeclarationOnly: 10689 // It's only a declaration. 10690 10691 // Block scope. C99 6.7p7: If an identifier for an object is 10692 // declared with no linkage (C99 6.2.2p6), the type for the 10693 // object shall be complete. 10694 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10695 !Var->hasLinkage() && !Var->isInvalidDecl() && 10696 RequireCompleteType(Var->getLocation(), Type, 10697 diag::err_typecheck_decl_incomplete_type)) 10698 Var->setInvalidDecl(); 10699 10700 // Make sure that the type is not abstract. 10701 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10702 RequireNonAbstractType(Var->getLocation(), Type, 10703 diag::err_abstract_type_in_decl, 10704 AbstractVariableType)) 10705 Var->setInvalidDecl(); 10706 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10707 Var->getStorageClass() == SC_PrivateExtern) { 10708 Diag(Var->getLocation(), diag::warn_private_extern); 10709 Diag(Var->getLocation(), diag::note_private_extern); 10710 } 10711 10712 return; 10713 10714 case VarDecl::TentativeDefinition: 10715 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10716 // object that has file scope without an initializer, and without a 10717 // storage-class specifier or with the storage-class specifier "static", 10718 // constitutes a tentative definition. Note: A tentative definition with 10719 // external linkage is valid (C99 6.2.2p5). 10720 if (!Var->isInvalidDecl()) { 10721 if (const IncompleteArrayType *ArrayT 10722 = Context.getAsIncompleteArrayType(Type)) { 10723 if (RequireCompleteType(Var->getLocation(), 10724 ArrayT->getElementType(), 10725 diag::err_illegal_decl_array_incomplete_type)) 10726 Var->setInvalidDecl(); 10727 } else if (Var->getStorageClass() == SC_Static) { 10728 // C99 6.9.2p3: If the declaration of an identifier for an object is 10729 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10730 // declared type shall not be an incomplete type. 10731 // NOTE: code such as the following 10732 // static struct s; 10733 // struct s { int a; }; 10734 // is accepted by gcc. Hence here we issue a warning instead of 10735 // an error and we do not invalidate the static declaration. 10736 // NOTE: to avoid multiple warnings, only check the first declaration. 10737 if (Var->isFirstDecl()) 10738 RequireCompleteType(Var->getLocation(), Type, 10739 diag::ext_typecheck_decl_incomplete_type); 10740 } 10741 } 10742 10743 // Record the tentative definition; we're done. 10744 if (!Var->isInvalidDecl()) 10745 TentativeDefinitions.push_back(Var); 10746 return; 10747 } 10748 10749 // Provide a specific diagnostic for uninitialized variable 10750 // definitions with incomplete array type. 10751 if (Type->isIncompleteArrayType()) { 10752 Diag(Var->getLocation(), 10753 diag::err_typecheck_incomplete_array_needs_initializer); 10754 Var->setInvalidDecl(); 10755 return; 10756 } 10757 10758 // Provide a specific diagnostic for uninitialized variable 10759 // definitions with reference type. 10760 if (Type->isReferenceType()) { 10761 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10762 << Var->getDeclName() 10763 << SourceRange(Var->getLocation(), Var->getLocation()); 10764 Var->setInvalidDecl(); 10765 return; 10766 } 10767 10768 // Do not attempt to type-check the default initializer for a 10769 // variable with dependent type. 10770 if (Type->isDependentType()) 10771 return; 10772 10773 if (Var->isInvalidDecl()) 10774 return; 10775 10776 if (!Var->hasAttr<AliasAttr>()) { 10777 if (RequireCompleteType(Var->getLocation(), 10778 Context.getBaseElementType(Type), 10779 diag::err_typecheck_decl_incomplete_type)) { 10780 Var->setInvalidDecl(); 10781 return; 10782 } 10783 } else { 10784 return; 10785 } 10786 10787 // The variable can not have an abstract class type. 10788 if (RequireNonAbstractType(Var->getLocation(), Type, 10789 diag::err_abstract_type_in_decl, 10790 AbstractVariableType)) { 10791 Var->setInvalidDecl(); 10792 return; 10793 } 10794 10795 // Check for jumps past the implicit initializer. C++0x 10796 // clarifies that this applies to a "variable with automatic 10797 // storage duration", not a "local variable". 10798 // C++11 [stmt.dcl]p3 10799 // A program that jumps from a point where a variable with automatic 10800 // storage duration is not in scope to a point where it is in scope is 10801 // ill-formed unless the variable has scalar type, class type with a 10802 // trivial default constructor and a trivial destructor, a cv-qualified 10803 // version of one of these types, or an array of one of the preceding 10804 // types and is declared without an initializer. 10805 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10806 if (const RecordType *Record 10807 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10808 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10809 // Mark the function for further checking even if the looser rules of 10810 // C++11 do not require such checks, so that we can diagnose 10811 // incompatibilities with C++98. 10812 if (!CXXRecord->isPOD()) 10813 getCurFunction()->setHasBranchProtectedScope(); 10814 } 10815 } 10816 10817 // C++03 [dcl.init]p9: 10818 // If no initializer is specified for an object, and the 10819 // object is of (possibly cv-qualified) non-POD class type (or 10820 // array thereof), the object shall be default-initialized; if 10821 // the object is of const-qualified type, the underlying class 10822 // type shall have a user-declared default 10823 // constructor. Otherwise, if no initializer is specified for 10824 // a non- static object, the object and its subobjects, if 10825 // any, have an indeterminate initial value); if the object 10826 // or any of its subobjects are of const-qualified type, the 10827 // program is ill-formed. 10828 // C++0x [dcl.init]p11: 10829 // If no initializer is specified for an object, the object is 10830 // default-initialized; [...]. 10831 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10832 InitializationKind Kind 10833 = InitializationKind::CreateDefault(Var->getLocation()); 10834 10835 InitializationSequence InitSeq(*this, Entity, Kind, None); 10836 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10837 if (Init.isInvalid()) 10838 Var->setInvalidDecl(); 10839 else if (Init.get()) { 10840 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10841 // This is important for template substitution. 10842 Var->setInitStyle(VarDecl::CallInit); 10843 } 10844 10845 CheckCompleteVariableDeclaration(Var); 10846 } 10847 } 10848 10849 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10850 // If there is no declaration, there was an error parsing it. Ignore it. 10851 if (!D) 10852 return; 10853 10854 VarDecl *VD = dyn_cast<VarDecl>(D); 10855 if (!VD) { 10856 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10857 D->setInvalidDecl(); 10858 return; 10859 } 10860 10861 VD->setCXXForRangeDecl(true); 10862 10863 // for-range-declaration cannot be given a storage class specifier. 10864 int Error = -1; 10865 switch (VD->getStorageClass()) { 10866 case SC_None: 10867 break; 10868 case SC_Extern: 10869 Error = 0; 10870 break; 10871 case SC_Static: 10872 Error = 1; 10873 break; 10874 case SC_PrivateExtern: 10875 Error = 2; 10876 break; 10877 case SC_Auto: 10878 Error = 3; 10879 break; 10880 case SC_Register: 10881 Error = 4; 10882 break; 10883 } 10884 if (Error != -1) { 10885 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10886 << VD->getDeclName() << Error; 10887 D->setInvalidDecl(); 10888 } 10889 } 10890 10891 StmtResult 10892 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10893 IdentifierInfo *Ident, 10894 ParsedAttributes &Attrs, 10895 SourceLocation AttrEnd) { 10896 // C++1y [stmt.iter]p1: 10897 // A range-based for statement of the form 10898 // for ( for-range-identifier : for-range-initializer ) statement 10899 // is equivalent to 10900 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10901 DeclSpec DS(Attrs.getPool().getFactory()); 10902 10903 const char *PrevSpec; 10904 unsigned DiagID; 10905 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10906 getPrintingPolicy()); 10907 10908 Declarator D(DS, Declarator::ForContext); 10909 D.SetIdentifier(Ident, IdentLoc); 10910 D.takeAttributes(Attrs, AttrEnd); 10911 10912 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10913 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10914 EmptyAttrs, IdentLoc); 10915 Decl *Var = ActOnDeclarator(S, D); 10916 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10917 FinalizeDeclaration(Var); 10918 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10919 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10920 } 10921 10922 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10923 if (var->isInvalidDecl()) return; 10924 10925 if (getLangOpts().OpenCL) { 10926 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10927 // initialiser 10928 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10929 !var->hasInit()) { 10930 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10931 << 1 /*Init*/; 10932 var->setInvalidDecl(); 10933 return; 10934 } 10935 } 10936 10937 // In Objective-C, don't allow jumps past the implicit initialization of a 10938 // local retaining variable. 10939 if (getLangOpts().ObjC1 && 10940 var->hasLocalStorage()) { 10941 switch (var->getType().getObjCLifetime()) { 10942 case Qualifiers::OCL_None: 10943 case Qualifiers::OCL_ExplicitNone: 10944 case Qualifiers::OCL_Autoreleasing: 10945 break; 10946 10947 case Qualifiers::OCL_Weak: 10948 case Qualifiers::OCL_Strong: 10949 getCurFunction()->setHasBranchProtectedScope(); 10950 break; 10951 } 10952 } 10953 10954 // Warn about externally-visible variables being defined without a 10955 // prior declaration. We only want to do this for global 10956 // declarations, but we also specifically need to avoid doing it for 10957 // class members because the linkage of an anonymous class can 10958 // change if it's later given a typedef name. 10959 if (var->isThisDeclarationADefinition() && 10960 var->getDeclContext()->getRedeclContext()->isFileContext() && 10961 var->isExternallyVisible() && var->hasLinkage() && 10962 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10963 var->getLocation())) { 10964 // Find a previous declaration that's not a definition. 10965 VarDecl *prev = var->getPreviousDecl(); 10966 while (prev && prev->isThisDeclarationADefinition()) 10967 prev = prev->getPreviousDecl(); 10968 10969 if (!prev) 10970 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10971 } 10972 10973 // Cache the result of checking for constant initialization. 10974 Optional<bool> CacheHasConstInit; 10975 const Expr *CacheCulprit; 10976 auto checkConstInit = [&]() mutable { 10977 if (!CacheHasConstInit) 10978 CacheHasConstInit = var->getInit()->isConstantInitializer( 10979 Context, var->getType()->isReferenceType(), &CacheCulprit); 10980 return *CacheHasConstInit; 10981 }; 10982 10983 if (var->getTLSKind() == VarDecl::TLS_Static) { 10984 if (var->getType().isDestructedType()) { 10985 // GNU C++98 edits for __thread, [basic.start.term]p3: 10986 // The type of an object with thread storage duration shall not 10987 // have a non-trivial destructor. 10988 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10989 if (getLangOpts().CPlusPlus11) 10990 Diag(var->getLocation(), diag::note_use_thread_local); 10991 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10992 if (!checkConstInit()) { 10993 // GNU C++98 edits for __thread, [basic.start.init]p4: 10994 // An object of thread storage duration shall not require dynamic 10995 // initialization. 10996 // FIXME: Need strict checking here. 10997 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 10998 << CacheCulprit->getSourceRange(); 10999 if (getLangOpts().CPlusPlus11) 11000 Diag(var->getLocation(), diag::note_use_thread_local); 11001 } 11002 } 11003 } 11004 11005 // Apply section attributes and pragmas to global variables. 11006 bool GlobalStorage = var->hasGlobalStorage(); 11007 if (GlobalStorage && var->isThisDeclarationADefinition() && 11008 !inTemplateInstantiation()) { 11009 PragmaStack<StringLiteral *> *Stack = nullptr; 11010 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11011 if (var->getType().isConstQualified()) 11012 Stack = &ConstSegStack; 11013 else if (!var->getInit()) { 11014 Stack = &BSSSegStack; 11015 SectionFlags |= ASTContext::PSF_Write; 11016 } else { 11017 Stack = &DataSegStack; 11018 SectionFlags |= ASTContext::PSF_Write; 11019 } 11020 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11021 var->addAttr(SectionAttr::CreateImplicit( 11022 Context, SectionAttr::Declspec_allocate, 11023 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11024 } 11025 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11026 if (UnifySection(SA->getName(), SectionFlags, var)) 11027 var->dropAttr<SectionAttr>(); 11028 11029 // Apply the init_seg attribute if this has an initializer. If the 11030 // initializer turns out to not be dynamic, we'll end up ignoring this 11031 // attribute. 11032 if (CurInitSeg && var->getInit()) 11033 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11034 CurInitSegLoc)); 11035 } 11036 11037 // All the following checks are C++ only. 11038 if (!getLangOpts().CPlusPlus) { 11039 // If this variable must be emitted, add it as an initializer for the 11040 // current module. 11041 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11042 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11043 return; 11044 } 11045 11046 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11047 CheckCompleteDecompositionDeclaration(DD); 11048 11049 QualType type = var->getType(); 11050 if (type->isDependentType()) return; 11051 11052 // __block variables might require us to capture a copy-initializer. 11053 if (var->hasAttr<BlocksAttr>()) { 11054 // It's currently invalid to ever have a __block variable with an 11055 // array type; should we diagnose that here? 11056 11057 // Regardless, we don't want to ignore array nesting when 11058 // constructing this copy. 11059 if (type->isStructureOrClassType()) { 11060 EnterExpressionEvaluationContext scope( 11061 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11062 SourceLocation poi = var->getLocation(); 11063 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11064 ExprResult result 11065 = PerformMoveOrCopyInitialization( 11066 InitializedEntity::InitializeBlock(poi, type, false), 11067 var, var->getType(), varRef, /*AllowNRVO=*/true); 11068 if (!result.isInvalid()) { 11069 result = MaybeCreateExprWithCleanups(result); 11070 Expr *init = result.getAs<Expr>(); 11071 Context.setBlockVarCopyInits(var, init); 11072 } 11073 } 11074 } 11075 11076 Expr *Init = var->getInit(); 11077 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11078 QualType baseType = Context.getBaseElementType(type); 11079 11080 if (!var->getDeclContext()->isDependentContext() && 11081 Init && !Init->isValueDependent()) { 11082 11083 if (var->isConstexpr()) { 11084 SmallVector<PartialDiagnosticAt, 8> Notes; 11085 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11086 SourceLocation DiagLoc = var->getLocation(); 11087 // If the note doesn't add any useful information other than a source 11088 // location, fold it into the primary diagnostic. 11089 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11090 diag::note_invalid_subexpr_in_const_expr) { 11091 DiagLoc = Notes[0].first; 11092 Notes.clear(); 11093 } 11094 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11095 << var << Init->getSourceRange(); 11096 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11097 Diag(Notes[I].first, Notes[I].second); 11098 } 11099 } else if (var->isUsableInConstantExpressions(Context)) { 11100 // Check whether the initializer of a const variable of integral or 11101 // enumeration type is an ICE now, since we can't tell whether it was 11102 // initialized by a constant expression if we check later. 11103 var->checkInitIsICE(); 11104 } 11105 11106 // Don't emit further diagnostics about constexpr globals since they 11107 // were just diagnosed. 11108 if (!var->isConstexpr() && GlobalStorage && 11109 var->hasAttr<RequireConstantInitAttr>()) { 11110 // FIXME: Need strict checking in C++03 here. 11111 bool DiagErr = getLangOpts().CPlusPlus11 11112 ? !var->checkInitIsICE() : !checkConstInit(); 11113 if (DiagErr) { 11114 auto attr = var->getAttr<RequireConstantInitAttr>(); 11115 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11116 << Init->getSourceRange(); 11117 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11118 << attr->getRange(); 11119 } 11120 } 11121 else if (!var->isConstexpr() && IsGlobal && 11122 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11123 var->getLocation())) { 11124 // Warn about globals which don't have a constant initializer. Don't 11125 // warn about globals with a non-trivial destructor because we already 11126 // warned about them. 11127 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11128 if (!(RD && !RD->hasTrivialDestructor())) { 11129 if (!checkConstInit()) 11130 Diag(var->getLocation(), diag::warn_global_constructor) 11131 << Init->getSourceRange(); 11132 } 11133 } 11134 } 11135 11136 // Require the destructor. 11137 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11138 FinalizeVarWithDestructor(var, recordType); 11139 11140 // If this variable must be emitted, add it as an initializer for the current 11141 // module. 11142 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11143 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11144 } 11145 11146 /// \brief Determines if a variable's alignment is dependent. 11147 static bool hasDependentAlignment(VarDecl *VD) { 11148 if (VD->getType()->isDependentType()) 11149 return true; 11150 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11151 if (I->isAlignmentDependent()) 11152 return true; 11153 return false; 11154 } 11155 11156 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11157 /// any semantic actions necessary after any initializer has been attached. 11158 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11159 // Note that we are no longer parsing the initializer for this declaration. 11160 ParsingInitForAutoVars.erase(ThisDecl); 11161 11162 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11163 if (!VD) 11164 return; 11165 11166 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11167 for (auto *BD : DD->bindings()) { 11168 FinalizeDeclaration(BD); 11169 } 11170 } 11171 11172 checkAttributesAfterMerging(*this, *VD); 11173 11174 // Perform TLS alignment check here after attributes attached to the variable 11175 // which may affect the alignment have been processed. Only perform the check 11176 // if the target has a maximum TLS alignment (zero means no constraints). 11177 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11178 // Protect the check so that it's not performed on dependent types and 11179 // dependent alignments (we can't determine the alignment in that case). 11180 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11181 !VD->isInvalidDecl()) { 11182 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11183 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11184 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11185 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11186 << (unsigned)MaxAlignChars.getQuantity(); 11187 } 11188 } 11189 } 11190 11191 if (VD->isStaticLocal()) { 11192 if (FunctionDecl *FD = 11193 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11194 // Static locals inherit dll attributes from their function. 11195 if (Attr *A = getDLLAttr(FD)) { 11196 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11197 NewAttr->setInherited(true); 11198 VD->addAttr(NewAttr); 11199 } 11200 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11201 // function, only __shared__ variables may be declared with 11202 // static storage class. 11203 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11204 CUDADiagIfDeviceCode(VD->getLocation(), 11205 diag::err_device_static_local_var) 11206 << CurrentCUDATarget()) 11207 VD->setInvalidDecl(); 11208 } 11209 } 11210 11211 // Perform check for initializers of device-side global variables. 11212 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11213 // 7.5). We must also apply the same checks to all __shared__ 11214 // variables whether they are local or not. CUDA also allows 11215 // constant initializers for __constant__ and __device__ variables. 11216 if (getLangOpts().CUDA) { 11217 const Expr *Init = VD->getInit(); 11218 if (Init && VD->hasGlobalStorage()) { 11219 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11220 VD->hasAttr<CUDASharedAttr>()) { 11221 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11222 bool AllowedInit = false; 11223 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11224 AllowedInit = 11225 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11226 // We'll allow constant initializers even if it's a non-empty 11227 // constructor according to CUDA rules. This deviates from NVCC, 11228 // but allows us to handle things like constexpr constructors. 11229 if (!AllowedInit && 11230 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11231 AllowedInit = VD->getInit()->isConstantInitializer( 11232 Context, VD->getType()->isReferenceType()); 11233 11234 // Also make sure that destructor, if there is one, is empty. 11235 if (AllowedInit) 11236 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11237 AllowedInit = 11238 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11239 11240 if (!AllowedInit) { 11241 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11242 ? diag::err_shared_var_init 11243 : diag::err_dynamic_var_init) 11244 << Init->getSourceRange(); 11245 VD->setInvalidDecl(); 11246 } 11247 } else { 11248 // This is a host-side global variable. Check that the initializer is 11249 // callable from the host side. 11250 const FunctionDecl *InitFn = nullptr; 11251 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11252 InitFn = CE->getConstructor(); 11253 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11254 InitFn = CE->getDirectCallee(); 11255 } 11256 if (InitFn) { 11257 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11258 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11259 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11260 << InitFnTarget << InitFn; 11261 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11262 VD->setInvalidDecl(); 11263 } 11264 } 11265 } 11266 } 11267 } 11268 11269 // Grab the dllimport or dllexport attribute off of the VarDecl. 11270 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11271 11272 // Imported static data members cannot be defined out-of-line. 11273 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11274 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11275 VD->isThisDeclarationADefinition()) { 11276 // We allow definitions of dllimport class template static data members 11277 // with a warning. 11278 CXXRecordDecl *Context = 11279 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11280 bool IsClassTemplateMember = 11281 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11282 Context->getDescribedClassTemplate(); 11283 11284 Diag(VD->getLocation(), 11285 IsClassTemplateMember 11286 ? diag::warn_attribute_dllimport_static_field_definition 11287 : diag::err_attribute_dllimport_static_field_definition); 11288 Diag(IA->getLocation(), diag::note_attribute); 11289 if (!IsClassTemplateMember) 11290 VD->setInvalidDecl(); 11291 } 11292 } 11293 11294 // dllimport/dllexport variables cannot be thread local, their TLS index 11295 // isn't exported with the variable. 11296 if (DLLAttr && VD->getTLSKind()) { 11297 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11298 if (F && getDLLAttr(F)) { 11299 assert(VD->isStaticLocal()); 11300 // But if this is a static local in a dlimport/dllexport function, the 11301 // function will never be inlined, which means the var would never be 11302 // imported, so having it marked import/export is safe. 11303 } else { 11304 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11305 << DLLAttr; 11306 VD->setInvalidDecl(); 11307 } 11308 } 11309 11310 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11311 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11312 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11313 VD->dropAttr<UsedAttr>(); 11314 } 11315 } 11316 11317 const DeclContext *DC = VD->getDeclContext(); 11318 // If there's a #pragma GCC visibility in scope, and this isn't a class 11319 // member, set the visibility of this variable. 11320 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11321 AddPushedVisibilityAttribute(VD); 11322 11323 // FIXME: Warn on unused var template partial specializations. 11324 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11325 MarkUnusedFileScopedDecl(VD); 11326 11327 // Now we have parsed the initializer and can update the table of magic 11328 // tag values. 11329 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11330 !VD->getType()->isIntegralOrEnumerationType()) 11331 return; 11332 11333 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11334 const Expr *MagicValueExpr = VD->getInit(); 11335 if (!MagicValueExpr) { 11336 continue; 11337 } 11338 llvm::APSInt MagicValueInt; 11339 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11340 Diag(I->getRange().getBegin(), 11341 diag::err_type_tag_for_datatype_not_ice) 11342 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11343 continue; 11344 } 11345 if (MagicValueInt.getActiveBits() > 64) { 11346 Diag(I->getRange().getBegin(), 11347 diag::err_type_tag_for_datatype_too_large) 11348 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11349 continue; 11350 } 11351 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11352 RegisterTypeTagForDatatype(I->getArgumentKind(), 11353 MagicValue, 11354 I->getMatchingCType(), 11355 I->getLayoutCompatible(), 11356 I->getMustBeNull()); 11357 } 11358 } 11359 11360 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11361 auto *VD = dyn_cast<VarDecl>(DD); 11362 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11363 } 11364 11365 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11366 ArrayRef<Decl *> Group) { 11367 SmallVector<Decl*, 8> Decls; 11368 11369 if (DS.isTypeSpecOwned()) 11370 Decls.push_back(DS.getRepAsDecl()); 11371 11372 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11373 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11374 bool DiagnosedMultipleDecomps = false; 11375 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11376 bool DiagnosedNonDeducedAuto = false; 11377 11378 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11379 if (Decl *D = Group[i]) { 11380 // For declarators, there are some additional syntactic-ish checks we need 11381 // to perform. 11382 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11383 if (!FirstDeclaratorInGroup) 11384 FirstDeclaratorInGroup = DD; 11385 if (!FirstDecompDeclaratorInGroup) 11386 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11387 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11388 !hasDeducedAuto(DD)) 11389 FirstNonDeducedAutoInGroup = DD; 11390 11391 if (FirstDeclaratorInGroup != DD) { 11392 // A decomposition declaration cannot be combined with any other 11393 // declaration in the same group. 11394 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11395 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11396 diag::err_decomp_decl_not_alone) 11397 << FirstDeclaratorInGroup->getSourceRange() 11398 << DD->getSourceRange(); 11399 DiagnosedMultipleDecomps = true; 11400 } 11401 11402 // A declarator that uses 'auto' in any way other than to declare a 11403 // variable with a deduced type cannot be combined with any other 11404 // declarator in the same group. 11405 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11406 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11407 diag::err_auto_non_deduced_not_alone) 11408 << FirstNonDeducedAutoInGroup->getType() 11409 ->hasAutoForTrailingReturnType() 11410 << FirstDeclaratorInGroup->getSourceRange() 11411 << DD->getSourceRange(); 11412 DiagnosedNonDeducedAuto = true; 11413 } 11414 } 11415 } 11416 11417 Decls.push_back(D); 11418 } 11419 } 11420 11421 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11422 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11423 handleTagNumbering(Tag, S); 11424 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11425 getLangOpts().CPlusPlus) 11426 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11427 } 11428 } 11429 11430 return BuildDeclaratorGroup(Decls); 11431 } 11432 11433 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11434 /// group, performing any necessary semantic checking. 11435 Sema::DeclGroupPtrTy 11436 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11437 // C++14 [dcl.spec.auto]p7: (DR1347) 11438 // If the type that replaces the placeholder type is not the same in each 11439 // deduction, the program is ill-formed. 11440 if (Group.size() > 1) { 11441 QualType Deduced; 11442 VarDecl *DeducedDecl = nullptr; 11443 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11444 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11445 if (!D || D->isInvalidDecl()) 11446 break; 11447 DeducedType *DT = D->getType()->getContainedDeducedType(); 11448 if (!DT || DT->getDeducedType().isNull()) 11449 continue; 11450 if (Deduced.isNull()) { 11451 Deduced = DT->getDeducedType(); 11452 DeducedDecl = D; 11453 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11454 auto *AT = dyn_cast<AutoType>(DT); 11455 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11456 diag::err_auto_different_deductions) 11457 << (AT ? (unsigned)AT->getKeyword() : 3) 11458 << Deduced << DeducedDecl->getDeclName() 11459 << DT->getDeducedType() << D->getDeclName() 11460 << DeducedDecl->getInit()->getSourceRange() 11461 << D->getInit()->getSourceRange(); 11462 D->setInvalidDecl(); 11463 break; 11464 } 11465 } 11466 } 11467 11468 ActOnDocumentableDecls(Group); 11469 11470 return DeclGroupPtrTy::make( 11471 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11472 } 11473 11474 void Sema::ActOnDocumentableDecl(Decl *D) { 11475 ActOnDocumentableDecls(D); 11476 } 11477 11478 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11479 // Don't parse the comment if Doxygen diagnostics are ignored. 11480 if (Group.empty() || !Group[0]) 11481 return; 11482 11483 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11484 Group[0]->getLocation()) && 11485 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11486 Group[0]->getLocation())) 11487 return; 11488 11489 if (Group.size() >= 2) { 11490 // This is a decl group. Normally it will contain only declarations 11491 // produced from declarator list. But in case we have any definitions or 11492 // additional declaration references: 11493 // 'typedef struct S {} S;' 11494 // 'typedef struct S *S;' 11495 // 'struct S *pS;' 11496 // FinalizeDeclaratorGroup adds these as separate declarations. 11497 Decl *MaybeTagDecl = Group[0]; 11498 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11499 Group = Group.slice(1); 11500 } 11501 } 11502 11503 // See if there are any new comments that are not attached to a decl. 11504 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11505 if (!Comments.empty() && 11506 !Comments.back()->isAttached()) { 11507 // There is at least one comment that not attached to a decl. 11508 // Maybe it should be attached to one of these decls? 11509 // 11510 // Note that this way we pick up not only comments that precede the 11511 // declaration, but also comments that *follow* the declaration -- thanks to 11512 // the lookahead in the lexer: we've consumed the semicolon and looked 11513 // ahead through comments. 11514 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11515 Context.getCommentForDecl(Group[i], &PP); 11516 } 11517 } 11518 11519 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11520 /// to introduce parameters into function prototype scope. 11521 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11522 const DeclSpec &DS = D.getDeclSpec(); 11523 11524 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11525 11526 // C++03 [dcl.stc]p2 also permits 'auto'. 11527 StorageClass SC = SC_None; 11528 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11529 SC = SC_Register; 11530 } else if (getLangOpts().CPlusPlus && 11531 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11532 SC = SC_Auto; 11533 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11534 Diag(DS.getStorageClassSpecLoc(), 11535 diag::err_invalid_storage_class_in_func_decl); 11536 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11537 } 11538 11539 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11540 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11541 << DeclSpec::getSpecifierName(TSCS); 11542 if (DS.isInlineSpecified()) 11543 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11544 << getLangOpts().CPlusPlus1z; 11545 if (DS.isConstexprSpecified()) 11546 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11547 << 0; 11548 if (DS.isConceptSpecified()) 11549 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11550 11551 DiagnoseFunctionSpecifiers(DS); 11552 11553 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11554 QualType parmDeclType = TInfo->getType(); 11555 11556 if (getLangOpts().CPlusPlus) { 11557 // Check that there are no default arguments inside the type of this 11558 // parameter. 11559 CheckExtraCXXDefaultArguments(D); 11560 11561 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11562 if (D.getCXXScopeSpec().isSet()) { 11563 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11564 << D.getCXXScopeSpec().getRange(); 11565 D.getCXXScopeSpec().clear(); 11566 } 11567 } 11568 11569 // Ensure we have a valid name 11570 IdentifierInfo *II = nullptr; 11571 if (D.hasName()) { 11572 II = D.getIdentifier(); 11573 if (!II) { 11574 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11575 << GetNameForDeclarator(D).getName(); 11576 D.setInvalidType(true); 11577 } 11578 } 11579 11580 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11581 if (II) { 11582 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11583 ForRedeclaration); 11584 LookupName(R, S); 11585 if (R.isSingleResult()) { 11586 NamedDecl *PrevDecl = R.getFoundDecl(); 11587 if (PrevDecl->isTemplateParameter()) { 11588 // Maybe we will complain about the shadowed template parameter. 11589 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11590 // Just pretend that we didn't see the previous declaration. 11591 PrevDecl = nullptr; 11592 } else if (S->isDeclScope(PrevDecl)) { 11593 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11594 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11595 11596 // Recover by removing the name 11597 II = nullptr; 11598 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11599 D.setInvalidType(true); 11600 } 11601 } 11602 } 11603 11604 // Temporarily put parameter variables in the translation unit, not 11605 // the enclosing context. This prevents them from accidentally 11606 // looking like class members in C++. 11607 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11608 D.getLocStart(), 11609 D.getIdentifierLoc(), II, 11610 parmDeclType, TInfo, 11611 SC); 11612 11613 if (D.isInvalidType()) 11614 New->setInvalidDecl(); 11615 11616 assert(S->isFunctionPrototypeScope()); 11617 assert(S->getFunctionPrototypeDepth() >= 1); 11618 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11619 S->getNextFunctionPrototypeIndex()); 11620 11621 // Add the parameter declaration into this scope. 11622 S->AddDecl(New); 11623 if (II) 11624 IdResolver.AddDecl(New); 11625 11626 ProcessDeclAttributes(S, New, D); 11627 11628 if (D.getDeclSpec().isModulePrivateSpecified()) 11629 Diag(New->getLocation(), diag::err_module_private_local) 11630 << 1 << New->getDeclName() 11631 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11632 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11633 11634 if (New->hasAttr<BlocksAttr>()) { 11635 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11636 } 11637 return New; 11638 } 11639 11640 /// \brief Synthesizes a variable for a parameter arising from a 11641 /// typedef. 11642 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11643 SourceLocation Loc, 11644 QualType T) { 11645 /* FIXME: setting StartLoc == Loc. 11646 Would it be worth to modify callers so as to provide proper source 11647 location for the unnamed parameters, embedding the parameter's type? */ 11648 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11649 T, Context.getTrivialTypeSourceInfo(T, Loc), 11650 SC_None, nullptr); 11651 Param->setImplicit(); 11652 return Param; 11653 } 11654 11655 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11656 // Don't diagnose unused-parameter errors in template instantiations; we 11657 // will already have done so in the template itself. 11658 if (inTemplateInstantiation()) 11659 return; 11660 11661 for (const ParmVarDecl *Parameter : Parameters) { 11662 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11663 !Parameter->hasAttr<UnusedAttr>()) { 11664 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11665 << Parameter->getDeclName(); 11666 } 11667 } 11668 } 11669 11670 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11671 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11672 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11673 return; 11674 11675 // Warn if the return value is pass-by-value and larger than the specified 11676 // threshold. 11677 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11678 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11679 if (Size > LangOpts.NumLargeByValueCopy) 11680 Diag(D->getLocation(), diag::warn_return_value_size) 11681 << D->getDeclName() << Size; 11682 } 11683 11684 // Warn if any parameter is pass-by-value and larger than the specified 11685 // threshold. 11686 for (const ParmVarDecl *Parameter : Parameters) { 11687 QualType T = Parameter->getType(); 11688 if (T->isDependentType() || !T.isPODType(Context)) 11689 continue; 11690 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11691 if (Size > LangOpts.NumLargeByValueCopy) 11692 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11693 << Parameter->getDeclName() << Size; 11694 } 11695 } 11696 11697 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11698 SourceLocation NameLoc, IdentifierInfo *Name, 11699 QualType T, TypeSourceInfo *TSInfo, 11700 StorageClass SC) { 11701 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11702 if (getLangOpts().ObjCAutoRefCount && 11703 T.getObjCLifetime() == Qualifiers::OCL_None && 11704 T->isObjCLifetimeType()) { 11705 11706 Qualifiers::ObjCLifetime lifetime; 11707 11708 // Special cases for arrays: 11709 // - if it's const, use __unsafe_unretained 11710 // - otherwise, it's an error 11711 if (T->isArrayType()) { 11712 if (!T.isConstQualified()) { 11713 DelayedDiagnostics.add( 11714 sema::DelayedDiagnostic::makeForbiddenType( 11715 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11716 } 11717 lifetime = Qualifiers::OCL_ExplicitNone; 11718 } else { 11719 lifetime = T->getObjCARCImplicitLifetime(); 11720 } 11721 T = Context.getLifetimeQualifiedType(T, lifetime); 11722 } 11723 11724 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11725 Context.getAdjustedParameterType(T), 11726 TSInfo, SC, nullptr); 11727 11728 // Parameters can not be abstract class types. 11729 // For record types, this is done by the AbstractClassUsageDiagnoser once 11730 // the class has been completely parsed. 11731 if (!CurContext->isRecord() && 11732 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11733 AbstractParamType)) 11734 New->setInvalidDecl(); 11735 11736 // Parameter declarators cannot be interface types. All ObjC objects are 11737 // passed by reference. 11738 if (T->isObjCObjectType()) { 11739 SourceLocation TypeEndLoc = 11740 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11741 Diag(NameLoc, 11742 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11743 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11744 T = Context.getObjCObjectPointerType(T); 11745 New->setType(T); 11746 } 11747 11748 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11749 // duration shall not be qualified by an address-space qualifier." 11750 // Since all parameters have automatic store duration, they can not have 11751 // an address space. 11752 if (T.getAddressSpace() != 0) { 11753 // OpenCL allows function arguments declared to be an array of a type 11754 // to be qualified with an address space. 11755 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11756 Diag(NameLoc, diag::err_arg_with_address_space); 11757 New->setInvalidDecl(); 11758 } 11759 } 11760 11761 return New; 11762 } 11763 11764 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11765 SourceLocation LocAfterDecls) { 11766 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11767 11768 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11769 // for a K&R function. 11770 if (!FTI.hasPrototype) { 11771 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11772 --i; 11773 if (FTI.Params[i].Param == nullptr) { 11774 SmallString<256> Code; 11775 llvm::raw_svector_ostream(Code) 11776 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11777 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11778 << FTI.Params[i].Ident 11779 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11780 11781 // Implicitly declare the argument as type 'int' for lack of a better 11782 // type. 11783 AttributeFactory attrs; 11784 DeclSpec DS(attrs); 11785 const char* PrevSpec; // unused 11786 unsigned DiagID; // unused 11787 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11788 DiagID, Context.getPrintingPolicy()); 11789 // Use the identifier location for the type source range. 11790 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11791 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11792 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11793 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11794 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11795 } 11796 } 11797 } 11798 } 11799 11800 Decl * 11801 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11802 MultiTemplateParamsArg TemplateParameterLists, 11803 SkipBodyInfo *SkipBody) { 11804 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11805 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11806 Scope *ParentScope = FnBodyScope->getParent(); 11807 11808 D.setFunctionDefinitionKind(FDK_Definition); 11809 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11810 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11811 } 11812 11813 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11814 Consumer.HandleInlineFunctionDefinition(D); 11815 } 11816 11817 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11818 const FunctionDecl*& PossibleZeroParamPrototype) { 11819 // Don't warn about invalid declarations. 11820 if (FD->isInvalidDecl()) 11821 return false; 11822 11823 // Or declarations that aren't global. 11824 if (!FD->isGlobal()) 11825 return false; 11826 11827 // Don't warn about C++ member functions. 11828 if (isa<CXXMethodDecl>(FD)) 11829 return false; 11830 11831 // Don't warn about 'main'. 11832 if (FD->isMain()) 11833 return false; 11834 11835 // Don't warn about inline functions. 11836 if (FD->isInlined()) 11837 return false; 11838 11839 // Don't warn about function templates. 11840 if (FD->getDescribedFunctionTemplate()) 11841 return false; 11842 11843 // Don't warn about function template specializations. 11844 if (FD->isFunctionTemplateSpecialization()) 11845 return false; 11846 11847 // Don't warn for OpenCL kernels. 11848 if (FD->hasAttr<OpenCLKernelAttr>()) 11849 return false; 11850 11851 // Don't warn on explicitly deleted functions. 11852 if (FD->isDeleted()) 11853 return false; 11854 11855 bool MissingPrototype = true; 11856 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11857 Prev; Prev = Prev->getPreviousDecl()) { 11858 // Ignore any declarations that occur in function or method 11859 // scope, because they aren't visible from the header. 11860 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11861 continue; 11862 11863 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11864 if (FD->getNumParams() == 0) 11865 PossibleZeroParamPrototype = Prev; 11866 break; 11867 } 11868 11869 return MissingPrototype; 11870 } 11871 11872 void 11873 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11874 const FunctionDecl *EffectiveDefinition, 11875 SkipBodyInfo *SkipBody) { 11876 const FunctionDecl *Definition = EffectiveDefinition; 11877 if (!Definition) 11878 if (!FD->isDefined(Definition)) 11879 return; 11880 11881 if (canRedefineFunction(Definition, getLangOpts())) 11882 return; 11883 11884 // Don't emit an error when this is redifinition of a typo-corrected 11885 // definition. 11886 if (TypoCorrectedFunctionDefinitions.count(Definition)) 11887 return; 11888 11889 // If we don't have a visible definition of the function, and it's inline or 11890 // a template, skip the new definition. 11891 if (SkipBody && !hasVisibleDefinition(Definition) && 11892 (Definition->getFormalLinkage() == InternalLinkage || 11893 Definition->isInlined() || 11894 Definition->getDescribedFunctionTemplate() || 11895 Definition->getNumTemplateParameterLists())) { 11896 SkipBody->ShouldSkip = true; 11897 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11898 makeMergedDefinitionVisible(TD); 11899 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 11900 return; 11901 } 11902 11903 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11904 Definition->getStorageClass() == SC_Extern) 11905 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11906 << FD->getDeclName() << getLangOpts().CPlusPlus; 11907 else 11908 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11909 11910 Diag(Definition->getLocation(), diag::note_previous_definition); 11911 FD->setInvalidDecl(); 11912 } 11913 11914 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11915 Sema &S) { 11916 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11917 11918 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11919 LSI->CallOperator = CallOperator; 11920 LSI->Lambda = LambdaClass; 11921 LSI->ReturnType = CallOperator->getReturnType(); 11922 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11923 11924 if (LCD == LCD_None) 11925 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11926 else if (LCD == LCD_ByCopy) 11927 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11928 else if (LCD == LCD_ByRef) 11929 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11930 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11931 11932 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11933 LSI->Mutable = !CallOperator->isConst(); 11934 11935 // Add the captures to the LSI so they can be noted as already 11936 // captured within tryCaptureVar. 11937 auto I = LambdaClass->field_begin(); 11938 for (const auto &C : LambdaClass->captures()) { 11939 if (C.capturesVariable()) { 11940 VarDecl *VD = C.getCapturedVar(); 11941 if (VD->isInitCapture()) 11942 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11943 QualType CaptureType = VD->getType(); 11944 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11945 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11946 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11947 /*EllipsisLoc*/C.isPackExpansion() 11948 ? C.getEllipsisLoc() : SourceLocation(), 11949 CaptureType, /*Expr*/ nullptr); 11950 11951 } else if (C.capturesThis()) { 11952 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11953 /*Expr*/ nullptr, 11954 C.getCaptureKind() == LCK_StarThis); 11955 } else { 11956 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11957 } 11958 ++I; 11959 } 11960 } 11961 11962 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11963 SkipBodyInfo *SkipBody) { 11964 if (!D) 11965 return D; 11966 FunctionDecl *FD = nullptr; 11967 11968 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11969 FD = FunTmpl->getTemplatedDecl(); 11970 else 11971 FD = cast<FunctionDecl>(D); 11972 11973 // Check for defining attributes before the check for redefinition. 11974 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 11975 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 11976 FD->dropAttr<AliasAttr>(); 11977 FD->setInvalidDecl(); 11978 } 11979 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 11980 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 11981 FD->dropAttr<IFuncAttr>(); 11982 FD->setInvalidDecl(); 11983 } 11984 11985 // See if this is a redefinition. 11986 if (!FD->isLateTemplateParsed()) { 11987 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11988 11989 // If we're skipping the body, we're done. Don't enter the scope. 11990 if (SkipBody && SkipBody->ShouldSkip) 11991 return D; 11992 } 11993 11994 // Mark this function as "will have a body eventually". This lets users to 11995 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 11996 // this function. 11997 FD->setWillHaveBody(); 11998 11999 // If we are instantiating a generic lambda call operator, push 12000 // a LambdaScopeInfo onto the function stack. But use the information 12001 // that's already been calculated (ActOnLambdaExpr) to prime the current 12002 // LambdaScopeInfo. 12003 // When the template operator is being specialized, the LambdaScopeInfo, 12004 // has to be properly restored so that tryCaptureVariable doesn't try 12005 // and capture any new variables. In addition when calculating potential 12006 // captures during transformation of nested lambdas, it is necessary to 12007 // have the LSI properly restored. 12008 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12009 assert(inTemplateInstantiation() && 12010 "There should be an active template instantiation on the stack " 12011 "when instantiating a generic lambda!"); 12012 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12013 } else { 12014 // Enter a new function scope 12015 PushFunctionScope(); 12016 } 12017 12018 // Builtin functions cannot be defined. 12019 if (unsigned BuiltinID = FD->getBuiltinID()) { 12020 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12021 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12022 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12023 FD->setInvalidDecl(); 12024 } 12025 } 12026 12027 // The return type of a function definition must be complete 12028 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12029 QualType ResultType = FD->getReturnType(); 12030 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12031 !FD->isInvalidDecl() && 12032 RequireCompleteType(FD->getLocation(), ResultType, 12033 diag::err_func_def_incomplete_result)) 12034 FD->setInvalidDecl(); 12035 12036 if (FnBodyScope) 12037 PushDeclContext(FnBodyScope, FD); 12038 12039 // Check the validity of our function parameters 12040 CheckParmsForFunctionDef(FD->parameters(), 12041 /*CheckParameterNames=*/true); 12042 12043 // Add non-parameter declarations already in the function to the current 12044 // scope. 12045 if (FnBodyScope) { 12046 for (Decl *NPD : FD->decls()) { 12047 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12048 if (!NonParmDecl) 12049 continue; 12050 assert(!isa<ParmVarDecl>(NonParmDecl) && 12051 "parameters should not be in newly created FD yet"); 12052 12053 // If the decl has a name, make it accessible in the current scope. 12054 if (NonParmDecl->getDeclName()) 12055 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12056 12057 // Similarly, dive into enums and fish their constants out, making them 12058 // accessible in this scope. 12059 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12060 for (auto *EI : ED->enumerators()) 12061 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12062 } 12063 } 12064 } 12065 12066 // Introduce our parameters into the function scope 12067 for (auto Param : FD->parameters()) { 12068 Param->setOwningFunction(FD); 12069 12070 // If this has an identifier, add it to the scope stack. 12071 if (Param->getIdentifier() && FnBodyScope) { 12072 CheckShadow(FnBodyScope, Param); 12073 12074 PushOnScopeChains(Param, FnBodyScope); 12075 } 12076 } 12077 12078 // Ensure that the function's exception specification is instantiated. 12079 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12080 ResolveExceptionSpec(D->getLocation(), FPT); 12081 12082 // dllimport cannot be applied to non-inline function definitions. 12083 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12084 !FD->isTemplateInstantiation()) { 12085 assert(!FD->hasAttr<DLLExportAttr>()); 12086 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12087 FD->setInvalidDecl(); 12088 return D; 12089 } 12090 // We want to attach documentation to original Decl (which might be 12091 // a function template). 12092 ActOnDocumentableDecl(D); 12093 if (getCurLexicalContext()->isObjCContainer() && 12094 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12095 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12096 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12097 12098 return D; 12099 } 12100 12101 /// \brief Given the set of return statements within a function body, 12102 /// compute the variables that are subject to the named return value 12103 /// optimization. 12104 /// 12105 /// Each of the variables that is subject to the named return value 12106 /// optimization will be marked as NRVO variables in the AST, and any 12107 /// return statement that has a marked NRVO variable as its NRVO candidate can 12108 /// use the named return value optimization. 12109 /// 12110 /// This function applies a very simplistic algorithm for NRVO: if every return 12111 /// statement in the scope of a variable has the same NRVO candidate, that 12112 /// candidate is an NRVO variable. 12113 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12114 ReturnStmt **Returns = Scope->Returns.data(); 12115 12116 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12117 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12118 if (!NRVOCandidate->isNRVOVariable()) 12119 Returns[I]->setNRVOCandidate(nullptr); 12120 } 12121 } 12122 } 12123 12124 bool Sema::canDelayFunctionBody(const Declarator &D) { 12125 // We can't delay parsing the body of a constexpr function template (yet). 12126 if (D.getDeclSpec().isConstexprSpecified()) 12127 return false; 12128 12129 // We can't delay parsing the body of a function template with a deduced 12130 // return type (yet). 12131 if (D.getDeclSpec().hasAutoTypeSpec()) { 12132 // If the placeholder introduces a non-deduced trailing return type, 12133 // we can still delay parsing it. 12134 if (D.getNumTypeObjects()) { 12135 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12136 if (Outer.Kind == DeclaratorChunk::Function && 12137 Outer.Fun.hasTrailingReturnType()) { 12138 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12139 return Ty.isNull() || !Ty->isUndeducedType(); 12140 } 12141 } 12142 return false; 12143 } 12144 12145 return true; 12146 } 12147 12148 bool Sema::canSkipFunctionBody(Decl *D) { 12149 // We cannot skip the body of a function (or function template) which is 12150 // constexpr, since we may need to evaluate its body in order to parse the 12151 // rest of the file. 12152 // We cannot skip the body of a function with an undeduced return type, 12153 // because any callers of that function need to know the type. 12154 if (const FunctionDecl *FD = D->getAsFunction()) 12155 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12156 return false; 12157 return Consumer.shouldSkipFunctionBody(D); 12158 } 12159 12160 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12161 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 12162 FD->setHasSkippedBody(); 12163 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 12164 MD->setHasSkippedBody(); 12165 return Decl; 12166 } 12167 12168 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12169 return ActOnFinishFunctionBody(D, BodyArg, false); 12170 } 12171 12172 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12173 bool IsInstantiation) { 12174 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12175 12176 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12177 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12178 12179 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12180 CheckCompletedCoroutineBody(FD, Body); 12181 12182 if (FD) { 12183 FD->setBody(Body); 12184 12185 if (getLangOpts().CPlusPlus14) { 12186 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12187 FD->getReturnType()->isUndeducedType()) { 12188 // If the function has a deduced result type but contains no 'return' 12189 // statements, the result type as written must be exactly 'auto', and 12190 // the deduced result type is 'void'. 12191 if (!FD->getReturnType()->getAs<AutoType>()) { 12192 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12193 << FD->getReturnType(); 12194 FD->setInvalidDecl(); 12195 } else { 12196 // Substitute 'void' for the 'auto' in the type. 12197 TypeLoc ResultType = getReturnTypeLoc(FD); 12198 Context.adjustDeducedFunctionResultType( 12199 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12200 } 12201 } 12202 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12203 // In C++11, we don't use 'auto' deduction rules for lambda call 12204 // operators because we don't support return type deduction. 12205 auto *LSI = getCurLambda(); 12206 if (LSI->HasImplicitReturnType) { 12207 deduceClosureReturnType(*LSI); 12208 12209 // C++11 [expr.prim.lambda]p4: 12210 // [...] if there are no return statements in the compound-statement 12211 // [the deduced type is] the type void 12212 QualType RetType = 12213 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12214 12215 // Update the return type to the deduced type. 12216 const FunctionProtoType *Proto = 12217 FD->getType()->getAs<FunctionProtoType>(); 12218 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12219 Proto->getExtProtoInfo())); 12220 } 12221 } 12222 12223 // The only way to be included in UndefinedButUsed is if there is an 12224 // ODR use before the definition. Avoid the expensive map lookup if this 12225 // is the first declaration. 12226 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 12227 if (!FD->isExternallyVisible()) 12228 UndefinedButUsed.erase(FD); 12229 else if (FD->isInlined() && 12230 !LangOpts.GNUInline && 12231 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 12232 UndefinedButUsed.erase(FD); 12233 } 12234 12235 // If the function implicitly returns zero (like 'main') or is naked, 12236 // don't complain about missing return statements. 12237 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12238 WP.disableCheckFallThrough(); 12239 12240 // MSVC permits the use of pure specifier (=0) on function definition, 12241 // defined at class scope, warn about this non-standard construct. 12242 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12243 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12244 12245 if (!FD->isInvalidDecl()) { 12246 // Don't diagnose unused parameters of defaulted or deleted functions. 12247 if (!FD->isDeleted() && !FD->isDefaulted()) 12248 DiagnoseUnusedParameters(FD->parameters()); 12249 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12250 FD->getReturnType(), FD); 12251 12252 // If this is a structor, we need a vtable. 12253 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12254 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12255 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12256 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12257 12258 // Try to apply the named return value optimization. We have to check 12259 // if we can do this here because lambdas keep return statements around 12260 // to deduce an implicit return type. 12261 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12262 !FD->isDependentContext()) 12263 computeNRVO(Body, getCurFunction()); 12264 } 12265 12266 // GNU warning -Wmissing-prototypes: 12267 // Warn if a global function is defined without a previous 12268 // prototype declaration. This warning is issued even if the 12269 // definition itself provides a prototype. The aim is to detect 12270 // global functions that fail to be declared in header files. 12271 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12272 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12273 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12274 12275 if (PossibleZeroParamPrototype) { 12276 // We found a declaration that is not a prototype, 12277 // but that could be a zero-parameter prototype 12278 if (TypeSourceInfo *TI = 12279 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12280 TypeLoc TL = TI->getTypeLoc(); 12281 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12282 Diag(PossibleZeroParamPrototype->getLocation(), 12283 diag::note_declaration_not_a_prototype) 12284 << PossibleZeroParamPrototype 12285 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12286 } 12287 } 12288 12289 // GNU warning -Wstrict-prototypes 12290 // Warn if K&R function is defined without a previous declaration. 12291 // This warning is issued only if the definition itself does not provide 12292 // a prototype. Only K&R definitions do not provide a prototype. 12293 // An empty list in a function declarator that is part of a definition 12294 // of that function specifies that the function has no parameters 12295 // (C99 6.7.5.3p14) 12296 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12297 !LangOpts.CPlusPlus) { 12298 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12299 TypeLoc TL = TI->getTypeLoc(); 12300 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12301 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1; 12302 } 12303 } 12304 12305 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12306 const CXXMethodDecl *KeyFunction; 12307 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12308 MD->isVirtual() && 12309 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12310 MD == KeyFunction->getCanonicalDecl()) { 12311 // Update the key-function state if necessary for this ABI. 12312 if (FD->isInlined() && 12313 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12314 Context.setNonKeyFunction(MD); 12315 12316 // If the newly-chosen key function is already defined, then we 12317 // need to mark the vtable as used retroactively. 12318 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12319 const FunctionDecl *Definition; 12320 if (KeyFunction && KeyFunction->isDefined(Definition)) 12321 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12322 } else { 12323 // We just defined they key function; mark the vtable as used. 12324 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12325 } 12326 } 12327 } 12328 12329 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12330 "Function parsing confused"); 12331 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12332 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12333 MD->setBody(Body); 12334 if (!MD->isInvalidDecl()) { 12335 DiagnoseUnusedParameters(MD->parameters()); 12336 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12337 MD->getReturnType(), MD); 12338 12339 if (Body) 12340 computeNRVO(Body, getCurFunction()); 12341 } 12342 if (getCurFunction()->ObjCShouldCallSuper) { 12343 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12344 << MD->getSelector().getAsString(); 12345 getCurFunction()->ObjCShouldCallSuper = false; 12346 } 12347 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12348 const ObjCMethodDecl *InitMethod = nullptr; 12349 bool isDesignated = 12350 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12351 assert(isDesignated && InitMethod); 12352 (void)isDesignated; 12353 12354 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12355 auto IFace = MD->getClassInterface(); 12356 if (!IFace) 12357 return false; 12358 auto SuperD = IFace->getSuperClass(); 12359 if (!SuperD) 12360 return false; 12361 return SuperD->getIdentifier() == 12362 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12363 }; 12364 // Don't issue this warning for unavailable inits or direct subclasses 12365 // of NSObject. 12366 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12367 Diag(MD->getLocation(), 12368 diag::warn_objc_designated_init_missing_super_call); 12369 Diag(InitMethod->getLocation(), 12370 diag::note_objc_designated_init_marked_here); 12371 } 12372 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12373 } 12374 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12375 // Don't issue this warning for unavaialable inits. 12376 if (!MD->isUnavailable()) 12377 Diag(MD->getLocation(), 12378 diag::warn_objc_secondary_init_missing_init_call); 12379 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12380 } 12381 } else { 12382 return nullptr; 12383 } 12384 12385 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12386 DiagnoseUnguardedAvailabilityViolations(dcl); 12387 12388 assert(!getCurFunction()->ObjCShouldCallSuper && 12389 "This should only be set for ObjC methods, which should have been " 12390 "handled in the block above."); 12391 12392 // Verify and clean out per-function state. 12393 if (Body && (!FD || !FD->isDefaulted())) { 12394 // C++ constructors that have function-try-blocks can't have return 12395 // statements in the handlers of that block. (C++ [except.handle]p14) 12396 // Verify this. 12397 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12398 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12399 12400 // Verify that gotos and switch cases don't jump into scopes illegally. 12401 if (getCurFunction()->NeedsScopeChecking() && 12402 !PP.isCodeCompletionEnabled()) 12403 DiagnoseInvalidJumps(Body); 12404 12405 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12406 if (!Destructor->getParent()->isDependentType()) 12407 CheckDestructor(Destructor); 12408 12409 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12410 Destructor->getParent()); 12411 } 12412 12413 // If any errors have occurred, clear out any temporaries that may have 12414 // been leftover. This ensures that these temporaries won't be picked up for 12415 // deletion in some later function. 12416 if (getDiagnostics().hasErrorOccurred() || 12417 getDiagnostics().getSuppressAllDiagnostics()) { 12418 DiscardCleanupsInEvaluationContext(); 12419 } 12420 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12421 !isa<FunctionTemplateDecl>(dcl)) { 12422 // Since the body is valid, issue any analysis-based warnings that are 12423 // enabled. 12424 ActivePolicy = &WP; 12425 } 12426 12427 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12428 (!CheckConstexprFunctionDecl(FD) || 12429 !CheckConstexprFunctionBody(FD, Body))) 12430 FD->setInvalidDecl(); 12431 12432 if (FD && FD->hasAttr<NakedAttr>()) { 12433 for (const Stmt *S : Body->children()) { 12434 // Allow local register variables without initializer as they don't 12435 // require prologue. 12436 bool RegisterVariables = false; 12437 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12438 for (const auto *Decl : DS->decls()) { 12439 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12440 RegisterVariables = 12441 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12442 if (!RegisterVariables) 12443 break; 12444 } 12445 } 12446 } 12447 if (RegisterVariables) 12448 continue; 12449 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12450 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12451 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12452 FD->setInvalidDecl(); 12453 break; 12454 } 12455 } 12456 } 12457 12458 assert(ExprCleanupObjects.size() == 12459 ExprEvalContexts.back().NumCleanupObjects && 12460 "Leftover temporaries in function"); 12461 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12462 assert(MaybeODRUseExprs.empty() && 12463 "Leftover expressions for odr-use checking"); 12464 } 12465 12466 if (!IsInstantiation) 12467 PopDeclContext(); 12468 12469 PopFunctionScopeInfo(ActivePolicy, dcl); 12470 // If any errors have occurred, clear out any temporaries that may have 12471 // been leftover. This ensures that these temporaries won't be picked up for 12472 // deletion in some later function. 12473 if (getDiagnostics().hasErrorOccurred()) { 12474 DiscardCleanupsInEvaluationContext(); 12475 } 12476 12477 return dcl; 12478 } 12479 12480 /// When we finish delayed parsing of an attribute, we must attach it to the 12481 /// relevant Decl. 12482 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12483 ParsedAttributes &Attrs) { 12484 // Always attach attributes to the underlying decl. 12485 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12486 D = TD->getTemplatedDecl(); 12487 ProcessDeclAttributeList(S, D, Attrs.getList()); 12488 12489 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12490 if (Method->isStatic()) 12491 checkThisInStaticMemberFunctionAttributes(Method); 12492 } 12493 12494 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12495 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12496 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12497 IdentifierInfo &II, Scope *S) { 12498 // Before we produce a declaration for an implicitly defined 12499 // function, see whether there was a locally-scoped declaration of 12500 // this name as a function or variable. If so, use that 12501 // (non-visible) declaration, and complain about it. 12502 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12503 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12504 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12505 return ExternCPrev; 12506 } 12507 12508 // Extension in C99. Legal in C90, but warn about it. 12509 unsigned diag_id; 12510 if (II.getName().startswith("__builtin_")) 12511 diag_id = diag::warn_builtin_unknown; 12512 else if (getLangOpts().C99) 12513 diag_id = diag::ext_implicit_function_decl; 12514 else 12515 diag_id = diag::warn_implicit_function_decl; 12516 Diag(Loc, diag_id) << &II; 12517 12518 // Because typo correction is expensive, only do it if the implicit 12519 // function declaration is going to be treated as an error. 12520 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12521 TypoCorrection Corrected; 12522 if (S && 12523 (Corrected = CorrectTypo( 12524 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12525 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12526 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12527 /*ErrorRecovery*/false); 12528 } 12529 12530 // Set a Declarator for the implicit definition: int foo(); 12531 const char *Dummy; 12532 AttributeFactory attrFactory; 12533 DeclSpec DS(attrFactory); 12534 unsigned DiagID; 12535 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12536 Context.getPrintingPolicy()); 12537 (void)Error; // Silence warning. 12538 assert(!Error && "Error setting up implicit decl!"); 12539 SourceLocation NoLoc; 12540 Declarator D(DS, Declarator::BlockContext); 12541 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12542 /*IsAmbiguous=*/false, 12543 /*LParenLoc=*/NoLoc, 12544 /*Params=*/nullptr, 12545 /*NumParams=*/0, 12546 /*EllipsisLoc=*/NoLoc, 12547 /*RParenLoc=*/NoLoc, 12548 /*TypeQuals=*/0, 12549 /*RefQualifierIsLvalueRef=*/true, 12550 /*RefQualifierLoc=*/NoLoc, 12551 /*ConstQualifierLoc=*/NoLoc, 12552 /*VolatileQualifierLoc=*/NoLoc, 12553 /*RestrictQualifierLoc=*/NoLoc, 12554 /*MutableLoc=*/NoLoc, 12555 EST_None, 12556 /*ESpecRange=*/SourceRange(), 12557 /*Exceptions=*/nullptr, 12558 /*ExceptionRanges=*/nullptr, 12559 /*NumExceptions=*/0, 12560 /*NoexceptExpr=*/nullptr, 12561 /*ExceptionSpecTokens=*/nullptr, 12562 /*DeclsInPrototype=*/None, 12563 Loc, Loc, D), 12564 DS.getAttributes(), 12565 SourceLocation()); 12566 D.SetIdentifier(&II, Loc); 12567 12568 // Insert this function into translation-unit scope. 12569 12570 DeclContext *PrevDC = CurContext; 12571 CurContext = Context.getTranslationUnitDecl(); 12572 12573 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12574 FD->setImplicit(); 12575 12576 CurContext = PrevDC; 12577 12578 AddKnownFunctionAttributes(FD); 12579 12580 return FD; 12581 } 12582 12583 /// \brief Adds any function attributes that we know a priori based on 12584 /// the declaration of this function. 12585 /// 12586 /// These attributes can apply both to implicitly-declared builtins 12587 /// (like __builtin___printf_chk) or to library-declared functions 12588 /// like NSLog or printf. 12589 /// 12590 /// We need to check for duplicate attributes both here and where user-written 12591 /// attributes are applied to declarations. 12592 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12593 if (FD->isInvalidDecl()) 12594 return; 12595 12596 // If this is a built-in function, map its builtin attributes to 12597 // actual attributes. 12598 if (unsigned BuiltinID = FD->getBuiltinID()) { 12599 // Handle printf-formatting attributes. 12600 unsigned FormatIdx; 12601 bool HasVAListArg; 12602 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12603 if (!FD->hasAttr<FormatAttr>()) { 12604 const char *fmt = "printf"; 12605 unsigned int NumParams = FD->getNumParams(); 12606 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12607 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12608 fmt = "NSString"; 12609 FD->addAttr(FormatAttr::CreateImplicit(Context, 12610 &Context.Idents.get(fmt), 12611 FormatIdx+1, 12612 HasVAListArg ? 0 : FormatIdx+2, 12613 FD->getLocation())); 12614 } 12615 } 12616 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12617 HasVAListArg)) { 12618 if (!FD->hasAttr<FormatAttr>()) 12619 FD->addAttr(FormatAttr::CreateImplicit(Context, 12620 &Context.Idents.get("scanf"), 12621 FormatIdx+1, 12622 HasVAListArg ? 0 : FormatIdx+2, 12623 FD->getLocation())); 12624 } 12625 12626 // Mark const if we don't care about errno and that is the only 12627 // thing preventing the function from being const. This allows 12628 // IRgen to use LLVM intrinsics for such functions. 12629 if (!getLangOpts().MathErrno && 12630 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12631 if (!FD->hasAttr<ConstAttr>()) 12632 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12633 } 12634 12635 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12636 !FD->hasAttr<ReturnsTwiceAttr>()) 12637 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12638 FD->getLocation())); 12639 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12640 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12641 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12642 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12643 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12644 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12645 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12646 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12647 // Add the appropriate attribute, depending on the CUDA compilation mode 12648 // and which target the builtin belongs to. For example, during host 12649 // compilation, aux builtins are __device__, while the rest are __host__. 12650 if (getLangOpts().CUDAIsDevice != 12651 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12652 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12653 else 12654 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12655 } 12656 } 12657 12658 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12659 // throw, add an implicit nothrow attribute to any extern "C" function we come 12660 // across. 12661 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12662 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12663 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12664 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12665 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12666 } 12667 12668 IdentifierInfo *Name = FD->getIdentifier(); 12669 if (!Name) 12670 return; 12671 if ((!getLangOpts().CPlusPlus && 12672 FD->getDeclContext()->isTranslationUnit()) || 12673 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12674 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12675 LinkageSpecDecl::lang_c)) { 12676 // Okay: this could be a libc/libm/Objective-C function we know 12677 // about. 12678 } else 12679 return; 12680 12681 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12682 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12683 // target-specific builtins, perhaps? 12684 if (!FD->hasAttr<FormatAttr>()) 12685 FD->addAttr(FormatAttr::CreateImplicit(Context, 12686 &Context.Idents.get("printf"), 2, 12687 Name->isStr("vasprintf") ? 0 : 3, 12688 FD->getLocation())); 12689 } 12690 12691 if (Name->isStr("__CFStringMakeConstantString")) { 12692 // We already have a __builtin___CFStringMakeConstantString, 12693 // but builds that use -fno-constant-cfstrings don't go through that. 12694 if (!FD->hasAttr<FormatArgAttr>()) 12695 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12696 FD->getLocation())); 12697 } 12698 } 12699 12700 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12701 TypeSourceInfo *TInfo) { 12702 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12703 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12704 12705 if (!TInfo) { 12706 assert(D.isInvalidType() && "no declarator info for valid type"); 12707 TInfo = Context.getTrivialTypeSourceInfo(T); 12708 } 12709 12710 // Scope manipulation handled by caller. 12711 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12712 D.getLocStart(), 12713 D.getIdentifierLoc(), 12714 D.getIdentifier(), 12715 TInfo); 12716 12717 // Bail out immediately if we have an invalid declaration. 12718 if (D.isInvalidType()) { 12719 NewTD->setInvalidDecl(); 12720 return NewTD; 12721 } 12722 12723 if (D.getDeclSpec().isModulePrivateSpecified()) { 12724 if (CurContext->isFunctionOrMethod()) 12725 Diag(NewTD->getLocation(), diag::err_module_private_local) 12726 << 2 << NewTD->getDeclName() 12727 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12728 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12729 else 12730 NewTD->setModulePrivate(); 12731 } 12732 12733 // C++ [dcl.typedef]p8: 12734 // If the typedef declaration defines an unnamed class (or 12735 // enum), the first typedef-name declared by the declaration 12736 // to be that class type (or enum type) is used to denote the 12737 // class type (or enum type) for linkage purposes only. 12738 // We need to check whether the type was declared in the declaration. 12739 switch (D.getDeclSpec().getTypeSpecType()) { 12740 case TST_enum: 12741 case TST_struct: 12742 case TST_interface: 12743 case TST_union: 12744 case TST_class: { 12745 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12746 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12747 break; 12748 } 12749 12750 default: 12751 break; 12752 } 12753 12754 return NewTD; 12755 } 12756 12757 /// \brief Check that this is a valid underlying type for an enum declaration. 12758 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12759 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12760 QualType T = TI->getType(); 12761 12762 if (T->isDependentType()) 12763 return false; 12764 12765 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12766 if (BT->isInteger()) 12767 return false; 12768 12769 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12770 return true; 12771 } 12772 12773 /// Check whether this is a valid redeclaration of a previous enumeration. 12774 /// \return true if the redeclaration was invalid. 12775 bool Sema::CheckEnumRedeclaration( 12776 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12777 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12778 bool IsFixed = !EnumUnderlyingTy.isNull(); 12779 12780 if (IsScoped != Prev->isScoped()) { 12781 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12782 << Prev->isScoped(); 12783 Diag(Prev->getLocation(), diag::note_previous_declaration); 12784 return true; 12785 } 12786 12787 if (IsFixed && Prev->isFixed()) { 12788 if (!EnumUnderlyingTy->isDependentType() && 12789 !Prev->getIntegerType()->isDependentType() && 12790 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12791 Prev->getIntegerType())) { 12792 // TODO: Highlight the underlying type of the redeclaration. 12793 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12794 << EnumUnderlyingTy << Prev->getIntegerType(); 12795 Diag(Prev->getLocation(), diag::note_previous_declaration) 12796 << Prev->getIntegerTypeRange(); 12797 return true; 12798 } 12799 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12800 ; 12801 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12802 ; 12803 } else if (IsFixed != Prev->isFixed()) { 12804 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12805 << Prev->isFixed(); 12806 Diag(Prev->getLocation(), diag::note_previous_declaration); 12807 return true; 12808 } 12809 12810 return false; 12811 } 12812 12813 /// \brief Get diagnostic %select index for tag kind for 12814 /// redeclaration diagnostic message. 12815 /// WARNING: Indexes apply to particular diagnostics only! 12816 /// 12817 /// \returns diagnostic %select index. 12818 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12819 switch (Tag) { 12820 case TTK_Struct: return 0; 12821 case TTK_Interface: return 1; 12822 case TTK_Class: return 2; 12823 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12824 } 12825 } 12826 12827 /// \brief Determine if tag kind is a class-key compatible with 12828 /// class for redeclaration (class, struct, or __interface). 12829 /// 12830 /// \returns true iff the tag kind is compatible. 12831 static bool isClassCompatTagKind(TagTypeKind Tag) 12832 { 12833 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12834 } 12835 12836 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12837 TagTypeKind TTK) { 12838 if (isa<TypedefDecl>(PrevDecl)) 12839 return NTK_Typedef; 12840 else if (isa<TypeAliasDecl>(PrevDecl)) 12841 return NTK_TypeAlias; 12842 else if (isa<ClassTemplateDecl>(PrevDecl)) 12843 return NTK_Template; 12844 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12845 return NTK_TypeAliasTemplate; 12846 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12847 return NTK_TemplateTemplateArgument; 12848 switch (TTK) { 12849 case TTK_Struct: 12850 case TTK_Interface: 12851 case TTK_Class: 12852 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12853 case TTK_Union: 12854 return NTK_NonUnion; 12855 case TTK_Enum: 12856 return NTK_NonEnum; 12857 } 12858 llvm_unreachable("invalid TTK"); 12859 } 12860 12861 /// \brief Determine whether a tag with a given kind is acceptable 12862 /// as a redeclaration of the given tag declaration. 12863 /// 12864 /// \returns true if the new tag kind is acceptable, false otherwise. 12865 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12866 TagTypeKind NewTag, bool isDefinition, 12867 SourceLocation NewTagLoc, 12868 const IdentifierInfo *Name) { 12869 // C++ [dcl.type.elab]p3: 12870 // The class-key or enum keyword present in the 12871 // elaborated-type-specifier shall agree in kind with the 12872 // declaration to which the name in the elaborated-type-specifier 12873 // refers. This rule also applies to the form of 12874 // elaborated-type-specifier that declares a class-name or 12875 // friend class since it can be construed as referring to the 12876 // definition of the class. Thus, in any 12877 // elaborated-type-specifier, the enum keyword shall be used to 12878 // refer to an enumeration (7.2), the union class-key shall be 12879 // used to refer to a union (clause 9), and either the class or 12880 // struct class-key shall be used to refer to a class (clause 9) 12881 // declared using the class or struct class-key. 12882 TagTypeKind OldTag = Previous->getTagKind(); 12883 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12884 if (OldTag == NewTag) 12885 return true; 12886 12887 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12888 // Warn about the struct/class tag mismatch. 12889 bool isTemplate = false; 12890 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12891 isTemplate = Record->getDescribedClassTemplate(); 12892 12893 if (inTemplateInstantiation()) { 12894 // In a template instantiation, do not offer fix-its for tag mismatches 12895 // since they usually mess up the template instead of fixing the problem. 12896 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12897 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12898 << getRedeclDiagFromTagKind(OldTag); 12899 return true; 12900 } 12901 12902 if (isDefinition) { 12903 // On definitions, check previous tags and issue a fix-it for each 12904 // one that doesn't match the current tag. 12905 if (Previous->getDefinition()) { 12906 // Don't suggest fix-its for redefinitions. 12907 return true; 12908 } 12909 12910 bool previousMismatch = false; 12911 for (auto I : Previous->redecls()) { 12912 if (I->getTagKind() != NewTag) { 12913 if (!previousMismatch) { 12914 previousMismatch = true; 12915 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12916 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12917 << getRedeclDiagFromTagKind(I->getTagKind()); 12918 } 12919 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12920 << getRedeclDiagFromTagKind(NewTag) 12921 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12922 TypeWithKeyword::getTagTypeKindName(NewTag)); 12923 } 12924 } 12925 return true; 12926 } 12927 12928 // Check for a previous definition. If current tag and definition 12929 // are same type, do nothing. If no definition, but disagree with 12930 // with previous tag type, give a warning, but no fix-it. 12931 const TagDecl *Redecl = Previous->getDefinition() ? 12932 Previous->getDefinition() : Previous; 12933 if (Redecl->getTagKind() == NewTag) { 12934 return true; 12935 } 12936 12937 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12938 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12939 << getRedeclDiagFromTagKind(OldTag); 12940 Diag(Redecl->getLocation(), diag::note_previous_use); 12941 12942 // If there is a previous definition, suggest a fix-it. 12943 if (Previous->getDefinition()) { 12944 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12945 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12946 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12947 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12948 } 12949 12950 return true; 12951 } 12952 return false; 12953 } 12954 12955 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12956 /// from an outer enclosing namespace or file scope inside a friend declaration. 12957 /// This should provide the commented out code in the following snippet: 12958 /// namespace N { 12959 /// struct X; 12960 /// namespace M { 12961 /// struct Y { friend struct /*N::*/ X; }; 12962 /// } 12963 /// } 12964 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12965 SourceLocation NameLoc) { 12966 // While the decl is in a namespace, do repeated lookup of that name and see 12967 // if we get the same namespace back. If we do not, continue until 12968 // translation unit scope, at which point we have a fully qualified NNS. 12969 SmallVector<IdentifierInfo *, 4> Namespaces; 12970 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12971 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12972 // This tag should be declared in a namespace, which can only be enclosed by 12973 // other namespaces. Bail if there's an anonymous namespace in the chain. 12974 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12975 if (!Namespace || Namespace->isAnonymousNamespace()) 12976 return FixItHint(); 12977 IdentifierInfo *II = Namespace->getIdentifier(); 12978 Namespaces.push_back(II); 12979 NamedDecl *Lookup = SemaRef.LookupSingleName( 12980 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12981 if (Lookup == Namespace) 12982 break; 12983 } 12984 12985 // Once we have all the namespaces, reverse them to go outermost first, and 12986 // build an NNS. 12987 SmallString<64> Insertion; 12988 llvm::raw_svector_ostream OS(Insertion); 12989 if (DC->isTranslationUnit()) 12990 OS << "::"; 12991 std::reverse(Namespaces.begin(), Namespaces.end()); 12992 for (auto *II : Namespaces) 12993 OS << II->getName() << "::"; 12994 return FixItHint::CreateInsertion(NameLoc, Insertion); 12995 } 12996 12997 /// \brief Determine whether a tag originally declared in context \p OldDC can 12998 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12999 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13000 /// using-declaration). 13001 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13002 DeclContext *NewDC) { 13003 OldDC = OldDC->getRedeclContext(); 13004 NewDC = NewDC->getRedeclContext(); 13005 13006 if (OldDC->Equals(NewDC)) 13007 return true; 13008 13009 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13010 // encloses the other). 13011 if (S.getLangOpts().MSVCCompat && 13012 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13013 return true; 13014 13015 return false; 13016 } 13017 13018 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13019 /// former case, Name will be non-null. In the later case, Name will be null. 13020 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13021 /// reference/declaration/definition of a tag. 13022 /// 13023 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13024 /// trailing-type-specifier) other than one in an alias-declaration. 13025 /// 13026 /// \param SkipBody If non-null, will be set to indicate if the caller should 13027 /// skip the definition of this tag and treat it as if it were a declaration. 13028 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13029 SourceLocation KWLoc, CXXScopeSpec &SS, 13030 IdentifierInfo *Name, SourceLocation NameLoc, 13031 AttributeList *Attr, AccessSpecifier AS, 13032 SourceLocation ModulePrivateLoc, 13033 MultiTemplateParamsArg TemplateParameterLists, 13034 bool &OwnedDecl, bool &IsDependent, 13035 SourceLocation ScopedEnumKWLoc, 13036 bool ScopedEnumUsesClassTag, 13037 TypeResult UnderlyingType, 13038 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 13039 // If this is not a definition, it must have a name. 13040 IdentifierInfo *OrigName = Name; 13041 assert((Name != nullptr || TUK == TUK_Definition) && 13042 "Nameless record must be a definition!"); 13043 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13044 13045 OwnedDecl = false; 13046 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13047 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13048 13049 // FIXME: Check member specializations more carefully. 13050 bool isMemberSpecialization = false; 13051 bool Invalid = false; 13052 13053 // We only need to do this matching if we have template parameters 13054 // or a scope specifier, which also conveniently avoids this work 13055 // for non-C++ cases. 13056 if (TemplateParameterLists.size() > 0 || 13057 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13058 if (TemplateParameterList *TemplateParams = 13059 MatchTemplateParametersToScopeSpecifier( 13060 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13061 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13062 if (Kind == TTK_Enum) { 13063 Diag(KWLoc, diag::err_enum_template); 13064 return nullptr; 13065 } 13066 13067 if (TemplateParams->size() > 0) { 13068 // This is a declaration or definition of a class template (which may 13069 // be a member of another template). 13070 13071 if (Invalid) 13072 return nullptr; 13073 13074 OwnedDecl = false; 13075 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13076 SS, Name, NameLoc, Attr, 13077 TemplateParams, AS, 13078 ModulePrivateLoc, 13079 /*FriendLoc*/SourceLocation(), 13080 TemplateParameterLists.size()-1, 13081 TemplateParameterLists.data(), 13082 SkipBody); 13083 return Result.get(); 13084 } else { 13085 // The "template<>" header is extraneous. 13086 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13087 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13088 isMemberSpecialization = true; 13089 } 13090 } 13091 } 13092 13093 // Figure out the underlying type if this a enum declaration. We need to do 13094 // this early, because it's needed to detect if this is an incompatible 13095 // redeclaration. 13096 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13097 bool EnumUnderlyingIsImplicit = false; 13098 13099 if (Kind == TTK_Enum) { 13100 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 13101 // No underlying type explicitly specified, or we failed to parse the 13102 // type, default to int. 13103 EnumUnderlying = Context.IntTy.getTypePtr(); 13104 else if (UnderlyingType.get()) { 13105 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13106 // integral type; any cv-qualification is ignored. 13107 TypeSourceInfo *TI = nullptr; 13108 GetTypeFromParser(UnderlyingType.get(), &TI); 13109 EnumUnderlying = TI; 13110 13111 if (CheckEnumUnderlyingType(TI)) 13112 // Recover by falling back to int. 13113 EnumUnderlying = Context.IntTy.getTypePtr(); 13114 13115 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13116 UPPC_FixedUnderlyingType)) 13117 EnumUnderlying = Context.IntTy.getTypePtr(); 13118 13119 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13120 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 13121 // Microsoft enums are always of int type. 13122 EnumUnderlying = Context.IntTy.getTypePtr(); 13123 EnumUnderlyingIsImplicit = true; 13124 } 13125 } 13126 } 13127 13128 DeclContext *SearchDC = CurContext; 13129 DeclContext *DC = CurContext; 13130 bool isStdBadAlloc = false; 13131 bool isStdAlignValT = false; 13132 13133 RedeclarationKind Redecl = ForRedeclaration; 13134 if (TUK == TUK_Friend || TUK == TUK_Reference) 13135 Redecl = NotForRedeclaration; 13136 13137 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13138 if (Name && SS.isNotEmpty()) { 13139 // We have a nested-name tag ('struct foo::bar'). 13140 13141 // Check for invalid 'foo::'. 13142 if (SS.isInvalid()) { 13143 Name = nullptr; 13144 goto CreateNewDecl; 13145 } 13146 13147 // If this is a friend or a reference to a class in a dependent 13148 // context, don't try to make a decl for it. 13149 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13150 DC = computeDeclContext(SS, false); 13151 if (!DC) { 13152 IsDependent = true; 13153 return nullptr; 13154 } 13155 } else { 13156 DC = computeDeclContext(SS, true); 13157 if (!DC) { 13158 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13159 << SS.getRange(); 13160 return nullptr; 13161 } 13162 } 13163 13164 if (RequireCompleteDeclContext(SS, DC)) 13165 return nullptr; 13166 13167 SearchDC = DC; 13168 // Look-up name inside 'foo::'. 13169 LookupQualifiedName(Previous, DC); 13170 13171 if (Previous.isAmbiguous()) 13172 return nullptr; 13173 13174 if (Previous.empty()) { 13175 // Name lookup did not find anything. However, if the 13176 // nested-name-specifier refers to the current instantiation, 13177 // and that current instantiation has any dependent base 13178 // classes, we might find something at instantiation time: treat 13179 // this as a dependent elaborated-type-specifier. 13180 // But this only makes any sense for reference-like lookups. 13181 if (Previous.wasNotFoundInCurrentInstantiation() && 13182 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13183 IsDependent = true; 13184 return nullptr; 13185 } 13186 13187 // A tag 'foo::bar' must already exist. 13188 Diag(NameLoc, diag::err_not_tag_in_scope) 13189 << Kind << Name << DC << SS.getRange(); 13190 Name = nullptr; 13191 Invalid = true; 13192 goto CreateNewDecl; 13193 } 13194 } else if (Name) { 13195 // C++14 [class.mem]p14: 13196 // If T is the name of a class, then each of the following shall have a 13197 // name different from T: 13198 // -- every member of class T that is itself a type 13199 if (TUK != TUK_Reference && TUK != TUK_Friend && 13200 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13201 return nullptr; 13202 13203 // If this is a named struct, check to see if there was a previous forward 13204 // declaration or definition. 13205 // FIXME: We're looking into outer scopes here, even when we 13206 // shouldn't be. Doing so can result in ambiguities that we 13207 // shouldn't be diagnosing. 13208 LookupName(Previous, S); 13209 13210 // When declaring or defining a tag, ignore ambiguities introduced 13211 // by types using'ed into this scope. 13212 if (Previous.isAmbiguous() && 13213 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13214 LookupResult::Filter F = Previous.makeFilter(); 13215 while (F.hasNext()) { 13216 NamedDecl *ND = F.next(); 13217 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13218 SearchDC->getRedeclContext())) 13219 F.erase(); 13220 } 13221 F.done(); 13222 } 13223 13224 // C++11 [namespace.memdef]p3: 13225 // If the name in a friend declaration is neither qualified nor 13226 // a template-id and the declaration is a function or an 13227 // elaborated-type-specifier, the lookup to determine whether 13228 // the entity has been previously declared shall not consider 13229 // any scopes outside the innermost enclosing namespace. 13230 // 13231 // MSVC doesn't implement the above rule for types, so a friend tag 13232 // declaration may be a redeclaration of a type declared in an enclosing 13233 // scope. They do implement this rule for friend functions. 13234 // 13235 // Does it matter that this should be by scope instead of by 13236 // semantic context? 13237 if (!Previous.empty() && TUK == TUK_Friend) { 13238 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13239 LookupResult::Filter F = Previous.makeFilter(); 13240 bool FriendSawTagOutsideEnclosingNamespace = false; 13241 while (F.hasNext()) { 13242 NamedDecl *ND = F.next(); 13243 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13244 if (DC->isFileContext() && 13245 !EnclosingNS->Encloses(ND->getDeclContext())) { 13246 if (getLangOpts().MSVCCompat) 13247 FriendSawTagOutsideEnclosingNamespace = true; 13248 else 13249 F.erase(); 13250 } 13251 } 13252 F.done(); 13253 13254 // Diagnose this MSVC extension in the easy case where lookup would have 13255 // unambiguously found something outside the enclosing namespace. 13256 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13257 NamedDecl *ND = Previous.getFoundDecl(); 13258 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13259 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13260 } 13261 } 13262 13263 // Note: there used to be some attempt at recovery here. 13264 if (Previous.isAmbiguous()) 13265 return nullptr; 13266 13267 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13268 // FIXME: This makes sure that we ignore the contexts associated 13269 // with C structs, unions, and enums when looking for a matching 13270 // tag declaration or definition. See the similar lookup tweak 13271 // in Sema::LookupName; is there a better way to deal with this? 13272 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13273 SearchDC = SearchDC->getParent(); 13274 } 13275 } 13276 13277 if (Previous.isSingleResult() && 13278 Previous.getFoundDecl()->isTemplateParameter()) { 13279 // Maybe we will complain about the shadowed template parameter. 13280 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13281 // Just pretend that we didn't see the previous declaration. 13282 Previous.clear(); 13283 } 13284 13285 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13286 DC->Equals(getStdNamespace())) { 13287 if (Name->isStr("bad_alloc")) { 13288 // This is a declaration of or a reference to "std::bad_alloc". 13289 isStdBadAlloc = true; 13290 13291 // If std::bad_alloc has been implicitly declared (but made invisible to 13292 // name lookup), fill in this implicit declaration as the previous 13293 // declaration, so that the declarations get chained appropriately. 13294 if (Previous.empty() && StdBadAlloc) 13295 Previous.addDecl(getStdBadAlloc()); 13296 } else if (Name->isStr("align_val_t")) { 13297 isStdAlignValT = true; 13298 if (Previous.empty() && StdAlignValT) 13299 Previous.addDecl(getStdAlignValT()); 13300 } 13301 } 13302 13303 // If we didn't find a previous declaration, and this is a reference 13304 // (or friend reference), move to the correct scope. In C++, we 13305 // also need to do a redeclaration lookup there, just in case 13306 // there's a shadow friend decl. 13307 if (Name && Previous.empty() && 13308 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13309 if (Invalid) goto CreateNewDecl; 13310 assert(SS.isEmpty()); 13311 13312 if (TUK == TUK_Reference) { 13313 // C++ [basic.scope.pdecl]p5: 13314 // -- for an elaborated-type-specifier of the form 13315 // 13316 // class-key identifier 13317 // 13318 // if the elaborated-type-specifier is used in the 13319 // decl-specifier-seq or parameter-declaration-clause of a 13320 // function defined in namespace scope, the identifier is 13321 // declared as a class-name in the namespace that contains 13322 // the declaration; otherwise, except as a friend 13323 // declaration, the identifier is declared in the smallest 13324 // non-class, non-function-prototype scope that contains the 13325 // declaration. 13326 // 13327 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13328 // C structs and unions. 13329 // 13330 // It is an error in C++ to declare (rather than define) an enum 13331 // type, including via an elaborated type specifier. We'll 13332 // diagnose that later; for now, declare the enum in the same 13333 // scope as we would have picked for any other tag type. 13334 // 13335 // GNU C also supports this behavior as part of its incomplete 13336 // enum types extension, while GNU C++ does not. 13337 // 13338 // Find the context where we'll be declaring the tag. 13339 // FIXME: We would like to maintain the current DeclContext as the 13340 // lexical context, 13341 SearchDC = getTagInjectionContext(SearchDC); 13342 13343 // Find the scope where we'll be declaring the tag. 13344 S = getTagInjectionScope(S, getLangOpts()); 13345 } else { 13346 assert(TUK == TUK_Friend); 13347 // C++ [namespace.memdef]p3: 13348 // If a friend declaration in a non-local class first declares a 13349 // class or function, the friend class or function is a member of 13350 // the innermost enclosing namespace. 13351 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13352 } 13353 13354 // In C++, we need to do a redeclaration lookup to properly 13355 // diagnose some problems. 13356 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13357 // hidden declaration so that we don't get ambiguity errors when using a 13358 // type declared by an elaborated-type-specifier. In C that is not correct 13359 // and we should instead merge compatible types found by lookup. 13360 if (getLangOpts().CPlusPlus) { 13361 Previous.setRedeclarationKind(ForRedeclaration); 13362 LookupQualifiedName(Previous, SearchDC); 13363 } else { 13364 Previous.setRedeclarationKind(ForRedeclaration); 13365 LookupName(Previous, S); 13366 } 13367 } 13368 13369 // If we have a known previous declaration to use, then use it. 13370 if (Previous.empty() && SkipBody && SkipBody->Previous) 13371 Previous.addDecl(SkipBody->Previous); 13372 13373 if (!Previous.empty()) { 13374 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13375 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13376 13377 // It's okay to have a tag decl in the same scope as a typedef 13378 // which hides a tag decl in the same scope. Finding this 13379 // insanity with a redeclaration lookup can only actually happen 13380 // in C++. 13381 // 13382 // This is also okay for elaborated-type-specifiers, which is 13383 // technically forbidden by the current standard but which is 13384 // okay according to the likely resolution of an open issue; 13385 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13386 if (getLangOpts().CPlusPlus) { 13387 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13388 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13389 TagDecl *Tag = TT->getDecl(); 13390 if (Tag->getDeclName() == Name && 13391 Tag->getDeclContext()->getRedeclContext() 13392 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13393 PrevDecl = Tag; 13394 Previous.clear(); 13395 Previous.addDecl(Tag); 13396 Previous.resolveKind(); 13397 } 13398 } 13399 } 13400 } 13401 13402 // If this is a redeclaration of a using shadow declaration, it must 13403 // declare a tag in the same context. In MSVC mode, we allow a 13404 // redefinition if either context is within the other. 13405 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13406 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13407 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13408 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13409 !(OldTag && isAcceptableTagRedeclContext( 13410 *this, OldTag->getDeclContext(), SearchDC))) { 13411 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13412 Diag(Shadow->getTargetDecl()->getLocation(), 13413 diag::note_using_decl_target); 13414 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13415 << 0; 13416 // Recover by ignoring the old declaration. 13417 Previous.clear(); 13418 goto CreateNewDecl; 13419 } 13420 } 13421 13422 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13423 // If this is a use of a previous tag, or if the tag is already declared 13424 // in the same scope (so that the definition/declaration completes or 13425 // rementions the tag), reuse the decl. 13426 if (TUK == TUK_Reference || TUK == TUK_Friend || 13427 isDeclInScope(DirectPrevDecl, SearchDC, S, 13428 SS.isNotEmpty() || isMemberSpecialization)) { 13429 // Make sure that this wasn't declared as an enum and now used as a 13430 // struct or something similar. 13431 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13432 TUK == TUK_Definition, KWLoc, 13433 Name)) { 13434 bool SafeToContinue 13435 = (PrevTagDecl->getTagKind() != TTK_Enum && 13436 Kind != TTK_Enum); 13437 if (SafeToContinue) 13438 Diag(KWLoc, diag::err_use_with_wrong_tag) 13439 << Name 13440 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13441 PrevTagDecl->getKindName()); 13442 else 13443 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13444 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13445 13446 if (SafeToContinue) 13447 Kind = PrevTagDecl->getTagKind(); 13448 else { 13449 // Recover by making this an anonymous redefinition. 13450 Name = nullptr; 13451 Previous.clear(); 13452 Invalid = true; 13453 } 13454 } 13455 13456 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13457 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13458 13459 // If this is an elaborated-type-specifier for a scoped enumeration, 13460 // the 'class' keyword is not necessary and not permitted. 13461 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13462 if (ScopedEnum) 13463 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13464 << PrevEnum->isScoped() 13465 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13466 return PrevTagDecl; 13467 } 13468 13469 QualType EnumUnderlyingTy; 13470 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13471 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13472 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13473 EnumUnderlyingTy = QualType(T, 0); 13474 13475 // All conflicts with previous declarations are recovered by 13476 // returning the previous declaration, unless this is a definition, 13477 // in which case we want the caller to bail out. 13478 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13479 ScopedEnum, EnumUnderlyingTy, 13480 EnumUnderlyingIsImplicit, PrevEnum)) 13481 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13482 } 13483 13484 // C++11 [class.mem]p1: 13485 // A member shall not be declared twice in the member-specification, 13486 // except that a nested class or member class template can be declared 13487 // and then later defined. 13488 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13489 S->isDeclScope(PrevDecl)) { 13490 Diag(NameLoc, diag::ext_member_redeclared); 13491 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13492 } 13493 13494 if (!Invalid) { 13495 // If this is a use, just return the declaration we found, unless 13496 // we have attributes. 13497 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13498 if (Attr) { 13499 // FIXME: Diagnose these attributes. For now, we create a new 13500 // declaration to hold them. 13501 } else if (TUK == TUK_Reference && 13502 (PrevTagDecl->getFriendObjectKind() == 13503 Decl::FOK_Undeclared || 13504 PrevDecl->getOwningModule() != getCurrentModule()) && 13505 SS.isEmpty()) { 13506 // This declaration is a reference to an existing entity, but 13507 // has different visibility from that entity: it either makes 13508 // a friend visible or it makes a type visible in a new module. 13509 // In either case, create a new declaration. We only do this if 13510 // the declaration would have meant the same thing if no prior 13511 // declaration were found, that is, if it was found in the same 13512 // scope where we would have injected a declaration. 13513 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13514 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13515 return PrevTagDecl; 13516 // This is in the injected scope, create a new declaration in 13517 // that scope. 13518 S = getTagInjectionScope(S, getLangOpts()); 13519 } else { 13520 return PrevTagDecl; 13521 } 13522 } 13523 13524 // Diagnose attempts to redefine a tag. 13525 if (TUK == TUK_Definition) { 13526 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13527 // If we're defining a specialization and the previous definition 13528 // is from an implicit instantiation, don't emit an error 13529 // here; we'll catch this in the general case below. 13530 bool IsExplicitSpecializationAfterInstantiation = false; 13531 if (isMemberSpecialization) { 13532 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13533 IsExplicitSpecializationAfterInstantiation = 13534 RD->getTemplateSpecializationKind() != 13535 TSK_ExplicitSpecialization; 13536 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13537 IsExplicitSpecializationAfterInstantiation = 13538 ED->getTemplateSpecializationKind() != 13539 TSK_ExplicitSpecialization; 13540 } 13541 13542 NamedDecl *Hidden = nullptr; 13543 if (SkipBody && getLangOpts().CPlusPlus && 13544 !hasVisibleDefinition(Def, &Hidden)) { 13545 // There is a definition of this tag, but it is not visible. We 13546 // explicitly make use of C++'s one definition rule here, and 13547 // assume that this definition is identical to the hidden one 13548 // we already have. Make the existing definition visible and 13549 // use it in place of this one. 13550 SkipBody->ShouldSkip = true; 13551 makeMergedDefinitionVisible(Hidden); 13552 return Def; 13553 } else if (!IsExplicitSpecializationAfterInstantiation) { 13554 // A redeclaration in function prototype scope in C isn't 13555 // visible elsewhere, so merely issue a warning. 13556 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13557 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13558 else 13559 Diag(NameLoc, diag::err_redefinition) << Name; 13560 notePreviousDefinition(Def, 13561 NameLoc.isValid() ? NameLoc : KWLoc); 13562 // If this is a redefinition, recover by making this 13563 // struct be anonymous, which will make any later 13564 // references get the previous definition. 13565 Name = nullptr; 13566 Previous.clear(); 13567 Invalid = true; 13568 } 13569 } else { 13570 // If the type is currently being defined, complain 13571 // about a nested redefinition. 13572 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13573 if (TD->isBeingDefined()) { 13574 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13575 Diag(PrevTagDecl->getLocation(), 13576 diag::note_previous_definition); 13577 Name = nullptr; 13578 Previous.clear(); 13579 Invalid = true; 13580 } 13581 } 13582 13583 // Okay, this is definition of a previously declared or referenced 13584 // tag. We're going to create a new Decl for it. 13585 } 13586 13587 // Okay, we're going to make a redeclaration. If this is some kind 13588 // of reference, make sure we build the redeclaration in the same DC 13589 // as the original, and ignore the current access specifier. 13590 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13591 SearchDC = PrevTagDecl->getDeclContext(); 13592 AS = AS_none; 13593 } 13594 } 13595 // If we get here we have (another) forward declaration or we 13596 // have a definition. Just create a new decl. 13597 13598 } else { 13599 // If we get here, this is a definition of a new tag type in a nested 13600 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13601 // new decl/type. We set PrevDecl to NULL so that the entities 13602 // have distinct types. 13603 Previous.clear(); 13604 } 13605 // If we get here, we're going to create a new Decl. If PrevDecl 13606 // is non-NULL, it's a definition of the tag declared by 13607 // PrevDecl. If it's NULL, we have a new definition. 13608 13609 // Otherwise, PrevDecl is not a tag, but was found with tag 13610 // lookup. This is only actually possible in C++, where a few 13611 // things like templates still live in the tag namespace. 13612 } else { 13613 // Use a better diagnostic if an elaborated-type-specifier 13614 // found the wrong kind of type on the first 13615 // (non-redeclaration) lookup. 13616 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13617 !Previous.isForRedeclaration()) { 13618 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13619 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13620 << Kind; 13621 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13622 Invalid = true; 13623 13624 // Otherwise, only diagnose if the declaration is in scope. 13625 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13626 SS.isNotEmpty() || isMemberSpecialization)) { 13627 // do nothing 13628 13629 // Diagnose implicit declarations introduced by elaborated types. 13630 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13631 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13632 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13633 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13634 Invalid = true; 13635 13636 // Otherwise it's a declaration. Call out a particularly common 13637 // case here. 13638 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13639 unsigned Kind = 0; 13640 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13641 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13642 << Name << Kind << TND->getUnderlyingType(); 13643 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13644 Invalid = true; 13645 13646 // Otherwise, diagnose. 13647 } else { 13648 // The tag name clashes with something else in the target scope, 13649 // issue an error and recover by making this tag be anonymous. 13650 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13651 notePreviousDefinition(PrevDecl, NameLoc); 13652 Name = nullptr; 13653 Invalid = true; 13654 } 13655 13656 // The existing declaration isn't relevant to us; we're in a 13657 // new scope, so clear out the previous declaration. 13658 Previous.clear(); 13659 } 13660 } 13661 13662 CreateNewDecl: 13663 13664 TagDecl *PrevDecl = nullptr; 13665 if (Previous.isSingleResult()) 13666 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13667 13668 // If there is an identifier, use the location of the identifier as the 13669 // location of the decl, otherwise use the location of the struct/union 13670 // keyword. 13671 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13672 13673 // Otherwise, create a new declaration. If there is a previous 13674 // declaration of the same entity, the two will be linked via 13675 // PrevDecl. 13676 TagDecl *New; 13677 13678 bool IsForwardReference = false; 13679 if (Kind == TTK_Enum) { 13680 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13681 // enum X { A, B, C } D; D should chain to X. 13682 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13683 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13684 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13685 13686 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13687 StdAlignValT = cast<EnumDecl>(New); 13688 13689 // If this is an undefined enum, warn. 13690 if (TUK != TUK_Definition && !Invalid) { 13691 TagDecl *Def; 13692 if (!EnumUnderlyingIsImplicit && 13693 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13694 cast<EnumDecl>(New)->isFixed()) { 13695 // C++0x: 7.2p2: opaque-enum-declaration. 13696 // Conflicts are diagnosed above. Do nothing. 13697 } 13698 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13699 Diag(Loc, diag::ext_forward_ref_enum_def) 13700 << New; 13701 Diag(Def->getLocation(), diag::note_previous_definition); 13702 } else { 13703 unsigned DiagID = diag::ext_forward_ref_enum; 13704 if (getLangOpts().MSVCCompat) 13705 DiagID = diag::ext_ms_forward_ref_enum; 13706 else if (getLangOpts().CPlusPlus) 13707 DiagID = diag::err_forward_ref_enum; 13708 Diag(Loc, DiagID); 13709 13710 // If this is a forward-declared reference to an enumeration, make a 13711 // note of it; we won't actually be introducing the declaration into 13712 // the declaration context. 13713 if (TUK == TUK_Reference) 13714 IsForwardReference = true; 13715 } 13716 } 13717 13718 if (EnumUnderlying) { 13719 EnumDecl *ED = cast<EnumDecl>(New); 13720 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13721 ED->setIntegerTypeSourceInfo(TI); 13722 else 13723 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13724 ED->setPromotionType(ED->getIntegerType()); 13725 } 13726 } else { 13727 // struct/union/class 13728 13729 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13730 // struct X { int A; } D; D should chain to X. 13731 if (getLangOpts().CPlusPlus) { 13732 // FIXME: Look for a way to use RecordDecl for simple structs. 13733 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13734 cast_or_null<CXXRecordDecl>(PrevDecl)); 13735 13736 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13737 StdBadAlloc = cast<CXXRecordDecl>(New); 13738 } else 13739 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13740 cast_or_null<RecordDecl>(PrevDecl)); 13741 } 13742 13743 // C++11 [dcl.type]p3: 13744 // A type-specifier-seq shall not define a class or enumeration [...]. 13745 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13746 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13747 << Context.getTagDeclType(New); 13748 Invalid = true; 13749 } 13750 13751 // Maybe add qualifier info. 13752 if (SS.isNotEmpty()) { 13753 if (SS.isSet()) { 13754 // If this is either a declaration or a definition, check the 13755 // nested-name-specifier against the current context. We don't do this 13756 // for explicit specializations, because they have similar checking 13757 // (with more specific diagnostics) in the call to 13758 // CheckMemberSpecialization, below. 13759 if (!isMemberSpecialization && 13760 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13761 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13762 Invalid = true; 13763 13764 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13765 if (TemplateParameterLists.size() > 0) { 13766 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13767 } 13768 } 13769 else 13770 Invalid = true; 13771 } 13772 13773 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13774 // Add alignment attributes if necessary; these attributes are checked when 13775 // the ASTContext lays out the structure. 13776 // 13777 // It is important for implementing the correct semantics that this 13778 // happen here (in act on tag decl). The #pragma pack stack is 13779 // maintained as a result of parser callbacks which can occur at 13780 // many points during the parsing of a struct declaration (because 13781 // the #pragma tokens are effectively skipped over during the 13782 // parsing of the struct). 13783 if (TUK == TUK_Definition) { 13784 AddAlignmentAttributesForRecord(RD); 13785 AddMsStructLayoutForRecord(RD); 13786 } 13787 } 13788 13789 if (ModulePrivateLoc.isValid()) { 13790 if (isMemberSpecialization) 13791 Diag(New->getLocation(), diag::err_module_private_specialization) 13792 << 2 13793 << FixItHint::CreateRemoval(ModulePrivateLoc); 13794 // __module_private__ does not apply to local classes. However, we only 13795 // diagnose this as an error when the declaration specifiers are 13796 // freestanding. Here, we just ignore the __module_private__. 13797 else if (!SearchDC->isFunctionOrMethod()) 13798 New->setModulePrivate(); 13799 } 13800 13801 // If this is a specialization of a member class (of a class template), 13802 // check the specialization. 13803 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 13804 Invalid = true; 13805 13806 // If we're declaring or defining a tag in function prototype scope in C, 13807 // note that this type can only be used within the function and add it to 13808 // the list of decls to inject into the function definition scope. 13809 if ((Name || Kind == TTK_Enum) && 13810 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13811 if (getLangOpts().CPlusPlus) { 13812 // C++ [dcl.fct]p6: 13813 // Types shall not be defined in return or parameter types. 13814 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13815 Diag(Loc, diag::err_type_defined_in_param_type) 13816 << Name; 13817 Invalid = true; 13818 } 13819 } else if (!PrevDecl) { 13820 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13821 } 13822 } 13823 13824 if (Invalid) 13825 New->setInvalidDecl(); 13826 13827 // Set the lexical context. If the tag has a C++ scope specifier, the 13828 // lexical context will be different from the semantic context. 13829 New->setLexicalDeclContext(CurContext); 13830 13831 // Mark this as a friend decl if applicable. 13832 // In Microsoft mode, a friend declaration also acts as a forward 13833 // declaration so we always pass true to setObjectOfFriendDecl to make 13834 // the tag name visible. 13835 if (TUK == TUK_Friend) 13836 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13837 13838 // Set the access specifier. 13839 if (!Invalid && SearchDC->isRecord()) 13840 SetMemberAccessSpecifier(New, PrevDecl, AS); 13841 13842 if (TUK == TUK_Definition) 13843 New->startDefinition(); 13844 13845 if (Attr) 13846 ProcessDeclAttributeList(S, New, Attr); 13847 AddPragmaAttributes(S, New); 13848 13849 // If this has an identifier, add it to the scope stack. 13850 if (TUK == TUK_Friend) { 13851 // We might be replacing an existing declaration in the lookup tables; 13852 // if so, borrow its access specifier. 13853 if (PrevDecl) 13854 New->setAccess(PrevDecl->getAccess()); 13855 13856 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13857 DC->makeDeclVisibleInContext(New); 13858 if (Name) // can be null along some error paths 13859 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13860 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13861 } else if (Name) { 13862 S = getNonFieldDeclScope(S); 13863 PushOnScopeChains(New, S, !IsForwardReference); 13864 if (IsForwardReference) 13865 SearchDC->makeDeclVisibleInContext(New); 13866 } else { 13867 CurContext->addDecl(New); 13868 } 13869 13870 // If this is the C FILE type, notify the AST context. 13871 if (IdentifierInfo *II = New->getIdentifier()) 13872 if (!New->isInvalidDecl() && 13873 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13874 II->isStr("FILE")) 13875 Context.setFILEDecl(New); 13876 13877 if (PrevDecl) 13878 mergeDeclAttributes(New, PrevDecl); 13879 13880 // If there's a #pragma GCC visibility in scope, set the visibility of this 13881 // record. 13882 AddPushedVisibilityAttribute(New); 13883 13884 if (isMemberSpecialization && !New->isInvalidDecl()) 13885 CompleteMemberSpecialization(New, Previous); 13886 13887 OwnedDecl = true; 13888 // In C++, don't return an invalid declaration. We can't recover well from 13889 // the cases where we make the type anonymous. 13890 if (Invalid && getLangOpts().CPlusPlus) { 13891 if (New->isBeingDefined()) 13892 if (auto RD = dyn_cast<RecordDecl>(New)) 13893 RD->completeDefinition(); 13894 return nullptr; 13895 } else { 13896 return New; 13897 } 13898 } 13899 13900 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13901 AdjustDeclIfTemplate(TagD); 13902 TagDecl *Tag = cast<TagDecl>(TagD); 13903 13904 // Enter the tag context. 13905 PushDeclContext(S, Tag); 13906 13907 ActOnDocumentableDecl(TagD); 13908 13909 // If there's a #pragma GCC visibility in scope, set the visibility of this 13910 // record. 13911 AddPushedVisibilityAttribute(Tag); 13912 } 13913 13914 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13915 assert(isa<ObjCContainerDecl>(IDecl) && 13916 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13917 DeclContext *OCD = cast<DeclContext>(IDecl); 13918 assert(getContainingDC(OCD) == CurContext && 13919 "The next DeclContext should be lexically contained in the current one."); 13920 CurContext = OCD; 13921 return IDecl; 13922 } 13923 13924 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13925 SourceLocation FinalLoc, 13926 bool IsFinalSpelledSealed, 13927 SourceLocation LBraceLoc) { 13928 AdjustDeclIfTemplate(TagD); 13929 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13930 13931 FieldCollector->StartClass(); 13932 13933 if (!Record->getIdentifier()) 13934 return; 13935 13936 if (FinalLoc.isValid()) 13937 Record->addAttr(new (Context) 13938 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13939 13940 // C++ [class]p2: 13941 // [...] The class-name is also inserted into the scope of the 13942 // class itself; this is known as the injected-class-name. For 13943 // purposes of access checking, the injected-class-name is treated 13944 // as if it were a public member name. 13945 CXXRecordDecl *InjectedClassName 13946 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13947 Record->getLocStart(), Record->getLocation(), 13948 Record->getIdentifier(), 13949 /*PrevDecl=*/nullptr, 13950 /*DelayTypeCreation=*/true); 13951 Context.getTypeDeclType(InjectedClassName, Record); 13952 InjectedClassName->setImplicit(); 13953 InjectedClassName->setAccess(AS_public); 13954 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13955 InjectedClassName->setDescribedClassTemplate(Template); 13956 PushOnScopeChains(InjectedClassName, S); 13957 assert(InjectedClassName->isInjectedClassName() && 13958 "Broken injected-class-name"); 13959 } 13960 13961 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13962 SourceRange BraceRange) { 13963 AdjustDeclIfTemplate(TagD); 13964 TagDecl *Tag = cast<TagDecl>(TagD); 13965 Tag->setBraceRange(BraceRange); 13966 13967 // Make sure we "complete" the definition even it is invalid. 13968 if (Tag->isBeingDefined()) { 13969 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13970 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13971 RD->completeDefinition(); 13972 } 13973 13974 if (isa<CXXRecordDecl>(Tag)) { 13975 FieldCollector->FinishClass(); 13976 } 13977 13978 // Exit this scope of this tag's definition. 13979 PopDeclContext(); 13980 13981 if (getCurLexicalContext()->isObjCContainer() && 13982 Tag->getDeclContext()->isFileContext()) 13983 Tag->setTopLevelDeclInObjCContainer(); 13984 13985 // Notify the consumer that we've defined a tag. 13986 if (!Tag->isInvalidDecl()) 13987 Consumer.HandleTagDeclDefinition(Tag); 13988 } 13989 13990 void Sema::ActOnObjCContainerFinishDefinition() { 13991 // Exit this scope of this interface definition. 13992 PopDeclContext(); 13993 } 13994 13995 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13996 assert(DC == CurContext && "Mismatch of container contexts"); 13997 OriginalLexicalContext = DC; 13998 ActOnObjCContainerFinishDefinition(); 13999 } 14000 14001 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14002 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14003 OriginalLexicalContext = nullptr; 14004 } 14005 14006 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14007 AdjustDeclIfTemplate(TagD); 14008 TagDecl *Tag = cast<TagDecl>(TagD); 14009 Tag->setInvalidDecl(); 14010 14011 // Make sure we "complete" the definition even it is invalid. 14012 if (Tag->isBeingDefined()) { 14013 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14014 RD->completeDefinition(); 14015 } 14016 14017 // We're undoing ActOnTagStartDefinition here, not 14018 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14019 // the FieldCollector. 14020 14021 PopDeclContext(); 14022 } 14023 14024 // Note that FieldName may be null for anonymous bitfields. 14025 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14026 IdentifierInfo *FieldName, 14027 QualType FieldTy, bool IsMsStruct, 14028 Expr *BitWidth, bool *ZeroWidth) { 14029 // Default to true; that shouldn't confuse checks for emptiness 14030 if (ZeroWidth) 14031 *ZeroWidth = true; 14032 14033 // C99 6.7.2.1p4 - verify the field type. 14034 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14035 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14036 // Handle incomplete types with specific error. 14037 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14038 return ExprError(); 14039 if (FieldName) 14040 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14041 << FieldName << FieldTy << BitWidth->getSourceRange(); 14042 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14043 << FieldTy << BitWidth->getSourceRange(); 14044 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14045 UPPC_BitFieldWidth)) 14046 return ExprError(); 14047 14048 // If the bit-width is type- or value-dependent, don't try to check 14049 // it now. 14050 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14051 return BitWidth; 14052 14053 llvm::APSInt Value; 14054 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14055 if (ICE.isInvalid()) 14056 return ICE; 14057 BitWidth = ICE.get(); 14058 14059 if (Value != 0 && ZeroWidth) 14060 *ZeroWidth = false; 14061 14062 // Zero-width bitfield is ok for anonymous field. 14063 if (Value == 0 && FieldName) 14064 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14065 14066 if (Value.isSigned() && Value.isNegative()) { 14067 if (FieldName) 14068 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14069 << FieldName << Value.toString(10); 14070 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14071 << Value.toString(10); 14072 } 14073 14074 if (!FieldTy->isDependentType()) { 14075 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14076 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14077 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14078 14079 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14080 // ABI. 14081 bool CStdConstraintViolation = 14082 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14083 bool MSBitfieldViolation = 14084 Value.ugt(TypeStorageSize) && 14085 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14086 if (CStdConstraintViolation || MSBitfieldViolation) { 14087 unsigned DiagWidth = 14088 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14089 if (FieldName) 14090 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14091 << FieldName << (unsigned)Value.getZExtValue() 14092 << !CStdConstraintViolation << DiagWidth; 14093 14094 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14095 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14096 << DiagWidth; 14097 } 14098 14099 // Warn on types where the user might conceivably expect to get all 14100 // specified bits as value bits: that's all integral types other than 14101 // 'bool'. 14102 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14103 if (FieldName) 14104 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14105 << FieldName << (unsigned)Value.getZExtValue() 14106 << (unsigned)TypeWidth; 14107 else 14108 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14109 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14110 } 14111 } 14112 14113 return BitWidth; 14114 } 14115 14116 /// ActOnField - Each field of a C struct/union is passed into this in order 14117 /// to create a FieldDecl object for it. 14118 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14119 Declarator &D, Expr *BitfieldWidth) { 14120 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14121 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14122 /*InitStyle=*/ICIS_NoInit, AS_public); 14123 return Res; 14124 } 14125 14126 /// HandleField - Analyze a field of a C struct or a C++ data member. 14127 /// 14128 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14129 SourceLocation DeclStart, 14130 Declarator &D, Expr *BitWidth, 14131 InClassInitStyle InitStyle, 14132 AccessSpecifier AS) { 14133 if (D.isDecompositionDeclarator()) { 14134 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14135 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14136 << Decomp.getSourceRange(); 14137 return nullptr; 14138 } 14139 14140 IdentifierInfo *II = D.getIdentifier(); 14141 SourceLocation Loc = DeclStart; 14142 if (II) Loc = D.getIdentifierLoc(); 14143 14144 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14145 QualType T = TInfo->getType(); 14146 if (getLangOpts().CPlusPlus) { 14147 CheckExtraCXXDefaultArguments(D); 14148 14149 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14150 UPPC_DataMemberType)) { 14151 D.setInvalidType(); 14152 T = Context.IntTy; 14153 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14154 } 14155 } 14156 14157 // TR 18037 does not allow fields to be declared with address spaces. 14158 if (T.getQualifiers().hasAddressSpace()) { 14159 Diag(Loc, diag::err_field_with_address_space); 14160 D.setInvalidType(); 14161 } 14162 14163 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14164 // used as structure or union field: image, sampler, event or block types. 14165 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14166 T->isSamplerT() || T->isBlockPointerType())) { 14167 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14168 D.setInvalidType(); 14169 } 14170 14171 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14172 14173 if (D.getDeclSpec().isInlineSpecified()) 14174 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14175 << getLangOpts().CPlusPlus1z; 14176 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14177 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14178 diag::err_invalid_thread) 14179 << DeclSpec::getSpecifierName(TSCS); 14180 14181 // Check to see if this name was declared as a member previously 14182 NamedDecl *PrevDecl = nullptr; 14183 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14184 LookupName(Previous, S); 14185 switch (Previous.getResultKind()) { 14186 case LookupResult::Found: 14187 case LookupResult::FoundUnresolvedValue: 14188 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14189 break; 14190 14191 case LookupResult::FoundOverloaded: 14192 PrevDecl = Previous.getRepresentativeDecl(); 14193 break; 14194 14195 case LookupResult::NotFound: 14196 case LookupResult::NotFoundInCurrentInstantiation: 14197 case LookupResult::Ambiguous: 14198 break; 14199 } 14200 Previous.suppressDiagnostics(); 14201 14202 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14203 // Maybe we will complain about the shadowed template parameter. 14204 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14205 // Just pretend that we didn't see the previous declaration. 14206 PrevDecl = nullptr; 14207 } 14208 14209 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14210 PrevDecl = nullptr; 14211 14212 bool Mutable 14213 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14214 SourceLocation TSSL = D.getLocStart(); 14215 FieldDecl *NewFD 14216 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14217 TSSL, AS, PrevDecl, &D); 14218 14219 if (NewFD->isInvalidDecl()) 14220 Record->setInvalidDecl(); 14221 14222 if (D.getDeclSpec().isModulePrivateSpecified()) 14223 NewFD->setModulePrivate(); 14224 14225 if (NewFD->isInvalidDecl() && PrevDecl) { 14226 // Don't introduce NewFD into scope; there's already something 14227 // with the same name in the same scope. 14228 } else if (II) { 14229 PushOnScopeChains(NewFD, S); 14230 } else 14231 Record->addDecl(NewFD); 14232 14233 return NewFD; 14234 } 14235 14236 /// \brief Build a new FieldDecl and check its well-formedness. 14237 /// 14238 /// This routine builds a new FieldDecl given the fields name, type, 14239 /// record, etc. \p PrevDecl should refer to any previous declaration 14240 /// with the same name and in the same scope as the field to be 14241 /// created. 14242 /// 14243 /// \returns a new FieldDecl. 14244 /// 14245 /// \todo The Declarator argument is a hack. It will be removed once 14246 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14247 TypeSourceInfo *TInfo, 14248 RecordDecl *Record, SourceLocation Loc, 14249 bool Mutable, Expr *BitWidth, 14250 InClassInitStyle InitStyle, 14251 SourceLocation TSSL, 14252 AccessSpecifier AS, NamedDecl *PrevDecl, 14253 Declarator *D) { 14254 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14255 bool InvalidDecl = false; 14256 if (D) InvalidDecl = D->isInvalidType(); 14257 14258 // If we receive a broken type, recover by assuming 'int' and 14259 // marking this declaration as invalid. 14260 if (T.isNull()) { 14261 InvalidDecl = true; 14262 T = Context.IntTy; 14263 } 14264 14265 QualType EltTy = Context.getBaseElementType(T); 14266 if (!EltTy->isDependentType()) { 14267 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14268 // Fields of incomplete type force their record to be invalid. 14269 Record->setInvalidDecl(); 14270 InvalidDecl = true; 14271 } else { 14272 NamedDecl *Def; 14273 EltTy->isIncompleteType(&Def); 14274 if (Def && Def->isInvalidDecl()) { 14275 Record->setInvalidDecl(); 14276 InvalidDecl = true; 14277 } 14278 } 14279 } 14280 14281 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14282 if (BitWidth && getLangOpts().OpenCL) { 14283 Diag(Loc, diag::err_opencl_bitfields); 14284 InvalidDecl = true; 14285 } 14286 14287 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14288 // than a variably modified type. 14289 if (!InvalidDecl && T->isVariablyModifiedType()) { 14290 bool SizeIsNegative; 14291 llvm::APSInt Oversized; 14292 14293 TypeSourceInfo *FixedTInfo = 14294 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14295 SizeIsNegative, 14296 Oversized); 14297 if (FixedTInfo) { 14298 Diag(Loc, diag::warn_illegal_constant_array_size); 14299 TInfo = FixedTInfo; 14300 T = FixedTInfo->getType(); 14301 } else { 14302 if (SizeIsNegative) 14303 Diag(Loc, diag::err_typecheck_negative_array_size); 14304 else if (Oversized.getBoolValue()) 14305 Diag(Loc, diag::err_array_too_large) 14306 << Oversized.toString(10); 14307 else 14308 Diag(Loc, diag::err_typecheck_field_variable_size); 14309 InvalidDecl = true; 14310 } 14311 } 14312 14313 // Fields can not have abstract class types 14314 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14315 diag::err_abstract_type_in_decl, 14316 AbstractFieldType)) 14317 InvalidDecl = true; 14318 14319 bool ZeroWidth = false; 14320 if (InvalidDecl) 14321 BitWidth = nullptr; 14322 // If this is declared as a bit-field, check the bit-field. 14323 if (BitWidth) { 14324 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14325 &ZeroWidth).get(); 14326 if (!BitWidth) { 14327 InvalidDecl = true; 14328 BitWidth = nullptr; 14329 ZeroWidth = false; 14330 } 14331 } 14332 14333 // Check that 'mutable' is consistent with the type of the declaration. 14334 if (!InvalidDecl && Mutable) { 14335 unsigned DiagID = 0; 14336 if (T->isReferenceType()) 14337 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14338 : diag::err_mutable_reference; 14339 else if (T.isConstQualified()) 14340 DiagID = diag::err_mutable_const; 14341 14342 if (DiagID) { 14343 SourceLocation ErrLoc = Loc; 14344 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14345 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14346 Diag(ErrLoc, DiagID); 14347 if (DiagID != diag::ext_mutable_reference) { 14348 Mutable = false; 14349 InvalidDecl = true; 14350 } 14351 } 14352 } 14353 14354 // C++11 [class.union]p8 (DR1460): 14355 // At most one variant member of a union may have a 14356 // brace-or-equal-initializer. 14357 if (InitStyle != ICIS_NoInit) 14358 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14359 14360 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14361 BitWidth, Mutable, InitStyle); 14362 if (InvalidDecl) 14363 NewFD->setInvalidDecl(); 14364 14365 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14366 Diag(Loc, diag::err_duplicate_member) << II; 14367 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14368 NewFD->setInvalidDecl(); 14369 } 14370 14371 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14372 if (Record->isUnion()) { 14373 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14374 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14375 if (RDecl->getDefinition()) { 14376 // C++ [class.union]p1: An object of a class with a non-trivial 14377 // constructor, a non-trivial copy constructor, a non-trivial 14378 // destructor, or a non-trivial copy assignment operator 14379 // cannot be a member of a union, nor can an array of such 14380 // objects. 14381 if (CheckNontrivialField(NewFD)) 14382 NewFD->setInvalidDecl(); 14383 } 14384 } 14385 14386 // C++ [class.union]p1: If a union contains a member of reference type, 14387 // the program is ill-formed, except when compiling with MSVC extensions 14388 // enabled. 14389 if (EltTy->isReferenceType()) { 14390 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14391 diag::ext_union_member_of_reference_type : 14392 diag::err_union_member_of_reference_type) 14393 << NewFD->getDeclName() << EltTy; 14394 if (!getLangOpts().MicrosoftExt) 14395 NewFD->setInvalidDecl(); 14396 } 14397 } 14398 } 14399 14400 // FIXME: We need to pass in the attributes given an AST 14401 // representation, not a parser representation. 14402 if (D) { 14403 // FIXME: The current scope is almost... but not entirely... correct here. 14404 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14405 14406 if (NewFD->hasAttrs()) 14407 CheckAlignasUnderalignment(NewFD); 14408 } 14409 14410 // In auto-retain/release, infer strong retension for fields of 14411 // retainable type. 14412 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14413 NewFD->setInvalidDecl(); 14414 14415 if (T.isObjCGCWeak()) 14416 Diag(Loc, diag::warn_attribute_weak_on_field); 14417 14418 NewFD->setAccess(AS); 14419 return NewFD; 14420 } 14421 14422 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14423 assert(FD); 14424 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14425 14426 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14427 return false; 14428 14429 QualType EltTy = Context.getBaseElementType(FD->getType()); 14430 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14431 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14432 if (RDecl->getDefinition()) { 14433 // We check for copy constructors before constructors 14434 // because otherwise we'll never get complaints about 14435 // copy constructors. 14436 14437 CXXSpecialMember member = CXXInvalid; 14438 // We're required to check for any non-trivial constructors. Since the 14439 // implicit default constructor is suppressed if there are any 14440 // user-declared constructors, we just need to check that there is a 14441 // trivial default constructor and a trivial copy constructor. (We don't 14442 // worry about move constructors here, since this is a C++98 check.) 14443 if (RDecl->hasNonTrivialCopyConstructor()) 14444 member = CXXCopyConstructor; 14445 else if (!RDecl->hasTrivialDefaultConstructor()) 14446 member = CXXDefaultConstructor; 14447 else if (RDecl->hasNonTrivialCopyAssignment()) 14448 member = CXXCopyAssignment; 14449 else if (RDecl->hasNonTrivialDestructor()) 14450 member = CXXDestructor; 14451 14452 if (member != CXXInvalid) { 14453 if (!getLangOpts().CPlusPlus11 && 14454 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14455 // Objective-C++ ARC: it is an error to have a non-trivial field of 14456 // a union. However, system headers in Objective-C programs 14457 // occasionally have Objective-C lifetime objects within unions, 14458 // and rather than cause the program to fail, we make those 14459 // members unavailable. 14460 SourceLocation Loc = FD->getLocation(); 14461 if (getSourceManager().isInSystemHeader(Loc)) { 14462 if (!FD->hasAttr<UnavailableAttr>()) 14463 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14464 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14465 return false; 14466 } 14467 } 14468 14469 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14470 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14471 diag::err_illegal_union_or_anon_struct_member) 14472 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14473 DiagnoseNontrivial(RDecl, member); 14474 return !getLangOpts().CPlusPlus11; 14475 } 14476 } 14477 } 14478 14479 return false; 14480 } 14481 14482 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14483 /// AST enum value. 14484 static ObjCIvarDecl::AccessControl 14485 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14486 switch (ivarVisibility) { 14487 default: llvm_unreachable("Unknown visitibility kind"); 14488 case tok::objc_private: return ObjCIvarDecl::Private; 14489 case tok::objc_public: return ObjCIvarDecl::Public; 14490 case tok::objc_protected: return ObjCIvarDecl::Protected; 14491 case tok::objc_package: return ObjCIvarDecl::Package; 14492 } 14493 } 14494 14495 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14496 /// in order to create an IvarDecl object for it. 14497 Decl *Sema::ActOnIvar(Scope *S, 14498 SourceLocation DeclStart, 14499 Declarator &D, Expr *BitfieldWidth, 14500 tok::ObjCKeywordKind Visibility) { 14501 14502 IdentifierInfo *II = D.getIdentifier(); 14503 Expr *BitWidth = (Expr*)BitfieldWidth; 14504 SourceLocation Loc = DeclStart; 14505 if (II) Loc = D.getIdentifierLoc(); 14506 14507 // FIXME: Unnamed fields can be handled in various different ways, for 14508 // example, unnamed unions inject all members into the struct namespace! 14509 14510 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14511 QualType T = TInfo->getType(); 14512 14513 if (BitWidth) { 14514 // 6.7.2.1p3, 6.7.2.1p4 14515 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14516 if (!BitWidth) 14517 D.setInvalidType(); 14518 } else { 14519 // Not a bitfield. 14520 14521 // validate II. 14522 14523 } 14524 if (T->isReferenceType()) { 14525 Diag(Loc, diag::err_ivar_reference_type); 14526 D.setInvalidType(); 14527 } 14528 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14529 // than a variably modified type. 14530 else if (T->isVariablyModifiedType()) { 14531 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14532 D.setInvalidType(); 14533 } 14534 14535 // Get the visibility (access control) for this ivar. 14536 ObjCIvarDecl::AccessControl ac = 14537 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14538 : ObjCIvarDecl::None; 14539 // Must set ivar's DeclContext to its enclosing interface. 14540 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14541 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14542 return nullptr; 14543 ObjCContainerDecl *EnclosingContext; 14544 if (ObjCImplementationDecl *IMPDecl = 14545 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14546 if (LangOpts.ObjCRuntime.isFragile()) { 14547 // Case of ivar declared in an implementation. Context is that of its class. 14548 EnclosingContext = IMPDecl->getClassInterface(); 14549 assert(EnclosingContext && "Implementation has no class interface!"); 14550 } 14551 else 14552 EnclosingContext = EnclosingDecl; 14553 } else { 14554 if (ObjCCategoryDecl *CDecl = 14555 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14556 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14557 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14558 return nullptr; 14559 } 14560 } 14561 EnclosingContext = EnclosingDecl; 14562 } 14563 14564 // Construct the decl. 14565 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14566 DeclStart, Loc, II, T, 14567 TInfo, ac, (Expr *)BitfieldWidth); 14568 14569 if (II) { 14570 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14571 ForRedeclaration); 14572 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14573 && !isa<TagDecl>(PrevDecl)) { 14574 Diag(Loc, diag::err_duplicate_member) << II; 14575 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14576 NewID->setInvalidDecl(); 14577 } 14578 } 14579 14580 // Process attributes attached to the ivar. 14581 ProcessDeclAttributes(S, NewID, D); 14582 14583 if (D.isInvalidType()) 14584 NewID->setInvalidDecl(); 14585 14586 // In ARC, infer 'retaining' for ivars of retainable type. 14587 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14588 NewID->setInvalidDecl(); 14589 14590 if (D.getDeclSpec().isModulePrivateSpecified()) 14591 NewID->setModulePrivate(); 14592 14593 if (II) { 14594 // FIXME: When interfaces are DeclContexts, we'll need to add 14595 // these to the interface. 14596 S->AddDecl(NewID); 14597 IdResolver.AddDecl(NewID); 14598 } 14599 14600 if (LangOpts.ObjCRuntime.isNonFragile() && 14601 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14602 Diag(Loc, diag::warn_ivars_in_interface); 14603 14604 return NewID; 14605 } 14606 14607 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14608 /// class and class extensions. For every class \@interface and class 14609 /// extension \@interface, if the last ivar is a bitfield of any type, 14610 /// then add an implicit `char :0` ivar to the end of that interface. 14611 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14612 SmallVectorImpl<Decl *> &AllIvarDecls) { 14613 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14614 return; 14615 14616 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14617 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14618 14619 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14620 return; 14621 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14622 if (!ID) { 14623 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14624 if (!CD->IsClassExtension()) 14625 return; 14626 } 14627 // No need to add this to end of @implementation. 14628 else 14629 return; 14630 } 14631 // All conditions are met. Add a new bitfield to the tail end of ivars. 14632 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14633 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14634 14635 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14636 DeclLoc, DeclLoc, nullptr, 14637 Context.CharTy, 14638 Context.getTrivialTypeSourceInfo(Context.CharTy, 14639 DeclLoc), 14640 ObjCIvarDecl::Private, BW, 14641 true); 14642 AllIvarDecls.push_back(Ivar); 14643 } 14644 14645 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14646 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14647 SourceLocation RBrac, AttributeList *Attr) { 14648 assert(EnclosingDecl && "missing record or interface decl"); 14649 14650 // If this is an Objective-C @implementation or category and we have 14651 // new fields here we should reset the layout of the interface since 14652 // it will now change. 14653 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14654 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14655 switch (DC->getKind()) { 14656 default: break; 14657 case Decl::ObjCCategory: 14658 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14659 break; 14660 case Decl::ObjCImplementation: 14661 Context. 14662 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14663 break; 14664 } 14665 } 14666 14667 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14668 14669 // Start counting up the number of named members; make sure to include 14670 // members of anonymous structs and unions in the total. 14671 unsigned NumNamedMembers = 0; 14672 if (Record) { 14673 for (const auto *I : Record->decls()) { 14674 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14675 if (IFD->getDeclName()) 14676 ++NumNamedMembers; 14677 } 14678 } 14679 14680 // Verify that all the fields are okay. 14681 SmallVector<FieldDecl*, 32> RecFields; 14682 14683 bool ObjCFieldLifetimeErrReported = false; 14684 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14685 i != end; ++i) { 14686 FieldDecl *FD = cast<FieldDecl>(*i); 14687 14688 // Get the type for the field. 14689 const Type *FDTy = FD->getType().getTypePtr(); 14690 14691 if (!FD->isAnonymousStructOrUnion()) { 14692 // Remember all fields written by the user. 14693 RecFields.push_back(FD); 14694 } 14695 14696 // If the field is already invalid for some reason, don't emit more 14697 // diagnostics about it. 14698 if (FD->isInvalidDecl()) { 14699 EnclosingDecl->setInvalidDecl(); 14700 continue; 14701 } 14702 14703 // C99 6.7.2.1p2: 14704 // A structure or union shall not contain a member with 14705 // incomplete or function type (hence, a structure shall not 14706 // contain an instance of itself, but may contain a pointer to 14707 // an instance of itself), except that the last member of a 14708 // structure with more than one named member may have incomplete 14709 // array type; such a structure (and any union containing, 14710 // possibly recursively, a member that is such a structure) 14711 // shall not be a member of a structure or an element of an 14712 // array. 14713 if (FDTy->isFunctionType()) { 14714 // Field declared as a function. 14715 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14716 << FD->getDeclName(); 14717 FD->setInvalidDecl(); 14718 EnclosingDecl->setInvalidDecl(); 14719 continue; 14720 } else if (FDTy->isIncompleteArrayType() && Record && 14721 ((i + 1 == Fields.end() && !Record->isUnion()) || 14722 ((getLangOpts().MicrosoftExt || 14723 getLangOpts().CPlusPlus) && 14724 (i + 1 == Fields.end() || Record->isUnion())))) { 14725 // Flexible array member. 14726 // Microsoft and g++ is more permissive regarding flexible array. 14727 // It will accept flexible array in union and also 14728 // as the sole element of a struct/class. 14729 unsigned DiagID = 0; 14730 if (Record->isUnion()) 14731 DiagID = getLangOpts().MicrosoftExt 14732 ? diag::ext_flexible_array_union_ms 14733 : getLangOpts().CPlusPlus 14734 ? diag::ext_flexible_array_union_gnu 14735 : diag::err_flexible_array_union; 14736 else if (NumNamedMembers < 1) 14737 DiagID = getLangOpts().MicrosoftExt 14738 ? diag::ext_flexible_array_empty_aggregate_ms 14739 : getLangOpts().CPlusPlus 14740 ? diag::ext_flexible_array_empty_aggregate_gnu 14741 : diag::err_flexible_array_empty_aggregate; 14742 14743 if (DiagID) 14744 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14745 << Record->getTagKind(); 14746 // While the layout of types that contain virtual bases is not specified 14747 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14748 // virtual bases after the derived members. This would make a flexible 14749 // array member declared at the end of an object not adjacent to the end 14750 // of the type. 14751 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14752 if (RD->getNumVBases() != 0) 14753 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14754 << FD->getDeclName() << Record->getTagKind(); 14755 if (!getLangOpts().C99) 14756 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14757 << FD->getDeclName() << Record->getTagKind(); 14758 14759 // If the element type has a non-trivial destructor, we would not 14760 // implicitly destroy the elements, so disallow it for now. 14761 // 14762 // FIXME: GCC allows this. We should probably either implicitly delete 14763 // the destructor of the containing class, or just allow this. 14764 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14765 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14766 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14767 << FD->getDeclName() << FD->getType(); 14768 FD->setInvalidDecl(); 14769 EnclosingDecl->setInvalidDecl(); 14770 continue; 14771 } 14772 // Okay, we have a legal flexible array member at the end of the struct. 14773 Record->setHasFlexibleArrayMember(true); 14774 } else if (!FDTy->isDependentType() && 14775 RequireCompleteType(FD->getLocation(), FD->getType(), 14776 diag::err_field_incomplete)) { 14777 // Incomplete type 14778 FD->setInvalidDecl(); 14779 EnclosingDecl->setInvalidDecl(); 14780 continue; 14781 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14782 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14783 // A type which contains a flexible array member is considered to be a 14784 // flexible array member. 14785 Record->setHasFlexibleArrayMember(true); 14786 if (!Record->isUnion()) { 14787 // If this is a struct/class and this is not the last element, reject 14788 // it. Note that GCC supports variable sized arrays in the middle of 14789 // structures. 14790 if (i + 1 != Fields.end()) 14791 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14792 << FD->getDeclName() << FD->getType(); 14793 else { 14794 // We support flexible arrays at the end of structs in 14795 // other structs as an extension. 14796 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14797 << FD->getDeclName(); 14798 } 14799 } 14800 } 14801 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14802 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14803 diag::err_abstract_type_in_decl, 14804 AbstractIvarType)) { 14805 // Ivars can not have abstract class types 14806 FD->setInvalidDecl(); 14807 } 14808 if (Record && FDTTy->getDecl()->hasObjectMember()) 14809 Record->setHasObjectMember(true); 14810 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14811 Record->setHasVolatileMember(true); 14812 } else if (FDTy->isObjCObjectType()) { 14813 /// A field cannot be an Objective-c object 14814 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14815 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14816 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14817 FD->setType(T); 14818 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 14819 Record && !ObjCFieldLifetimeErrReported && 14820 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14821 // It's an error in ARC or Weak if a field has lifetime. 14822 // We don't want to report this in a system header, though, 14823 // so we just make the field unavailable. 14824 // FIXME: that's really not sufficient; we need to make the type 14825 // itself invalid to, say, initialize or copy. 14826 QualType T = FD->getType(); 14827 if (T.hasNonTrivialObjCLifetime()) { 14828 SourceLocation loc = FD->getLocation(); 14829 if (getSourceManager().isInSystemHeader(loc)) { 14830 if (!FD->hasAttr<UnavailableAttr>()) { 14831 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14832 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14833 } 14834 } else { 14835 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14836 << T->isBlockPointerType() << Record->getTagKind(); 14837 } 14838 ObjCFieldLifetimeErrReported = true; 14839 } 14840 } else if (getLangOpts().ObjC1 && 14841 getLangOpts().getGC() != LangOptions::NonGC && 14842 Record && !Record->hasObjectMember()) { 14843 if (FD->getType()->isObjCObjectPointerType() || 14844 FD->getType().isObjCGCStrong()) 14845 Record->setHasObjectMember(true); 14846 else if (Context.getAsArrayType(FD->getType())) { 14847 QualType BaseType = Context.getBaseElementType(FD->getType()); 14848 if (BaseType->isRecordType() && 14849 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14850 Record->setHasObjectMember(true); 14851 else if (BaseType->isObjCObjectPointerType() || 14852 BaseType.isObjCGCStrong()) 14853 Record->setHasObjectMember(true); 14854 } 14855 } 14856 if (Record && FD->getType().isVolatileQualified()) 14857 Record->setHasVolatileMember(true); 14858 // Keep track of the number of named members. 14859 if (FD->getIdentifier()) 14860 ++NumNamedMembers; 14861 } 14862 14863 // Okay, we successfully defined 'Record'. 14864 if (Record) { 14865 bool Completed = false; 14866 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14867 if (!CXXRecord->isInvalidDecl()) { 14868 // Set access bits correctly on the directly-declared conversions. 14869 for (CXXRecordDecl::conversion_iterator 14870 I = CXXRecord->conversion_begin(), 14871 E = CXXRecord->conversion_end(); I != E; ++I) 14872 I.setAccess((*I)->getAccess()); 14873 } 14874 14875 if (!CXXRecord->isDependentType()) { 14876 if (CXXRecord->hasUserDeclaredDestructor()) { 14877 // Adjust user-defined destructor exception spec. 14878 if (getLangOpts().CPlusPlus11) 14879 AdjustDestructorExceptionSpec(CXXRecord, 14880 CXXRecord->getDestructor()); 14881 } 14882 14883 if (!CXXRecord->isInvalidDecl()) { 14884 // Add any implicitly-declared members to this class. 14885 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14886 14887 // If we have virtual base classes, we may end up finding multiple 14888 // final overriders for a given virtual function. Check for this 14889 // problem now. 14890 if (CXXRecord->getNumVBases()) { 14891 CXXFinalOverriderMap FinalOverriders; 14892 CXXRecord->getFinalOverriders(FinalOverriders); 14893 14894 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14895 MEnd = FinalOverriders.end(); 14896 M != MEnd; ++M) { 14897 for (OverridingMethods::iterator SO = M->second.begin(), 14898 SOEnd = M->second.end(); 14899 SO != SOEnd; ++SO) { 14900 assert(SO->second.size() > 0 && 14901 "Virtual function without overridding functions?"); 14902 if (SO->second.size() == 1) 14903 continue; 14904 14905 // C++ [class.virtual]p2: 14906 // In a derived class, if a virtual member function of a base 14907 // class subobject has more than one final overrider the 14908 // program is ill-formed. 14909 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14910 << (const NamedDecl *)M->first << Record; 14911 Diag(M->first->getLocation(), 14912 diag::note_overridden_virtual_function); 14913 for (OverridingMethods::overriding_iterator 14914 OM = SO->second.begin(), 14915 OMEnd = SO->second.end(); 14916 OM != OMEnd; ++OM) 14917 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14918 << (const NamedDecl *)M->first << OM->Method->getParent(); 14919 14920 Record->setInvalidDecl(); 14921 } 14922 } 14923 CXXRecord->completeDefinition(&FinalOverriders); 14924 Completed = true; 14925 } 14926 } 14927 } 14928 } 14929 14930 if (!Completed) 14931 Record->completeDefinition(); 14932 14933 // We may have deferred checking for a deleted destructor. Check now. 14934 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14935 auto *Dtor = CXXRecord->getDestructor(); 14936 if (Dtor && Dtor->isImplicit() && 14937 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14938 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14939 } 14940 14941 if (Record->hasAttrs()) { 14942 CheckAlignasUnderalignment(Record); 14943 14944 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14945 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14946 IA->getRange(), IA->getBestCase(), 14947 IA->getSemanticSpelling()); 14948 } 14949 14950 // Check if the structure/union declaration is a type that can have zero 14951 // size in C. For C this is a language extension, for C++ it may cause 14952 // compatibility problems. 14953 bool CheckForZeroSize; 14954 if (!getLangOpts().CPlusPlus) { 14955 CheckForZeroSize = true; 14956 } else { 14957 // For C++ filter out types that cannot be referenced in C code. 14958 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14959 CheckForZeroSize = 14960 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14961 !CXXRecord->isDependentType() && 14962 CXXRecord->isCLike(); 14963 } 14964 if (CheckForZeroSize) { 14965 bool ZeroSize = true; 14966 bool IsEmpty = true; 14967 unsigned NonBitFields = 0; 14968 for (RecordDecl::field_iterator I = Record->field_begin(), 14969 E = Record->field_end(); 14970 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14971 IsEmpty = false; 14972 if (I->isUnnamedBitfield()) { 14973 if (I->getBitWidthValue(Context) > 0) 14974 ZeroSize = false; 14975 } else { 14976 ++NonBitFields; 14977 QualType FieldType = I->getType(); 14978 if (FieldType->isIncompleteType() || 14979 !Context.getTypeSizeInChars(FieldType).isZero()) 14980 ZeroSize = false; 14981 } 14982 } 14983 14984 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14985 // allowed in C++, but warn if its declaration is inside 14986 // extern "C" block. 14987 if (ZeroSize) { 14988 Diag(RecLoc, getLangOpts().CPlusPlus ? 14989 diag::warn_zero_size_struct_union_in_extern_c : 14990 diag::warn_zero_size_struct_union_compat) 14991 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14992 } 14993 14994 // Structs without named members are extension in C (C99 6.7.2.1p7), 14995 // but are accepted by GCC. 14996 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14997 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14998 diag::ext_no_named_members_in_struct_union) 14999 << Record->isUnion(); 15000 } 15001 } 15002 } else { 15003 ObjCIvarDecl **ClsFields = 15004 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15005 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15006 ID->setEndOfDefinitionLoc(RBrac); 15007 // Add ivar's to class's DeclContext. 15008 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15009 ClsFields[i]->setLexicalDeclContext(ID); 15010 ID->addDecl(ClsFields[i]); 15011 } 15012 // Must enforce the rule that ivars in the base classes may not be 15013 // duplicates. 15014 if (ID->getSuperClass()) 15015 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15016 } else if (ObjCImplementationDecl *IMPDecl = 15017 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15018 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15019 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15020 // Ivar declared in @implementation never belongs to the implementation. 15021 // Only it is in implementation's lexical context. 15022 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15023 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15024 IMPDecl->setIvarLBraceLoc(LBrac); 15025 IMPDecl->setIvarRBraceLoc(RBrac); 15026 } else if (ObjCCategoryDecl *CDecl = 15027 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15028 // case of ivars in class extension; all other cases have been 15029 // reported as errors elsewhere. 15030 // FIXME. Class extension does not have a LocEnd field. 15031 // CDecl->setLocEnd(RBrac); 15032 // Add ivar's to class extension's DeclContext. 15033 // Diagnose redeclaration of private ivars. 15034 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15035 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15036 if (IDecl) { 15037 if (const ObjCIvarDecl *ClsIvar = 15038 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15039 Diag(ClsFields[i]->getLocation(), 15040 diag::err_duplicate_ivar_declaration); 15041 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15042 continue; 15043 } 15044 for (const auto *Ext : IDecl->known_extensions()) { 15045 if (const ObjCIvarDecl *ClsExtIvar 15046 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15047 Diag(ClsFields[i]->getLocation(), 15048 diag::err_duplicate_ivar_declaration); 15049 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15050 continue; 15051 } 15052 } 15053 } 15054 ClsFields[i]->setLexicalDeclContext(CDecl); 15055 CDecl->addDecl(ClsFields[i]); 15056 } 15057 CDecl->setIvarLBraceLoc(LBrac); 15058 CDecl->setIvarRBraceLoc(RBrac); 15059 } 15060 } 15061 15062 if (Attr) 15063 ProcessDeclAttributeList(S, Record, Attr); 15064 } 15065 15066 /// \brief Determine whether the given integral value is representable within 15067 /// the given type T. 15068 static bool isRepresentableIntegerValue(ASTContext &Context, 15069 llvm::APSInt &Value, 15070 QualType T) { 15071 assert(T->isIntegralType(Context) && "Integral type required!"); 15072 unsigned BitWidth = Context.getIntWidth(T); 15073 15074 if (Value.isUnsigned() || Value.isNonNegative()) { 15075 if (T->isSignedIntegerOrEnumerationType()) 15076 --BitWidth; 15077 return Value.getActiveBits() <= BitWidth; 15078 } 15079 return Value.getMinSignedBits() <= BitWidth; 15080 } 15081 15082 // \brief Given an integral type, return the next larger integral type 15083 // (or a NULL type of no such type exists). 15084 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15085 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15086 // enum checking below. 15087 assert(T->isIntegralType(Context) && "Integral type required!"); 15088 const unsigned NumTypes = 4; 15089 QualType SignedIntegralTypes[NumTypes] = { 15090 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15091 }; 15092 QualType UnsignedIntegralTypes[NumTypes] = { 15093 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15094 Context.UnsignedLongLongTy 15095 }; 15096 15097 unsigned BitWidth = Context.getTypeSize(T); 15098 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15099 : UnsignedIntegralTypes; 15100 for (unsigned I = 0; I != NumTypes; ++I) 15101 if (Context.getTypeSize(Types[I]) > BitWidth) 15102 return Types[I]; 15103 15104 return QualType(); 15105 } 15106 15107 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15108 EnumConstantDecl *LastEnumConst, 15109 SourceLocation IdLoc, 15110 IdentifierInfo *Id, 15111 Expr *Val) { 15112 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15113 llvm::APSInt EnumVal(IntWidth); 15114 QualType EltTy; 15115 15116 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15117 Val = nullptr; 15118 15119 if (Val) 15120 Val = DefaultLvalueConversion(Val).get(); 15121 15122 if (Val) { 15123 if (Enum->isDependentType() || Val->isTypeDependent()) 15124 EltTy = Context.DependentTy; 15125 else { 15126 SourceLocation ExpLoc; 15127 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15128 !getLangOpts().MSVCCompat) { 15129 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15130 // constant-expression in the enumerator-definition shall be a converted 15131 // constant expression of the underlying type. 15132 EltTy = Enum->getIntegerType(); 15133 ExprResult Converted = 15134 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15135 CCEK_Enumerator); 15136 if (Converted.isInvalid()) 15137 Val = nullptr; 15138 else 15139 Val = Converted.get(); 15140 } else if (!Val->isValueDependent() && 15141 !(Val = VerifyIntegerConstantExpression(Val, 15142 &EnumVal).get())) { 15143 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15144 } else { 15145 if (Enum->isFixed()) { 15146 EltTy = Enum->getIntegerType(); 15147 15148 // In Obj-C and Microsoft mode, require the enumeration value to be 15149 // representable in the underlying type of the enumeration. In C++11, 15150 // we perform a non-narrowing conversion as part of converted constant 15151 // expression checking. 15152 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15153 if (getLangOpts().MSVCCompat) { 15154 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15155 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15156 } else 15157 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15158 } else 15159 Val = ImpCastExprToType(Val, EltTy, 15160 EltTy->isBooleanType() ? 15161 CK_IntegralToBoolean : CK_IntegralCast) 15162 .get(); 15163 } else if (getLangOpts().CPlusPlus) { 15164 // C++11 [dcl.enum]p5: 15165 // If the underlying type is not fixed, the type of each enumerator 15166 // is the type of its initializing value: 15167 // - If an initializer is specified for an enumerator, the 15168 // initializing value has the same type as the expression. 15169 EltTy = Val->getType(); 15170 } else { 15171 // C99 6.7.2.2p2: 15172 // The expression that defines the value of an enumeration constant 15173 // shall be an integer constant expression that has a value 15174 // representable as an int. 15175 15176 // Complain if the value is not representable in an int. 15177 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15178 Diag(IdLoc, diag::ext_enum_value_not_int) 15179 << EnumVal.toString(10) << Val->getSourceRange() 15180 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15181 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15182 // Force the type of the expression to 'int'. 15183 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15184 } 15185 EltTy = Val->getType(); 15186 } 15187 } 15188 } 15189 } 15190 15191 if (!Val) { 15192 if (Enum->isDependentType()) 15193 EltTy = Context.DependentTy; 15194 else if (!LastEnumConst) { 15195 // C++0x [dcl.enum]p5: 15196 // If the underlying type is not fixed, the type of each enumerator 15197 // is the type of its initializing value: 15198 // - If no initializer is specified for the first enumerator, the 15199 // initializing value has an unspecified integral type. 15200 // 15201 // GCC uses 'int' for its unspecified integral type, as does 15202 // C99 6.7.2.2p3. 15203 if (Enum->isFixed()) { 15204 EltTy = Enum->getIntegerType(); 15205 } 15206 else { 15207 EltTy = Context.IntTy; 15208 } 15209 } else { 15210 // Assign the last value + 1. 15211 EnumVal = LastEnumConst->getInitVal(); 15212 ++EnumVal; 15213 EltTy = LastEnumConst->getType(); 15214 15215 // Check for overflow on increment. 15216 if (EnumVal < LastEnumConst->getInitVal()) { 15217 // C++0x [dcl.enum]p5: 15218 // If the underlying type is not fixed, the type of each enumerator 15219 // is the type of its initializing value: 15220 // 15221 // - Otherwise the type of the initializing value is the same as 15222 // the type of the initializing value of the preceding enumerator 15223 // unless the incremented value is not representable in that type, 15224 // in which case the type is an unspecified integral type 15225 // sufficient to contain the incremented value. If no such type 15226 // exists, the program is ill-formed. 15227 QualType T = getNextLargerIntegralType(Context, EltTy); 15228 if (T.isNull() || Enum->isFixed()) { 15229 // There is no integral type larger enough to represent this 15230 // value. Complain, then allow the value to wrap around. 15231 EnumVal = LastEnumConst->getInitVal(); 15232 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15233 ++EnumVal; 15234 if (Enum->isFixed()) 15235 // When the underlying type is fixed, this is ill-formed. 15236 Diag(IdLoc, diag::err_enumerator_wrapped) 15237 << EnumVal.toString(10) 15238 << EltTy; 15239 else 15240 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15241 << EnumVal.toString(10); 15242 } else { 15243 EltTy = T; 15244 } 15245 15246 // Retrieve the last enumerator's value, extent that type to the 15247 // type that is supposed to be large enough to represent the incremented 15248 // value, then increment. 15249 EnumVal = LastEnumConst->getInitVal(); 15250 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15251 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15252 ++EnumVal; 15253 15254 // If we're not in C++, diagnose the overflow of enumerator values, 15255 // which in C99 means that the enumerator value is not representable in 15256 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15257 // permits enumerator values that are representable in some larger 15258 // integral type. 15259 if (!getLangOpts().CPlusPlus && !T.isNull()) 15260 Diag(IdLoc, diag::warn_enum_value_overflow); 15261 } else if (!getLangOpts().CPlusPlus && 15262 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15263 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15264 Diag(IdLoc, diag::ext_enum_value_not_int) 15265 << EnumVal.toString(10) << 1; 15266 } 15267 } 15268 } 15269 15270 if (!EltTy->isDependentType()) { 15271 // Make the enumerator value match the signedness and size of the 15272 // enumerator's type. 15273 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15274 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15275 } 15276 15277 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15278 Val, EnumVal); 15279 } 15280 15281 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15282 SourceLocation IILoc) { 15283 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15284 !getLangOpts().CPlusPlus) 15285 return SkipBodyInfo(); 15286 15287 // We have an anonymous enum definition. Look up the first enumerator to 15288 // determine if we should merge the definition with an existing one and 15289 // skip the body. 15290 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15291 ForRedeclaration); 15292 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15293 if (!PrevECD) 15294 return SkipBodyInfo(); 15295 15296 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15297 NamedDecl *Hidden; 15298 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15299 SkipBodyInfo Skip; 15300 Skip.Previous = Hidden; 15301 return Skip; 15302 } 15303 15304 return SkipBodyInfo(); 15305 } 15306 15307 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15308 SourceLocation IdLoc, IdentifierInfo *Id, 15309 AttributeList *Attr, 15310 SourceLocation EqualLoc, Expr *Val) { 15311 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15312 EnumConstantDecl *LastEnumConst = 15313 cast_or_null<EnumConstantDecl>(lastEnumConst); 15314 15315 // The scope passed in may not be a decl scope. Zip up the scope tree until 15316 // we find one that is. 15317 S = getNonFieldDeclScope(S); 15318 15319 // Verify that there isn't already something declared with this name in this 15320 // scope. 15321 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15322 ForRedeclaration); 15323 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15324 // Maybe we will complain about the shadowed template parameter. 15325 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15326 // Just pretend that we didn't see the previous declaration. 15327 PrevDecl = nullptr; 15328 } 15329 15330 // C++ [class.mem]p15: 15331 // If T is the name of a class, then each of the following shall have a name 15332 // different from T: 15333 // - every enumerator of every member of class T that is an unscoped 15334 // enumerated type 15335 if (!TheEnumDecl->isScoped()) 15336 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15337 DeclarationNameInfo(Id, IdLoc)); 15338 15339 EnumConstantDecl *New = 15340 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15341 if (!New) 15342 return nullptr; 15343 15344 if (PrevDecl) { 15345 // When in C++, we may get a TagDecl with the same name; in this case the 15346 // enum constant will 'hide' the tag. 15347 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15348 "Received TagDecl when not in C++!"); 15349 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15350 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15351 if (isa<EnumConstantDecl>(PrevDecl)) 15352 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15353 else 15354 Diag(IdLoc, diag::err_redefinition) << Id; 15355 notePreviousDefinition(PrevDecl, IdLoc); 15356 return nullptr; 15357 } 15358 } 15359 15360 // Process attributes. 15361 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15362 AddPragmaAttributes(S, New); 15363 15364 // Register this decl in the current scope stack. 15365 New->setAccess(TheEnumDecl->getAccess()); 15366 PushOnScopeChains(New, S); 15367 15368 ActOnDocumentableDecl(New); 15369 15370 return New; 15371 } 15372 15373 // Returns true when the enum initial expression does not trigger the 15374 // duplicate enum warning. A few common cases are exempted as follows: 15375 // Element2 = Element1 15376 // Element2 = Element1 + 1 15377 // Element2 = Element1 - 1 15378 // Where Element2 and Element1 are from the same enum. 15379 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15380 Expr *InitExpr = ECD->getInitExpr(); 15381 if (!InitExpr) 15382 return true; 15383 InitExpr = InitExpr->IgnoreImpCasts(); 15384 15385 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15386 if (!BO->isAdditiveOp()) 15387 return true; 15388 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15389 if (!IL) 15390 return true; 15391 if (IL->getValue() != 1) 15392 return true; 15393 15394 InitExpr = BO->getLHS(); 15395 } 15396 15397 // This checks if the elements are from the same enum. 15398 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15399 if (!DRE) 15400 return true; 15401 15402 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15403 if (!EnumConstant) 15404 return true; 15405 15406 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15407 Enum) 15408 return true; 15409 15410 return false; 15411 } 15412 15413 namespace { 15414 struct DupKey { 15415 int64_t val; 15416 bool isTombstoneOrEmptyKey; 15417 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15418 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15419 }; 15420 15421 static DupKey GetDupKey(const llvm::APSInt& Val) { 15422 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15423 false); 15424 } 15425 15426 struct DenseMapInfoDupKey { 15427 static DupKey getEmptyKey() { return DupKey(0, true); } 15428 static DupKey getTombstoneKey() { return DupKey(1, true); } 15429 static unsigned getHashValue(const DupKey Key) { 15430 return (unsigned)(Key.val * 37); 15431 } 15432 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15433 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15434 LHS.val == RHS.val; 15435 } 15436 }; 15437 } // end anonymous namespace 15438 15439 // Emits a warning when an element is implicitly set a value that 15440 // a previous element has already been set to. 15441 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15442 EnumDecl *Enum, 15443 QualType EnumType) { 15444 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15445 return; 15446 // Avoid anonymous enums 15447 if (!Enum->getIdentifier()) 15448 return; 15449 15450 // Only check for small enums. 15451 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15452 return; 15453 15454 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15455 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15456 15457 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15458 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15459 ValueToVectorMap; 15460 15461 DuplicatesVector DupVector; 15462 ValueToVectorMap EnumMap; 15463 15464 // Populate the EnumMap with all values represented by enum constants without 15465 // an initialier. 15466 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15467 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15468 15469 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15470 // this constant. Skip this enum since it may be ill-formed. 15471 if (!ECD) { 15472 return; 15473 } 15474 15475 if (ECD->getInitExpr()) 15476 continue; 15477 15478 DupKey Key = GetDupKey(ECD->getInitVal()); 15479 DeclOrVector &Entry = EnumMap[Key]; 15480 15481 // First time encountering this value. 15482 if (Entry.isNull()) 15483 Entry = ECD; 15484 } 15485 15486 // Create vectors for any values that has duplicates. 15487 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15488 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15489 if (!ValidDuplicateEnum(ECD, Enum)) 15490 continue; 15491 15492 DupKey Key = GetDupKey(ECD->getInitVal()); 15493 15494 DeclOrVector& Entry = EnumMap[Key]; 15495 if (Entry.isNull()) 15496 continue; 15497 15498 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15499 // Ensure constants are different. 15500 if (D == ECD) 15501 continue; 15502 15503 // Create new vector and push values onto it. 15504 ECDVector *Vec = new ECDVector(); 15505 Vec->push_back(D); 15506 Vec->push_back(ECD); 15507 15508 // Update entry to point to the duplicates vector. 15509 Entry = Vec; 15510 15511 // Store the vector somewhere we can consult later for quick emission of 15512 // diagnostics. 15513 DupVector.push_back(Vec); 15514 continue; 15515 } 15516 15517 ECDVector *Vec = Entry.get<ECDVector*>(); 15518 // Make sure constants are not added more than once. 15519 if (*Vec->begin() == ECD) 15520 continue; 15521 15522 Vec->push_back(ECD); 15523 } 15524 15525 // Emit diagnostics. 15526 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15527 DupVectorEnd = DupVector.end(); 15528 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15529 ECDVector *Vec = *DupVectorIter; 15530 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15531 15532 // Emit warning for one enum constant. 15533 ECDVector::iterator I = Vec->begin(); 15534 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15535 << (*I)->getName() << (*I)->getInitVal().toString(10) 15536 << (*I)->getSourceRange(); 15537 ++I; 15538 15539 // Emit one note for each of the remaining enum constants with 15540 // the same value. 15541 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15542 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15543 << (*I)->getName() << (*I)->getInitVal().toString(10) 15544 << (*I)->getSourceRange(); 15545 delete Vec; 15546 } 15547 } 15548 15549 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15550 bool AllowMask) const { 15551 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 15552 assert(ED->isCompleteDefinition() && "expected enum definition"); 15553 15554 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15555 llvm::APInt &FlagBits = R.first->second; 15556 15557 if (R.second) { 15558 for (auto *E : ED->enumerators()) { 15559 const auto &EVal = E->getInitVal(); 15560 // Only single-bit enumerators introduce new flag values. 15561 if (EVal.isPowerOf2()) 15562 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15563 } 15564 } 15565 15566 // A value is in a flag enum if either its bits are a subset of the enum's 15567 // flag bits (the first condition) or we are allowing masks and the same is 15568 // true of its complement (the second condition). When masks are allowed, we 15569 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15570 // 15571 // While it's true that any value could be used as a mask, the assumption is 15572 // that a mask will have all of the insignificant bits set. Anything else is 15573 // likely a logic error. 15574 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15575 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15576 } 15577 15578 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15579 Decl *EnumDeclX, 15580 ArrayRef<Decl *> Elements, 15581 Scope *S, AttributeList *Attr) { 15582 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15583 QualType EnumType = Context.getTypeDeclType(Enum); 15584 15585 if (Attr) 15586 ProcessDeclAttributeList(S, Enum, Attr); 15587 15588 if (Enum->isDependentType()) { 15589 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15590 EnumConstantDecl *ECD = 15591 cast_or_null<EnumConstantDecl>(Elements[i]); 15592 if (!ECD) continue; 15593 15594 ECD->setType(EnumType); 15595 } 15596 15597 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15598 return; 15599 } 15600 15601 // TODO: If the result value doesn't fit in an int, it must be a long or long 15602 // long value. ISO C does not support this, but GCC does as an extension, 15603 // emit a warning. 15604 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15605 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15606 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15607 15608 // Verify that all the values are okay, compute the size of the values, and 15609 // reverse the list. 15610 unsigned NumNegativeBits = 0; 15611 unsigned NumPositiveBits = 0; 15612 15613 // Keep track of whether all elements have type int. 15614 bool AllElementsInt = true; 15615 15616 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15617 EnumConstantDecl *ECD = 15618 cast_or_null<EnumConstantDecl>(Elements[i]); 15619 if (!ECD) continue; // Already issued a diagnostic. 15620 15621 const llvm::APSInt &InitVal = ECD->getInitVal(); 15622 15623 // Keep track of the size of positive and negative values. 15624 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15625 NumPositiveBits = std::max(NumPositiveBits, 15626 (unsigned)InitVal.getActiveBits()); 15627 else 15628 NumNegativeBits = std::max(NumNegativeBits, 15629 (unsigned)InitVal.getMinSignedBits()); 15630 15631 // Keep track of whether every enum element has type int (very commmon). 15632 if (AllElementsInt) 15633 AllElementsInt = ECD->getType() == Context.IntTy; 15634 } 15635 15636 // Figure out the type that should be used for this enum. 15637 QualType BestType; 15638 unsigned BestWidth; 15639 15640 // C++0x N3000 [conv.prom]p3: 15641 // An rvalue of an unscoped enumeration type whose underlying 15642 // type is not fixed can be converted to an rvalue of the first 15643 // of the following types that can represent all the values of 15644 // the enumeration: int, unsigned int, long int, unsigned long 15645 // int, long long int, or unsigned long long int. 15646 // C99 6.4.4.3p2: 15647 // An identifier declared as an enumeration constant has type int. 15648 // The C99 rule is modified by a gcc extension 15649 QualType BestPromotionType; 15650 15651 bool Packed = Enum->hasAttr<PackedAttr>(); 15652 // -fshort-enums is the equivalent to specifying the packed attribute on all 15653 // enum definitions. 15654 if (LangOpts.ShortEnums) 15655 Packed = true; 15656 15657 if (Enum->isFixed()) { 15658 BestType = Enum->getIntegerType(); 15659 if (BestType->isPromotableIntegerType()) 15660 BestPromotionType = Context.getPromotedIntegerType(BestType); 15661 else 15662 BestPromotionType = BestType; 15663 15664 BestWidth = Context.getIntWidth(BestType); 15665 } 15666 else if (NumNegativeBits) { 15667 // If there is a negative value, figure out the smallest integer type (of 15668 // int/long/longlong) that fits. 15669 // If it's packed, check also if it fits a char or a short. 15670 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15671 BestType = Context.SignedCharTy; 15672 BestWidth = CharWidth; 15673 } else if (Packed && NumNegativeBits <= ShortWidth && 15674 NumPositiveBits < ShortWidth) { 15675 BestType = Context.ShortTy; 15676 BestWidth = ShortWidth; 15677 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15678 BestType = Context.IntTy; 15679 BestWidth = IntWidth; 15680 } else { 15681 BestWidth = Context.getTargetInfo().getLongWidth(); 15682 15683 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15684 BestType = Context.LongTy; 15685 } else { 15686 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15687 15688 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15689 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15690 BestType = Context.LongLongTy; 15691 } 15692 } 15693 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15694 } else { 15695 // If there is no negative value, figure out the smallest type that fits 15696 // all of the enumerator values. 15697 // If it's packed, check also if it fits a char or a short. 15698 if (Packed && NumPositiveBits <= CharWidth) { 15699 BestType = Context.UnsignedCharTy; 15700 BestPromotionType = Context.IntTy; 15701 BestWidth = CharWidth; 15702 } else if (Packed && NumPositiveBits <= ShortWidth) { 15703 BestType = Context.UnsignedShortTy; 15704 BestPromotionType = Context.IntTy; 15705 BestWidth = ShortWidth; 15706 } else if (NumPositiveBits <= IntWidth) { 15707 BestType = Context.UnsignedIntTy; 15708 BestWidth = IntWidth; 15709 BestPromotionType 15710 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15711 ? Context.UnsignedIntTy : Context.IntTy; 15712 } else if (NumPositiveBits <= 15713 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15714 BestType = Context.UnsignedLongTy; 15715 BestPromotionType 15716 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15717 ? Context.UnsignedLongTy : Context.LongTy; 15718 } else { 15719 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15720 assert(NumPositiveBits <= BestWidth && 15721 "How could an initializer get larger than ULL?"); 15722 BestType = Context.UnsignedLongLongTy; 15723 BestPromotionType 15724 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15725 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15726 } 15727 } 15728 15729 // Loop over all of the enumerator constants, changing their types to match 15730 // the type of the enum if needed. 15731 for (auto *D : Elements) { 15732 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15733 if (!ECD) continue; // Already issued a diagnostic. 15734 15735 // Standard C says the enumerators have int type, but we allow, as an 15736 // extension, the enumerators to be larger than int size. If each 15737 // enumerator value fits in an int, type it as an int, otherwise type it the 15738 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15739 // that X has type 'int', not 'unsigned'. 15740 15741 // Determine whether the value fits into an int. 15742 llvm::APSInt InitVal = ECD->getInitVal(); 15743 15744 // If it fits into an integer type, force it. Otherwise force it to match 15745 // the enum decl type. 15746 QualType NewTy; 15747 unsigned NewWidth; 15748 bool NewSign; 15749 if (!getLangOpts().CPlusPlus && 15750 !Enum->isFixed() && 15751 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15752 NewTy = Context.IntTy; 15753 NewWidth = IntWidth; 15754 NewSign = true; 15755 } else if (ECD->getType() == BestType) { 15756 // Already the right type! 15757 if (getLangOpts().CPlusPlus) 15758 // C++ [dcl.enum]p4: Following the closing brace of an 15759 // enum-specifier, each enumerator has the type of its 15760 // enumeration. 15761 ECD->setType(EnumType); 15762 continue; 15763 } else { 15764 NewTy = BestType; 15765 NewWidth = BestWidth; 15766 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15767 } 15768 15769 // Adjust the APSInt value. 15770 InitVal = InitVal.extOrTrunc(NewWidth); 15771 InitVal.setIsSigned(NewSign); 15772 ECD->setInitVal(InitVal); 15773 15774 // Adjust the Expr initializer and type. 15775 if (ECD->getInitExpr() && 15776 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15777 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15778 CK_IntegralCast, 15779 ECD->getInitExpr(), 15780 /*base paths*/ nullptr, 15781 VK_RValue)); 15782 if (getLangOpts().CPlusPlus) 15783 // C++ [dcl.enum]p4: Following the closing brace of an 15784 // enum-specifier, each enumerator has the type of its 15785 // enumeration. 15786 ECD->setType(EnumType); 15787 else 15788 ECD->setType(NewTy); 15789 } 15790 15791 Enum->completeDefinition(BestType, BestPromotionType, 15792 NumPositiveBits, NumNegativeBits); 15793 15794 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15795 15796 if (Enum->isClosedFlag()) { 15797 for (Decl *D : Elements) { 15798 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15799 if (!ECD) continue; // Already issued a diagnostic. 15800 15801 llvm::APSInt InitVal = ECD->getInitVal(); 15802 if (InitVal != 0 && !InitVal.isPowerOf2() && 15803 !IsValueInFlagEnum(Enum, InitVal, true)) 15804 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15805 << ECD << Enum; 15806 } 15807 } 15808 15809 // Now that the enum type is defined, ensure it's not been underaligned. 15810 if (Enum->hasAttrs()) 15811 CheckAlignasUnderalignment(Enum); 15812 } 15813 15814 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15815 SourceLocation StartLoc, 15816 SourceLocation EndLoc) { 15817 StringLiteral *AsmString = cast<StringLiteral>(expr); 15818 15819 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15820 AsmString, StartLoc, 15821 EndLoc); 15822 CurContext->addDecl(New); 15823 return New; 15824 } 15825 15826 static void checkModuleImportContext(Sema &S, Module *M, 15827 SourceLocation ImportLoc, DeclContext *DC, 15828 bool FromInclude = false) { 15829 SourceLocation ExternCLoc; 15830 15831 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15832 switch (LSD->getLanguage()) { 15833 case LinkageSpecDecl::lang_c: 15834 if (ExternCLoc.isInvalid()) 15835 ExternCLoc = LSD->getLocStart(); 15836 break; 15837 case LinkageSpecDecl::lang_cxx: 15838 break; 15839 } 15840 DC = LSD->getParent(); 15841 } 15842 15843 while (isa<LinkageSpecDecl>(DC)) 15844 DC = DC->getParent(); 15845 15846 if (!isa<TranslationUnitDecl>(DC)) { 15847 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15848 ? diag::ext_module_import_not_at_top_level_noop 15849 : diag::err_module_import_not_at_top_level_fatal) 15850 << M->getFullModuleName() << DC; 15851 S.Diag(cast<Decl>(DC)->getLocStart(), 15852 diag::note_module_import_not_at_top_level) << DC; 15853 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15854 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15855 << M->getFullModuleName(); 15856 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 15857 } 15858 } 15859 15860 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 15861 SourceLocation ModuleLoc, 15862 ModuleDeclKind MDK, 15863 ModuleIdPath Path) { 15864 // A module implementation unit requires that we are not compiling a module 15865 // of any kind. A module interface unit requires that we are not compiling a 15866 // module map. 15867 switch (getLangOpts().getCompilingModule()) { 15868 case LangOptions::CMK_None: 15869 // It's OK to compile a module interface as a normal translation unit. 15870 break; 15871 15872 case LangOptions::CMK_ModuleInterface: 15873 if (MDK != ModuleDeclKind::Implementation) 15874 break; 15875 15876 // We were asked to compile a module interface unit but this is a module 15877 // implementation unit. That indicates the 'export' is missing. 15878 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15879 << FixItHint::CreateInsertion(ModuleLoc, "export "); 15880 break; 15881 15882 case LangOptions::CMK_ModuleMap: 15883 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 15884 return nullptr; 15885 } 15886 15887 // FIXME: Create a ModuleDecl and return it. 15888 15889 // FIXME: Most of this work should be done by the preprocessor rather than 15890 // here, in order to support macro import. 15891 15892 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 15893 // modules, the dots here are just another character that can appear in a 15894 // module name. 15895 std::string ModuleName; 15896 for (auto &Piece : Path) { 15897 if (!ModuleName.empty()) 15898 ModuleName += "."; 15899 ModuleName += Piece.first->getName(); 15900 } 15901 15902 // If a module name was explicitly specified on the command line, it must be 15903 // correct. 15904 if (!getLangOpts().CurrentModule.empty() && 15905 getLangOpts().CurrentModule != ModuleName) { 15906 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15907 << SourceRange(Path.front().second, Path.back().second) 15908 << getLangOpts().CurrentModule; 15909 return nullptr; 15910 } 15911 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15912 15913 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15914 15915 switch (MDK) { 15916 case ModuleDeclKind::Module: { 15917 // FIXME: Check we're not in a submodule. 15918 15919 // We can't have parsed or imported a definition of this module or parsed a 15920 // module map defining it already. 15921 if (auto *M = Map.findModule(ModuleName)) { 15922 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15923 if (M->DefinitionLoc.isValid()) 15924 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15925 else if (const auto *FE = M->getASTFile()) 15926 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15927 << FE->getName(); 15928 return nullptr; 15929 } 15930 15931 // Create a Module for the module that we're defining. 15932 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15933 assert(Mod && "module creation should not fail"); 15934 15935 // Enter the semantic scope of the module. 15936 ActOnModuleBegin(ModuleLoc, Mod); 15937 return nullptr; 15938 } 15939 15940 case ModuleDeclKind::Partition: 15941 // FIXME: Check we are in a submodule of the named module. 15942 return nullptr; 15943 15944 case ModuleDeclKind::Implementation: 15945 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15946 PP.getIdentifierInfo(ModuleName), Path[0].second); 15947 15948 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15949 if (Import.isInvalid()) 15950 return nullptr; 15951 return ConvertDeclToDeclGroup(Import.get()); 15952 } 15953 15954 llvm_unreachable("unexpected module decl kind"); 15955 } 15956 15957 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15958 SourceLocation ImportLoc, 15959 ModuleIdPath Path) { 15960 Module *Mod = 15961 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15962 /*IsIncludeDirective=*/false); 15963 if (!Mod) 15964 return true; 15965 15966 VisibleModules.setVisible(Mod, ImportLoc); 15967 15968 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15969 15970 // FIXME: we should support importing a submodule within a different submodule 15971 // of the same top-level module. Until we do, make it an error rather than 15972 // silently ignoring the import. 15973 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15974 // warn on a redundant import of the current module? 15975 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15976 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15977 Diag(ImportLoc, getLangOpts().isCompilingModule() 15978 ? diag::err_module_self_import 15979 : diag::err_module_import_in_implementation) 15980 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15981 15982 SmallVector<SourceLocation, 2> IdentifierLocs; 15983 Module *ModCheck = Mod; 15984 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15985 // If we've run out of module parents, just drop the remaining identifiers. 15986 // We need the length to be consistent. 15987 if (!ModCheck) 15988 break; 15989 ModCheck = ModCheck->Parent; 15990 15991 IdentifierLocs.push_back(Path[I].second); 15992 } 15993 15994 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15995 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15996 Mod, IdentifierLocs); 15997 if (!ModuleScopes.empty()) 15998 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 15999 TU->addDecl(Import); 16000 return Import; 16001 } 16002 16003 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16004 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16005 BuildModuleInclude(DirectiveLoc, Mod); 16006 } 16007 16008 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16009 // Determine whether we're in the #include buffer for a module. The #includes 16010 // in that buffer do not qualify as module imports; they're just an 16011 // implementation detail of us building the module. 16012 // 16013 // FIXME: Should we even get ActOnModuleInclude calls for those? 16014 bool IsInModuleIncludes = 16015 TUKind == TU_Module && 16016 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16017 16018 bool ShouldAddImport = !IsInModuleIncludes; 16019 16020 // If this module import was due to an inclusion directive, create an 16021 // implicit import declaration to capture it in the AST. 16022 if (ShouldAddImport) { 16023 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16024 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16025 DirectiveLoc, Mod, 16026 DirectiveLoc); 16027 if (!ModuleScopes.empty()) 16028 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16029 TU->addDecl(ImportD); 16030 Consumer.HandleImplicitImportDecl(ImportD); 16031 } 16032 16033 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16034 VisibleModules.setVisible(Mod, DirectiveLoc); 16035 } 16036 16037 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16038 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16039 16040 ModuleScopes.push_back({}); 16041 ModuleScopes.back().Module = Mod; 16042 if (getLangOpts().ModulesLocalVisibility) 16043 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16044 16045 VisibleModules.setVisible(Mod, DirectiveLoc); 16046 16047 // The enclosing context is now part of this module. 16048 // FIXME: Consider creating a child DeclContext to hold the entities 16049 // lexically within the module. 16050 if (getLangOpts().trackLocalOwningModule()) { 16051 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16052 cast<Decl>(DC)->setHidden(true); 16053 cast<Decl>(DC)->setLocalOwningModule(Mod); 16054 } 16055 } 16056 } 16057 16058 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16059 if (getLangOpts().ModulesLocalVisibility) { 16060 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16061 // Leaving a module hides namespace names, so our visible namespace cache 16062 // is now out of date. 16063 VisibleNamespaceCache.clear(); 16064 } 16065 16066 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16067 "left the wrong module scope"); 16068 ModuleScopes.pop_back(); 16069 16070 // We got to the end of processing a local module. Create an 16071 // ImportDecl as we would for an imported module. 16072 FileID File = getSourceManager().getFileID(EomLoc); 16073 SourceLocation DirectiveLoc; 16074 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16075 // We reached the end of a #included module header. Use the #include loc. 16076 assert(File != getSourceManager().getMainFileID() && 16077 "end of submodule in main source file"); 16078 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16079 } else { 16080 // We reached an EOM pragma. Use the pragma location. 16081 DirectiveLoc = EomLoc; 16082 } 16083 BuildModuleInclude(DirectiveLoc, Mod); 16084 16085 // Any further declarations are in whatever module we returned to. 16086 if (getLangOpts().trackLocalOwningModule()) { 16087 // The parser guarantees that this is the same context that we entered 16088 // the module within. 16089 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16090 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16091 if (!getCurrentModule()) 16092 cast<Decl>(DC)->setHidden(false); 16093 } 16094 } 16095 } 16096 16097 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16098 Module *Mod) { 16099 // Bail if we're not allowed to implicitly import a module here. 16100 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16101 VisibleModules.isVisible(Mod)) 16102 return; 16103 16104 // Create the implicit import declaration. 16105 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16106 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16107 Loc, Mod, Loc); 16108 TU->addDecl(ImportD); 16109 Consumer.HandleImplicitImportDecl(ImportD); 16110 16111 // Make the module visible. 16112 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16113 VisibleModules.setVisible(Mod, Loc); 16114 } 16115 16116 /// We have parsed the start of an export declaration, including the '{' 16117 /// (if present). 16118 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16119 SourceLocation LBraceLoc) { 16120 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16121 16122 // C++ Modules TS draft: 16123 // An export-declaration shall appear in the purview of a module other than 16124 // the global module. 16125 if (ModuleScopes.empty() || !ModuleScopes.back().Module || 16126 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit) 16127 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16128 16129 // An export-declaration [...] shall not contain more than one 16130 // export keyword. 16131 // 16132 // The intent here is that an export-declaration cannot appear within another 16133 // export-declaration. 16134 if (D->isExported()) 16135 Diag(ExportLoc, diag::err_export_within_export); 16136 16137 CurContext->addDecl(D); 16138 PushDeclContext(S, D); 16139 return D; 16140 } 16141 16142 /// Complete the definition of an export declaration. 16143 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16144 auto *ED = cast<ExportDecl>(D); 16145 if (RBraceLoc.isValid()) 16146 ED->setRBraceLoc(RBraceLoc); 16147 16148 // FIXME: Diagnose export of internal-linkage declaration (including 16149 // anonymous namespace). 16150 16151 PopDeclContext(); 16152 return D; 16153 } 16154 16155 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16156 IdentifierInfo* AliasName, 16157 SourceLocation PragmaLoc, 16158 SourceLocation NameLoc, 16159 SourceLocation AliasNameLoc) { 16160 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16161 LookupOrdinaryName); 16162 AsmLabelAttr *Attr = 16163 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16164 16165 // If a declaration that: 16166 // 1) declares a function or a variable 16167 // 2) has external linkage 16168 // already exists, add a label attribute to it. 16169 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16170 if (isDeclExternC(PrevDecl)) 16171 PrevDecl->addAttr(Attr); 16172 else 16173 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16174 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16175 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16176 } else 16177 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16178 } 16179 16180 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16181 SourceLocation PragmaLoc, 16182 SourceLocation NameLoc) { 16183 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16184 16185 if (PrevDecl) { 16186 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16187 } else { 16188 (void)WeakUndeclaredIdentifiers.insert( 16189 std::pair<IdentifierInfo*,WeakInfo> 16190 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16191 } 16192 } 16193 16194 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16195 IdentifierInfo* AliasName, 16196 SourceLocation PragmaLoc, 16197 SourceLocation NameLoc, 16198 SourceLocation AliasNameLoc) { 16199 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16200 LookupOrdinaryName); 16201 WeakInfo W = WeakInfo(Name, NameLoc); 16202 16203 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16204 if (!PrevDecl->hasAttr<AliasAttr>()) 16205 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16206 DeclApplyPragmaWeak(TUScope, ND, W); 16207 } else { 16208 (void)WeakUndeclaredIdentifiers.insert( 16209 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16210 } 16211 } 16212 16213 Decl *Sema::getObjCDeclContext() const { 16214 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16215 } 16216