1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw__Float16: 136 case tok::kw___float128: 137 case tok::kw_wchar_t: 138 case tok::kw_bool: 139 case tok::kw___underlying_type: 140 case tok::kw___auto_type: 141 return true; 142 143 case tok::annot_typename: 144 case tok::kw_char16_t: 145 case tok::kw_char32_t: 146 case tok::kw_typeof: 147 case tok::annot_decltype: 148 case tok::kw_decltype: 149 return getLangOpts().CPlusPlus; 150 151 case tok::kw_char8_t: 152 return getLangOpts().Char8; 153 154 default: 155 break; 156 } 157 158 return false; 159 } 160 161 namespace { 162 enum class UnqualifiedTypeNameLookupResult { 163 NotFound, 164 FoundNonType, 165 FoundType 166 }; 167 } // end anonymous namespace 168 169 /// Tries to perform unqualified lookup of the type decls in bases for 170 /// dependent class. 171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 172 /// type decl, \a FoundType if only type decls are found. 173 static UnqualifiedTypeNameLookupResult 174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 175 SourceLocation NameLoc, 176 const CXXRecordDecl *RD) { 177 if (!RD->hasDefinition()) 178 return UnqualifiedTypeNameLookupResult::NotFound; 179 // Look for type decls in base classes. 180 UnqualifiedTypeNameLookupResult FoundTypeDecl = 181 UnqualifiedTypeNameLookupResult::NotFound; 182 for (const auto &Base : RD->bases()) { 183 const CXXRecordDecl *BaseRD = nullptr; 184 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 185 BaseRD = BaseTT->getAsCXXRecordDecl(); 186 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 187 // Look for type decls in dependent base classes that have known primary 188 // templates. 189 if (!TST || !TST->isDependentType()) 190 continue; 191 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 192 if (!TD) 193 continue; 194 if (auto *BasePrimaryTemplate = 195 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 196 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 197 BaseRD = BasePrimaryTemplate; 198 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 199 if (const ClassTemplatePartialSpecializationDecl *PS = 200 CTD->findPartialSpecialization(Base.getType())) 201 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 202 BaseRD = PS; 203 } 204 } 205 } 206 if (BaseRD) { 207 for (NamedDecl *ND : BaseRD->lookup(&II)) { 208 if (!isa<TypeDecl>(ND)) 209 return UnqualifiedTypeNameLookupResult::FoundNonType; 210 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 211 } 212 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 213 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 214 case UnqualifiedTypeNameLookupResult::FoundNonType: 215 return UnqualifiedTypeNameLookupResult::FoundNonType; 216 case UnqualifiedTypeNameLookupResult::FoundType: 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 break; 219 case UnqualifiedTypeNameLookupResult::NotFound: 220 break; 221 } 222 } 223 } 224 } 225 226 return FoundTypeDecl; 227 } 228 229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 230 const IdentifierInfo &II, 231 SourceLocation NameLoc) { 232 // Lookup in the parent class template context, if any. 233 const CXXRecordDecl *RD = nullptr; 234 UnqualifiedTypeNameLookupResult FoundTypeDecl = 235 UnqualifiedTypeNameLookupResult::NotFound; 236 for (DeclContext *DC = S.CurContext; 237 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 238 DC = DC->getParent()) { 239 // Look for type decls in dependent base classes that have known primary 240 // templates. 241 RD = dyn_cast<CXXRecordDecl>(DC); 242 if (RD && RD->getDescribedClassTemplate()) 243 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 244 } 245 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 246 return nullptr; 247 248 // We found some types in dependent base classes. Recover as if the user 249 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 250 // lookup during template instantiation. 251 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 252 253 ASTContext &Context = S.Context; 254 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 255 cast<Type>(Context.getRecordType(RD))); 256 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 257 258 CXXScopeSpec SS; 259 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 260 261 TypeLocBuilder Builder; 262 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 263 DepTL.setNameLoc(NameLoc); 264 DepTL.setElaboratedKeywordLoc(SourceLocation()); 265 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 266 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 267 } 268 269 /// If the identifier refers to a type name within this scope, 270 /// return the declaration of that type. 271 /// 272 /// This routine performs ordinary name lookup of the identifier II 273 /// within the given scope, with optional C++ scope specifier SS, to 274 /// determine whether the name refers to a type. If so, returns an 275 /// opaque pointer (actually a QualType) corresponding to that 276 /// type. Otherwise, returns NULL. 277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 278 Scope *S, CXXScopeSpec *SS, 279 bool isClassName, bool HasTrailingDot, 280 ParsedType ObjectTypePtr, 281 bool IsCtorOrDtorName, 282 bool WantNontrivialTypeSourceInfo, 283 bool IsClassTemplateDeductionContext, 284 IdentifierInfo **CorrectedII) { 285 // FIXME: Consider allowing this outside C++1z mode as an extension. 286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 287 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 288 !isClassName && !HasTrailingDot; 289 290 // Determine where we will perform name lookup. 291 DeclContext *LookupCtx = nullptr; 292 if (ObjectTypePtr) { 293 QualType ObjectType = ObjectTypePtr.get(); 294 if (ObjectType->isRecordType()) 295 LookupCtx = computeDeclContext(ObjectType); 296 } else if (SS && SS->isNotEmpty()) { 297 LookupCtx = computeDeclContext(*SS, false); 298 299 if (!LookupCtx) { 300 if (isDependentScopeSpecifier(*SS)) { 301 // C++ [temp.res]p3: 302 // A qualified-id that refers to a type and in which the 303 // nested-name-specifier depends on a template-parameter (14.6.2) 304 // shall be prefixed by the keyword typename to indicate that the 305 // qualified-id denotes a type, forming an 306 // elaborated-type-specifier (7.1.5.3). 307 // 308 // We therefore do not perform any name lookup if the result would 309 // refer to a member of an unknown specialization. 310 if (!isClassName && !IsCtorOrDtorName) 311 return nullptr; 312 313 // We know from the grammar that this name refers to a type, 314 // so build a dependent node to describe the type. 315 if (WantNontrivialTypeSourceInfo) 316 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 317 318 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 319 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 320 II, NameLoc); 321 return ParsedType::make(T); 322 } 323 324 return nullptr; 325 } 326 327 if (!LookupCtx->isDependentContext() && 328 RequireCompleteDeclContext(*SS, LookupCtx)) 329 return nullptr; 330 } 331 332 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 333 // lookup for class-names. 334 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 335 LookupOrdinaryName; 336 LookupResult Result(*this, &II, NameLoc, Kind); 337 if (LookupCtx) { 338 // Perform "qualified" name lookup into the declaration context we 339 // computed, which is either the type of the base of a member access 340 // expression or the declaration context associated with a prior 341 // nested-name-specifier. 342 LookupQualifiedName(Result, LookupCtx); 343 344 if (ObjectTypePtr && Result.empty()) { 345 // C++ [basic.lookup.classref]p3: 346 // If the unqualified-id is ~type-name, the type-name is looked up 347 // in the context of the entire postfix-expression. If the type T of 348 // the object expression is of a class type C, the type-name is also 349 // looked up in the scope of class C. At least one of the lookups shall 350 // find a name that refers to (possibly cv-qualified) T. 351 LookupName(Result, S); 352 } 353 } else { 354 // Perform unqualified name lookup. 355 LookupName(Result, S); 356 357 // For unqualified lookup in a class template in MSVC mode, look into 358 // dependent base classes where the primary class template is known. 359 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 360 if (ParsedType TypeInBase = 361 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 362 return TypeInBase; 363 } 364 } 365 366 NamedDecl *IIDecl = nullptr; 367 switch (Result.getResultKind()) { 368 case LookupResult::NotFound: 369 case LookupResult::NotFoundInCurrentInstantiation: 370 if (CorrectedII) { 371 TypoCorrection Correction = 372 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 373 llvm::make_unique<TypeNameValidatorCCC>( 374 true, isClassName, AllowDeducedTemplate), 375 CTK_ErrorRecovery); 376 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 377 TemplateTy Template; 378 bool MemberOfUnknownSpecialization; 379 UnqualifiedId TemplateName; 380 TemplateName.setIdentifier(NewII, NameLoc); 381 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 382 CXXScopeSpec NewSS, *NewSSPtr = SS; 383 if (SS && NNS) { 384 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 385 NewSSPtr = &NewSS; 386 } 387 if (Correction && (NNS || NewII != &II) && 388 // Ignore a correction to a template type as the to-be-corrected 389 // identifier is not a template (typo correction for template names 390 // is handled elsewhere). 391 !(getLangOpts().CPlusPlus && NewSSPtr && 392 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 393 Template, MemberOfUnknownSpecialization))) { 394 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 395 isClassName, HasTrailingDot, ObjectTypePtr, 396 IsCtorOrDtorName, 397 WantNontrivialTypeSourceInfo, 398 IsClassTemplateDeductionContext); 399 if (Ty) { 400 diagnoseTypo(Correction, 401 PDiag(diag::err_unknown_type_or_class_name_suggest) 402 << Result.getLookupName() << isClassName); 403 if (SS && NNS) 404 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 405 *CorrectedII = NewII; 406 return Ty; 407 } 408 } 409 } 410 // If typo correction failed or was not performed, fall through 411 LLVM_FALLTHROUGH; 412 case LookupResult::FoundOverloaded: 413 case LookupResult::FoundUnresolvedValue: 414 Result.suppressDiagnostics(); 415 return nullptr; 416 417 case LookupResult::Ambiguous: 418 // Recover from type-hiding ambiguities by hiding the type. We'll 419 // do the lookup again when looking for an object, and we can 420 // diagnose the error then. If we don't do this, then the error 421 // about hiding the type will be immediately followed by an error 422 // that only makes sense if the identifier was treated like a type. 423 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 424 Result.suppressDiagnostics(); 425 return nullptr; 426 } 427 428 // Look to see if we have a type anywhere in the list of results. 429 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 430 Res != ResEnd; ++Res) { 431 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 432 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 433 if (!IIDecl || 434 (*Res)->getLocation().getRawEncoding() < 435 IIDecl->getLocation().getRawEncoding()) 436 IIDecl = *Res; 437 } 438 } 439 440 if (!IIDecl) { 441 // None of the entities we found is a type, so there is no way 442 // to even assume that the result is a type. In this case, don't 443 // complain about the ambiguity. The parser will either try to 444 // perform this lookup again (e.g., as an object name), which 445 // will produce the ambiguity, or will complain that it expected 446 // a type name. 447 Result.suppressDiagnostics(); 448 return nullptr; 449 } 450 451 // We found a type within the ambiguous lookup; diagnose the 452 // ambiguity and then return that type. This might be the right 453 // answer, or it might not be, but it suppresses any attempt to 454 // perform the name lookup again. 455 break; 456 457 case LookupResult::Found: 458 IIDecl = Result.getFoundDecl(); 459 break; 460 } 461 462 assert(IIDecl && "Didn't find decl"); 463 464 QualType T; 465 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 466 // C++ [class.qual]p2: A lookup that would find the injected-class-name 467 // instead names the constructors of the class, except when naming a class. 468 // This is ill-formed when we're not actually forming a ctor or dtor name. 469 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 470 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 471 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 472 FoundRD->isInjectedClassName() && 473 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 474 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 475 << &II << /*Type*/1; 476 477 DiagnoseUseOfDecl(IIDecl, NameLoc); 478 479 T = Context.getTypeDeclType(TD); 480 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 481 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 482 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 483 if (!HasTrailingDot) 484 T = Context.getObjCInterfaceType(IDecl); 485 } else if (AllowDeducedTemplate) { 486 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 487 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 488 QualType(), false); 489 } 490 491 if (T.isNull()) { 492 // If it's not plausibly a type, suppress diagnostics. 493 Result.suppressDiagnostics(); 494 return nullptr; 495 } 496 497 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 498 // constructor or destructor name (in such a case, the scope specifier 499 // will be attached to the enclosing Expr or Decl node). 500 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 501 !isa<ObjCInterfaceDecl>(IIDecl)) { 502 if (WantNontrivialTypeSourceInfo) { 503 // Construct a type with type-source information. 504 TypeLocBuilder Builder; 505 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 506 507 T = getElaboratedType(ETK_None, *SS, T); 508 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 509 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 510 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 511 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 512 } else { 513 T = getElaboratedType(ETK_None, *SS, T); 514 } 515 } 516 517 return ParsedType::make(T); 518 } 519 520 // Builds a fake NNS for the given decl context. 521 static NestedNameSpecifier * 522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 523 for (;; DC = DC->getLookupParent()) { 524 DC = DC->getPrimaryContext(); 525 auto *ND = dyn_cast<NamespaceDecl>(DC); 526 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 527 return NestedNameSpecifier::Create(Context, nullptr, ND); 528 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 529 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 530 RD->getTypeForDecl()); 531 else if (isa<TranslationUnitDecl>(DC)) 532 return NestedNameSpecifier::GlobalSpecifier(Context); 533 } 534 llvm_unreachable("something isn't in TU scope?"); 535 } 536 537 /// Find the parent class with dependent bases of the innermost enclosing method 538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 539 /// up allowing unqualified dependent type names at class-level, which MSVC 540 /// correctly rejects. 541 static const CXXRecordDecl * 542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 543 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 544 DC = DC->getPrimaryContext(); 545 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 546 if (MD->getParent()->hasAnyDependentBases()) 547 return MD->getParent(); 548 } 549 return nullptr; 550 } 551 552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 553 SourceLocation NameLoc, 554 bool IsTemplateTypeArg) { 555 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 556 557 NestedNameSpecifier *NNS = nullptr; 558 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 559 // If we weren't able to parse a default template argument, delay lookup 560 // until instantiation time by making a non-dependent DependentTypeName. We 561 // pretend we saw a NestedNameSpecifier referring to the current scope, and 562 // lookup is retried. 563 // FIXME: This hurts our diagnostic quality, since we get errors like "no 564 // type named 'Foo' in 'current_namespace'" when the user didn't write any 565 // name specifiers. 566 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 567 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 568 } else if (const CXXRecordDecl *RD = 569 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 570 // Build a DependentNameType that will perform lookup into RD at 571 // instantiation time. 572 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 573 RD->getTypeForDecl()); 574 575 // Diagnose that this identifier was undeclared, and retry the lookup during 576 // template instantiation. 577 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 578 << RD; 579 } else { 580 // This is not a situation that we should recover from. 581 return ParsedType(); 582 } 583 584 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 585 586 // Build type location information. We synthesized the qualifier, so we have 587 // to build a fake NestedNameSpecifierLoc. 588 NestedNameSpecifierLocBuilder NNSLocBuilder; 589 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 590 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 591 592 TypeLocBuilder Builder; 593 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 594 DepTL.setNameLoc(NameLoc); 595 DepTL.setElaboratedKeywordLoc(SourceLocation()); 596 DepTL.setQualifierLoc(QualifierLoc); 597 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 598 } 599 600 /// isTagName() - This method is called *for error recovery purposes only* 601 /// to determine if the specified name is a valid tag name ("struct foo"). If 602 /// so, this returns the TST for the tag corresponding to it (TST_enum, 603 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 604 /// cases in C where the user forgot to specify the tag. 605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 606 // Do a tag name lookup in this scope. 607 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 608 LookupName(R, S, false); 609 R.suppressDiagnostics(); 610 if (R.getResultKind() == LookupResult::Found) 611 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 612 switch (TD->getTagKind()) { 613 case TTK_Struct: return DeclSpec::TST_struct; 614 case TTK_Interface: return DeclSpec::TST_interface; 615 case TTK_Union: return DeclSpec::TST_union; 616 case TTK_Class: return DeclSpec::TST_class; 617 case TTK_Enum: return DeclSpec::TST_enum; 618 } 619 } 620 621 return DeclSpec::TST_unspecified; 622 } 623 624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 626 /// then downgrade the missing typename error to a warning. 627 /// This is needed for MSVC compatibility; Example: 628 /// @code 629 /// template<class T> class A { 630 /// public: 631 /// typedef int TYPE; 632 /// }; 633 /// template<class T> class B : public A<T> { 634 /// public: 635 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 636 /// }; 637 /// @endcode 638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 639 if (CurContext->isRecord()) { 640 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 641 return true; 642 643 const Type *Ty = SS->getScopeRep()->getAsType(); 644 645 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 646 for (const auto &Base : RD->bases()) 647 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 648 return true; 649 return S->isFunctionPrototypeScope(); 650 } 651 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 652 } 653 654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 655 SourceLocation IILoc, 656 Scope *S, 657 CXXScopeSpec *SS, 658 ParsedType &SuggestedType, 659 bool IsTemplateName) { 660 // Don't report typename errors for editor placeholders. 661 if (II->isEditorPlaceholder()) 662 return; 663 // We don't have anything to suggest (yet). 664 SuggestedType = nullptr; 665 666 // There may have been a typo in the name of the type. Look up typo 667 // results, in case we have something that we can suggest. 668 if (TypoCorrection Corrected = 669 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 670 llvm::make_unique<TypeNameValidatorCCC>( 671 false, false, IsTemplateName, !IsTemplateName), 672 CTK_ErrorRecovery)) { 673 // FIXME: Support error recovery for the template-name case. 674 bool CanRecover = !IsTemplateName; 675 if (Corrected.isKeyword()) { 676 // We corrected to a keyword. 677 diagnoseTypo(Corrected, 678 PDiag(IsTemplateName ? diag::err_no_template_suggest 679 : diag::err_unknown_typename_suggest) 680 << II); 681 II = Corrected.getCorrectionAsIdentifierInfo(); 682 } else { 683 // We found a similarly-named type or interface; suggest that. 684 if (!SS || !SS->isSet()) { 685 diagnoseTypo(Corrected, 686 PDiag(IsTemplateName ? diag::err_no_template_suggest 687 : diag::err_unknown_typename_suggest) 688 << II, CanRecover); 689 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 690 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 691 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 692 II->getName().equals(CorrectedStr); 693 diagnoseTypo(Corrected, 694 PDiag(IsTemplateName 695 ? diag::err_no_member_template_suggest 696 : diag::err_unknown_nested_typename_suggest) 697 << II << DC << DroppedSpecifier << SS->getRange(), 698 CanRecover); 699 } else { 700 llvm_unreachable("could not have corrected a typo here"); 701 } 702 703 if (!CanRecover) 704 return; 705 706 CXXScopeSpec tmpSS; 707 if (Corrected.getCorrectionSpecifier()) 708 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 709 SourceRange(IILoc)); 710 // FIXME: Support class template argument deduction here. 711 SuggestedType = 712 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 713 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 714 /*IsCtorOrDtorName=*/false, 715 /*NonTrivialTypeSourceInfo=*/true); 716 } 717 return; 718 } 719 720 if (getLangOpts().CPlusPlus && !IsTemplateName) { 721 // See if II is a class template that the user forgot to pass arguments to. 722 UnqualifiedId Name; 723 Name.setIdentifier(II, IILoc); 724 CXXScopeSpec EmptySS; 725 TemplateTy TemplateResult; 726 bool MemberOfUnknownSpecialization; 727 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 728 Name, nullptr, true, TemplateResult, 729 MemberOfUnknownSpecialization) == TNK_Type_template) { 730 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 731 return; 732 } 733 } 734 735 // FIXME: Should we move the logic that tries to recover from a missing tag 736 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 737 738 if (!SS || (!SS->isSet() && !SS->isInvalid())) 739 Diag(IILoc, IsTemplateName ? diag::err_no_template 740 : diag::err_unknown_typename) 741 << II; 742 else if (DeclContext *DC = computeDeclContext(*SS, false)) 743 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 744 : diag::err_typename_nested_not_found) 745 << II << DC << SS->getRange(); 746 else if (isDependentScopeSpecifier(*SS)) { 747 unsigned DiagID = diag::err_typename_missing; 748 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 749 DiagID = diag::ext_typename_missing; 750 751 Diag(SS->getRange().getBegin(), DiagID) 752 << SS->getScopeRep() << II->getName() 753 << SourceRange(SS->getRange().getBegin(), IILoc) 754 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 755 SuggestedType = ActOnTypenameType(S, SourceLocation(), 756 *SS, *II, IILoc).get(); 757 } else { 758 assert(SS && SS->isInvalid() && 759 "Invalid scope specifier has already been diagnosed"); 760 } 761 } 762 763 /// Determine whether the given result set contains either a type name 764 /// or 765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 766 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 767 NextToken.is(tok::less); 768 769 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 770 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 771 return true; 772 773 if (CheckTemplate && isa<TemplateDecl>(*I)) 774 return true; 775 } 776 777 return false; 778 } 779 780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 781 Scope *S, CXXScopeSpec &SS, 782 IdentifierInfo *&Name, 783 SourceLocation NameLoc) { 784 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 785 SemaRef.LookupParsedName(R, S, &SS); 786 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 787 StringRef FixItTagName; 788 switch (Tag->getTagKind()) { 789 case TTK_Class: 790 FixItTagName = "class "; 791 break; 792 793 case TTK_Enum: 794 FixItTagName = "enum "; 795 break; 796 797 case TTK_Struct: 798 FixItTagName = "struct "; 799 break; 800 801 case TTK_Interface: 802 FixItTagName = "__interface "; 803 break; 804 805 case TTK_Union: 806 FixItTagName = "union "; 807 break; 808 } 809 810 StringRef TagName = FixItTagName.drop_back(); 811 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 812 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 813 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 814 815 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 816 I != IEnd; ++I) 817 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 818 << Name << TagName; 819 820 // Replace lookup results with just the tag decl. 821 Result.clear(Sema::LookupTagName); 822 SemaRef.LookupParsedName(Result, S, &SS); 823 return true; 824 } 825 826 return false; 827 } 828 829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 831 QualType T, SourceLocation NameLoc) { 832 ASTContext &Context = S.Context; 833 834 TypeLocBuilder Builder; 835 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 836 837 T = S.getElaboratedType(ETK_None, SS, T); 838 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 839 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 840 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 841 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 842 } 843 844 Sema::NameClassification 845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 846 SourceLocation NameLoc, const Token &NextToken, 847 bool IsAddressOfOperand, 848 std::unique_ptr<CorrectionCandidateCallback> CCC) { 849 DeclarationNameInfo NameInfo(Name, NameLoc); 850 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 851 852 if (NextToken.is(tok::coloncolon)) { 853 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 854 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 855 } else if (getLangOpts().CPlusPlus && SS.isSet() && 856 isCurrentClassName(*Name, S, &SS)) { 857 // Per [class.qual]p2, this names the constructors of SS, not the 858 // injected-class-name. We don't have a classification for that. 859 // There's not much point caching this result, since the parser 860 // will reject it later. 861 return NameClassification::Unknown(); 862 } 863 864 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 865 LookupParsedName(Result, S, &SS, !CurMethod); 866 867 // For unqualified lookup in a class template in MSVC mode, look into 868 // dependent base classes where the primary class template is known. 869 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 870 if (ParsedType TypeInBase = 871 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 872 return TypeInBase; 873 } 874 875 // Perform lookup for Objective-C instance variables (including automatically 876 // synthesized instance variables), if we're in an Objective-C method. 877 // FIXME: This lookup really, really needs to be folded in to the normal 878 // unqualified lookup mechanism. 879 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 880 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 881 if (E.get() || E.isInvalid()) 882 return E; 883 } 884 885 bool SecondTry = false; 886 bool IsFilteredTemplateName = false; 887 888 Corrected: 889 switch (Result.getResultKind()) { 890 case LookupResult::NotFound: 891 // If an unqualified-id is followed by a '(', then we have a function 892 // call. 893 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 894 // In C++, this is an ADL-only call. 895 // FIXME: Reference? 896 if (getLangOpts().CPlusPlus) 897 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 898 899 // C90 6.3.2.2: 900 // If the expression that precedes the parenthesized argument list in a 901 // function call consists solely of an identifier, and if no 902 // declaration is visible for this identifier, the identifier is 903 // implicitly declared exactly as if, in the innermost block containing 904 // the function call, the declaration 905 // 906 // extern int identifier (); 907 // 908 // appeared. 909 // 910 // We also allow this in C99 as an extension. 911 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 912 Result.addDecl(D); 913 Result.resolveKind(); 914 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 915 } 916 } 917 918 // In C, we first see whether there is a tag type by the same name, in 919 // which case it's likely that the user just forgot to write "enum", 920 // "struct", or "union". 921 if (!getLangOpts().CPlusPlus && !SecondTry && 922 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 923 break; 924 } 925 926 // Perform typo correction to determine if there is another name that is 927 // close to this name. 928 if (!SecondTry && CCC) { 929 SecondTry = true; 930 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 931 Result.getLookupKind(), S, 932 &SS, std::move(CCC), 933 CTK_ErrorRecovery)) { 934 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 935 unsigned QualifiedDiag = diag::err_no_member_suggest; 936 937 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 938 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 939 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 940 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 941 UnqualifiedDiag = diag::err_no_template_suggest; 942 QualifiedDiag = diag::err_no_member_template_suggest; 943 } else if (UnderlyingFirstDecl && 944 (isa<TypeDecl>(UnderlyingFirstDecl) || 945 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 946 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 947 UnqualifiedDiag = diag::err_unknown_typename_suggest; 948 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 949 } 950 951 if (SS.isEmpty()) { 952 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 953 } else {// FIXME: is this even reachable? Test it. 954 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 955 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 956 Name->getName().equals(CorrectedStr); 957 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 958 << Name << computeDeclContext(SS, false) 959 << DroppedSpecifier << SS.getRange()); 960 } 961 962 // Update the name, so that the caller has the new name. 963 Name = Corrected.getCorrectionAsIdentifierInfo(); 964 965 // Typo correction corrected to a keyword. 966 if (Corrected.isKeyword()) 967 return Name; 968 969 // Also update the LookupResult... 970 // FIXME: This should probably go away at some point 971 Result.clear(); 972 Result.setLookupName(Corrected.getCorrection()); 973 if (FirstDecl) 974 Result.addDecl(FirstDecl); 975 976 // If we found an Objective-C instance variable, let 977 // LookupInObjCMethod build the appropriate expression to 978 // reference the ivar. 979 // FIXME: This is a gross hack. 980 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 981 Result.clear(); 982 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 983 return E; 984 } 985 986 goto Corrected; 987 } 988 } 989 990 // We failed to correct; just fall through and let the parser deal with it. 991 Result.suppressDiagnostics(); 992 return NameClassification::Unknown(); 993 994 case LookupResult::NotFoundInCurrentInstantiation: { 995 // We performed name lookup into the current instantiation, and there were 996 // dependent bases, so we treat this result the same way as any other 997 // dependent nested-name-specifier. 998 999 // C++ [temp.res]p2: 1000 // A name used in a template declaration or definition and that is 1001 // dependent on a template-parameter is assumed not to name a type 1002 // unless the applicable name lookup finds a type name or the name is 1003 // qualified by the keyword typename. 1004 // 1005 // FIXME: If the next token is '<', we might want to ask the parser to 1006 // perform some heroics to see if we actually have a 1007 // template-argument-list, which would indicate a missing 'template' 1008 // keyword here. 1009 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1010 NameInfo, IsAddressOfOperand, 1011 /*TemplateArgs=*/nullptr); 1012 } 1013 1014 case LookupResult::Found: 1015 case LookupResult::FoundOverloaded: 1016 case LookupResult::FoundUnresolvedValue: 1017 break; 1018 1019 case LookupResult::Ambiguous: 1020 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1021 hasAnyAcceptableTemplateNames(Result)) { 1022 // C++ [temp.local]p3: 1023 // A lookup that finds an injected-class-name (10.2) can result in an 1024 // ambiguity in certain cases (for example, if it is found in more than 1025 // one base class). If all of the injected-class-names that are found 1026 // refer to specializations of the same class template, and if the name 1027 // is followed by a template-argument-list, the reference refers to the 1028 // class template itself and not a specialization thereof, and is not 1029 // ambiguous. 1030 // 1031 // This filtering can make an ambiguous result into an unambiguous one, 1032 // so try again after filtering out template names. 1033 FilterAcceptableTemplateNames(Result); 1034 if (!Result.isAmbiguous()) { 1035 IsFilteredTemplateName = true; 1036 break; 1037 } 1038 } 1039 1040 // Diagnose the ambiguity and return an error. 1041 return NameClassification::Error(); 1042 } 1043 1044 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1045 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1046 // C++ [temp.names]p3: 1047 // After name lookup (3.4) finds that a name is a template-name or that 1048 // an operator-function-id or a literal- operator-id refers to a set of 1049 // overloaded functions any member of which is a function template if 1050 // this is followed by a <, the < is always taken as the delimiter of a 1051 // template-argument-list and never as the less-than operator. 1052 if (!IsFilteredTemplateName) 1053 FilterAcceptableTemplateNames(Result); 1054 1055 if (!Result.empty()) { 1056 bool IsFunctionTemplate; 1057 bool IsVarTemplate; 1058 TemplateName Template; 1059 if (Result.end() - Result.begin() > 1) { 1060 IsFunctionTemplate = true; 1061 Template = Context.getOverloadedTemplateName(Result.begin(), 1062 Result.end()); 1063 } else { 1064 TemplateDecl *TD 1065 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1066 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1067 IsVarTemplate = isa<VarTemplateDecl>(TD); 1068 1069 if (SS.isSet() && !SS.isInvalid()) 1070 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1071 /*TemplateKeyword=*/false, 1072 TD); 1073 else 1074 Template = TemplateName(TD); 1075 } 1076 1077 if (IsFunctionTemplate) { 1078 // Function templates always go through overload resolution, at which 1079 // point we'll perform the various checks (e.g., accessibility) we need 1080 // to based on which function we selected. 1081 Result.suppressDiagnostics(); 1082 1083 return NameClassification::FunctionTemplate(Template); 1084 } 1085 1086 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1087 : NameClassification::TypeTemplate(Template); 1088 } 1089 } 1090 1091 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1092 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1093 DiagnoseUseOfDecl(Type, NameLoc); 1094 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1095 QualType T = Context.getTypeDeclType(Type); 1096 if (SS.isNotEmpty()) 1097 return buildNestedType(*this, SS, T, NameLoc); 1098 return ParsedType::make(T); 1099 } 1100 1101 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1102 if (!Class) { 1103 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1104 if (ObjCCompatibleAliasDecl *Alias = 1105 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1106 Class = Alias->getClassInterface(); 1107 } 1108 1109 if (Class) { 1110 DiagnoseUseOfDecl(Class, NameLoc); 1111 1112 if (NextToken.is(tok::period)) { 1113 // Interface. <something> is parsed as a property reference expression. 1114 // Just return "unknown" as a fall-through for now. 1115 Result.suppressDiagnostics(); 1116 return NameClassification::Unknown(); 1117 } 1118 1119 QualType T = Context.getObjCInterfaceType(Class); 1120 return ParsedType::make(T); 1121 } 1122 1123 // We can have a type template here if we're classifying a template argument. 1124 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1125 !isa<VarTemplateDecl>(FirstDecl)) 1126 return NameClassification::TypeTemplate( 1127 TemplateName(cast<TemplateDecl>(FirstDecl))); 1128 1129 // Check for a tag type hidden by a non-type decl in a few cases where it 1130 // seems likely a type is wanted instead of the non-type that was found. 1131 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1132 if ((NextToken.is(tok::identifier) || 1133 (NextIsOp && 1134 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1135 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1136 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1137 DiagnoseUseOfDecl(Type, NameLoc); 1138 QualType T = Context.getTypeDeclType(Type); 1139 if (SS.isNotEmpty()) 1140 return buildNestedType(*this, SS, T, NameLoc); 1141 return ParsedType::make(T); 1142 } 1143 1144 if (FirstDecl->isCXXClassMember()) 1145 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1146 nullptr, S); 1147 1148 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1149 return BuildDeclarationNameExpr(SS, Result, ADL); 1150 } 1151 1152 Sema::TemplateNameKindForDiagnostics 1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1154 auto *TD = Name.getAsTemplateDecl(); 1155 if (!TD) 1156 return TemplateNameKindForDiagnostics::DependentTemplate; 1157 if (isa<ClassTemplateDecl>(TD)) 1158 return TemplateNameKindForDiagnostics::ClassTemplate; 1159 if (isa<FunctionTemplateDecl>(TD)) 1160 return TemplateNameKindForDiagnostics::FunctionTemplate; 1161 if (isa<VarTemplateDecl>(TD)) 1162 return TemplateNameKindForDiagnostics::VarTemplate; 1163 if (isa<TypeAliasTemplateDecl>(TD)) 1164 return TemplateNameKindForDiagnostics::AliasTemplate; 1165 if (isa<TemplateTemplateParmDecl>(TD)) 1166 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1167 return TemplateNameKindForDiagnostics::DependentTemplate; 1168 } 1169 1170 // Determines the context to return to after temporarily entering a 1171 // context. This depends in an unnecessarily complicated way on the 1172 // exact ordering of callbacks from the parser. 1173 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1174 1175 // Functions defined inline within classes aren't parsed until we've 1176 // finished parsing the top-level class, so the top-level class is 1177 // the context we'll need to return to. 1178 // A Lambda call operator whose parent is a class must not be treated 1179 // as an inline member function. A Lambda can be used legally 1180 // either as an in-class member initializer or a default argument. These 1181 // are parsed once the class has been marked complete and so the containing 1182 // context would be the nested class (when the lambda is defined in one); 1183 // If the class is not complete, then the lambda is being used in an 1184 // ill-formed fashion (such as to specify the width of a bit-field, or 1185 // in an array-bound) - in which case we still want to return the 1186 // lexically containing DC (which could be a nested class). 1187 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1188 DC = DC->getLexicalParent(); 1189 1190 // A function not defined within a class will always return to its 1191 // lexical context. 1192 if (!isa<CXXRecordDecl>(DC)) 1193 return DC; 1194 1195 // A C++ inline method/friend is parsed *after* the topmost class 1196 // it was declared in is fully parsed ("complete"); the topmost 1197 // class is the context we need to return to. 1198 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1199 DC = RD; 1200 1201 // Return the declaration context of the topmost class the inline method is 1202 // declared in. 1203 return DC; 1204 } 1205 1206 return DC->getLexicalParent(); 1207 } 1208 1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1210 assert(getContainingDC(DC) == CurContext && 1211 "The next DeclContext should be lexically contained in the current one."); 1212 CurContext = DC; 1213 S->setEntity(DC); 1214 } 1215 1216 void Sema::PopDeclContext() { 1217 assert(CurContext && "DeclContext imbalance!"); 1218 1219 CurContext = getContainingDC(CurContext); 1220 assert(CurContext && "Popped translation unit!"); 1221 } 1222 1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1224 Decl *D) { 1225 // Unlike PushDeclContext, the context to which we return is not necessarily 1226 // the containing DC of TD, because the new context will be some pre-existing 1227 // TagDecl definition instead of a fresh one. 1228 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1229 CurContext = cast<TagDecl>(D)->getDefinition(); 1230 assert(CurContext && "skipping definition of undefined tag"); 1231 // Start lookups from the parent of the current context; we don't want to look 1232 // into the pre-existing complete definition. 1233 S->setEntity(CurContext->getLookupParent()); 1234 return Result; 1235 } 1236 1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1238 CurContext = static_cast<decltype(CurContext)>(Context); 1239 } 1240 1241 /// EnterDeclaratorContext - Used when we must lookup names in the context 1242 /// of a declarator's nested name specifier. 1243 /// 1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1245 // C++0x [basic.lookup.unqual]p13: 1246 // A name used in the definition of a static data member of class 1247 // X (after the qualified-id of the static member) is looked up as 1248 // if the name was used in a member function of X. 1249 // C++0x [basic.lookup.unqual]p14: 1250 // If a variable member of a namespace is defined outside of the 1251 // scope of its namespace then any name used in the definition of 1252 // the variable member (after the declarator-id) is looked up as 1253 // if the definition of the variable member occurred in its 1254 // namespace. 1255 // Both of these imply that we should push a scope whose context 1256 // is the semantic context of the declaration. We can't use 1257 // PushDeclContext here because that context is not necessarily 1258 // lexically contained in the current context. Fortunately, 1259 // the containing scope should have the appropriate information. 1260 1261 assert(!S->getEntity() && "scope already has entity"); 1262 1263 #ifndef NDEBUG 1264 Scope *Ancestor = S->getParent(); 1265 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1266 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1267 #endif 1268 1269 CurContext = DC; 1270 S->setEntity(DC); 1271 } 1272 1273 void Sema::ExitDeclaratorContext(Scope *S) { 1274 assert(S->getEntity() == CurContext && "Context imbalance!"); 1275 1276 // Switch back to the lexical context. The safety of this is 1277 // enforced by an assert in EnterDeclaratorContext. 1278 Scope *Ancestor = S->getParent(); 1279 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1280 CurContext = Ancestor->getEntity(); 1281 1282 // We don't need to do anything with the scope, which is going to 1283 // disappear. 1284 } 1285 1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1287 // We assume that the caller has already called 1288 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1289 FunctionDecl *FD = D->getAsFunction(); 1290 if (!FD) 1291 return; 1292 1293 // Same implementation as PushDeclContext, but enters the context 1294 // from the lexical parent, rather than the top-level class. 1295 assert(CurContext == FD->getLexicalParent() && 1296 "The next DeclContext should be lexically contained in the current one."); 1297 CurContext = FD; 1298 S->setEntity(CurContext); 1299 1300 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1301 ParmVarDecl *Param = FD->getParamDecl(P); 1302 // If the parameter has an identifier, then add it to the scope 1303 if (Param->getIdentifier()) { 1304 S->AddDecl(Param); 1305 IdResolver.AddDecl(Param); 1306 } 1307 } 1308 } 1309 1310 void Sema::ActOnExitFunctionContext() { 1311 // Same implementation as PopDeclContext, but returns to the lexical parent, 1312 // rather than the top-level class. 1313 assert(CurContext && "DeclContext imbalance!"); 1314 CurContext = CurContext->getLexicalParent(); 1315 assert(CurContext && "Popped translation unit!"); 1316 } 1317 1318 /// Determine whether we allow overloading of the function 1319 /// PrevDecl with another declaration. 1320 /// 1321 /// This routine determines whether overloading is possible, not 1322 /// whether some new function is actually an overload. It will return 1323 /// true in C++ (where we can always provide overloads) or, as an 1324 /// extension, in C when the previous function is already an 1325 /// overloaded function declaration or has the "overloadable" 1326 /// attribute. 1327 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1328 ASTContext &Context, 1329 const FunctionDecl *New) { 1330 if (Context.getLangOpts().CPlusPlus) 1331 return true; 1332 1333 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1334 return true; 1335 1336 return Previous.getResultKind() == LookupResult::Found && 1337 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1338 New->hasAttr<OverloadableAttr>()); 1339 } 1340 1341 /// Add this decl to the scope shadowed decl chains. 1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1343 // Move up the scope chain until we find the nearest enclosing 1344 // non-transparent context. The declaration will be introduced into this 1345 // scope. 1346 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1347 S = S->getParent(); 1348 1349 // Add scoped declarations into their context, so that they can be 1350 // found later. Declarations without a context won't be inserted 1351 // into any context. 1352 if (AddToContext) 1353 CurContext->addDecl(D); 1354 1355 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1356 // are function-local declarations. 1357 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1358 !D->getDeclContext()->getRedeclContext()->Equals( 1359 D->getLexicalDeclContext()->getRedeclContext()) && 1360 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1361 return; 1362 1363 // Template instantiations should also not be pushed into scope. 1364 if (isa<FunctionDecl>(D) && 1365 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1366 return; 1367 1368 // If this replaces anything in the current scope, 1369 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1370 IEnd = IdResolver.end(); 1371 for (; I != IEnd; ++I) { 1372 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1373 S->RemoveDecl(*I); 1374 IdResolver.RemoveDecl(*I); 1375 1376 // Should only need to replace one decl. 1377 break; 1378 } 1379 } 1380 1381 S->AddDecl(D); 1382 1383 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1384 // Implicitly-generated labels may end up getting generated in an order that 1385 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1386 // the label at the appropriate place in the identifier chain. 1387 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1388 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1389 if (IDC == CurContext) { 1390 if (!S->isDeclScope(*I)) 1391 continue; 1392 } else if (IDC->Encloses(CurContext)) 1393 break; 1394 } 1395 1396 IdResolver.InsertDeclAfter(I, D); 1397 } else { 1398 IdResolver.AddDecl(D); 1399 } 1400 } 1401 1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1403 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1404 TUScope->AddDecl(D); 1405 } 1406 1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1408 bool AllowInlineNamespace) { 1409 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1410 } 1411 1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1413 DeclContext *TargetDC = DC->getPrimaryContext(); 1414 do { 1415 if (DeclContext *ScopeDC = S->getEntity()) 1416 if (ScopeDC->getPrimaryContext() == TargetDC) 1417 return S; 1418 } while ((S = S->getParent())); 1419 1420 return nullptr; 1421 } 1422 1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1424 DeclContext*, 1425 ASTContext&); 1426 1427 /// Filters out lookup results that don't fall within the given scope 1428 /// as determined by isDeclInScope. 1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1430 bool ConsiderLinkage, 1431 bool AllowInlineNamespace) { 1432 LookupResult::Filter F = R.makeFilter(); 1433 while (F.hasNext()) { 1434 NamedDecl *D = F.next(); 1435 1436 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1437 continue; 1438 1439 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1440 continue; 1441 1442 F.erase(); 1443 } 1444 1445 F.done(); 1446 } 1447 1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1449 /// have compatible owning modules. 1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1451 // FIXME: The Modules TS is not clear about how friend declarations are 1452 // to be treated. It's not meaningful to have different owning modules for 1453 // linkage in redeclarations of the same entity, so for now allow the 1454 // redeclaration and change the owning modules to match. 1455 if (New->getFriendObjectKind() && 1456 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1457 New->setLocalOwningModule(Old->getOwningModule()); 1458 makeMergedDefinitionVisible(New); 1459 return false; 1460 } 1461 1462 Module *NewM = New->getOwningModule(); 1463 Module *OldM = Old->getOwningModule(); 1464 if (NewM == OldM) 1465 return false; 1466 1467 // FIXME: Check proclaimed-ownership-declarations here too. 1468 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit; 1469 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit; 1470 if (NewIsModuleInterface || OldIsModuleInterface) { 1471 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1472 // if a declaration of D [...] appears in the purview of a module, all 1473 // other such declarations shall appear in the purview of the same module 1474 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1475 << New 1476 << NewIsModuleInterface 1477 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1478 << OldIsModuleInterface 1479 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1480 Diag(Old->getLocation(), diag::note_previous_declaration); 1481 New->setInvalidDecl(); 1482 return true; 1483 } 1484 1485 return false; 1486 } 1487 1488 static bool isUsingDecl(NamedDecl *D) { 1489 return isa<UsingShadowDecl>(D) || 1490 isa<UnresolvedUsingTypenameDecl>(D) || 1491 isa<UnresolvedUsingValueDecl>(D); 1492 } 1493 1494 /// Removes using shadow declarations from the lookup results. 1495 static void RemoveUsingDecls(LookupResult &R) { 1496 LookupResult::Filter F = R.makeFilter(); 1497 while (F.hasNext()) 1498 if (isUsingDecl(F.next())) 1499 F.erase(); 1500 1501 F.done(); 1502 } 1503 1504 /// Check for this common pattern: 1505 /// @code 1506 /// class S { 1507 /// S(const S&); // DO NOT IMPLEMENT 1508 /// void operator=(const S&); // DO NOT IMPLEMENT 1509 /// }; 1510 /// @endcode 1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1512 // FIXME: Should check for private access too but access is set after we get 1513 // the decl here. 1514 if (D->doesThisDeclarationHaveABody()) 1515 return false; 1516 1517 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1518 return CD->isCopyConstructor(); 1519 return D->isCopyAssignmentOperator(); 1520 } 1521 1522 // We need this to handle 1523 // 1524 // typedef struct { 1525 // void *foo() { return 0; } 1526 // } A; 1527 // 1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1529 // for example. If 'A', foo will have external linkage. If we have '*A', 1530 // foo will have no linkage. Since we can't know until we get to the end 1531 // of the typedef, this function finds out if D might have non-external linkage. 1532 // Callers should verify at the end of the TU if it D has external linkage or 1533 // not. 1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1535 const DeclContext *DC = D->getDeclContext(); 1536 while (!DC->isTranslationUnit()) { 1537 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1538 if (!RD->hasNameForLinkage()) 1539 return true; 1540 } 1541 DC = DC->getParent(); 1542 } 1543 1544 return !D->isExternallyVisible(); 1545 } 1546 1547 // FIXME: This needs to be refactored; some other isInMainFile users want 1548 // these semantics. 1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1550 if (S.TUKind != TU_Complete) 1551 return false; 1552 return S.SourceMgr.isInMainFile(Loc); 1553 } 1554 1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1556 assert(D); 1557 1558 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1559 return false; 1560 1561 // Ignore all entities declared within templates, and out-of-line definitions 1562 // of members of class templates. 1563 if (D->getDeclContext()->isDependentContext() || 1564 D->getLexicalDeclContext()->isDependentContext()) 1565 return false; 1566 1567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1568 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1569 return false; 1570 // A non-out-of-line declaration of a member specialization was implicitly 1571 // instantiated; it's the out-of-line declaration that we're interested in. 1572 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1573 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1574 return false; 1575 1576 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1577 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1578 return false; 1579 } else { 1580 // 'static inline' functions are defined in headers; don't warn. 1581 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1582 return false; 1583 } 1584 1585 if (FD->doesThisDeclarationHaveABody() && 1586 Context.DeclMustBeEmitted(FD)) 1587 return false; 1588 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1589 // Constants and utility variables are defined in headers with internal 1590 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1591 // like "inline".) 1592 if (!isMainFileLoc(*this, VD->getLocation())) 1593 return false; 1594 1595 if (Context.DeclMustBeEmitted(VD)) 1596 return false; 1597 1598 if (VD->isStaticDataMember() && 1599 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1600 return false; 1601 if (VD->isStaticDataMember() && 1602 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1603 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1604 return false; 1605 1606 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1607 return false; 1608 } else { 1609 return false; 1610 } 1611 1612 // Only warn for unused decls internal to the translation unit. 1613 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1614 // for inline functions defined in the main source file, for instance. 1615 return mightHaveNonExternalLinkage(D); 1616 } 1617 1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1619 if (!D) 1620 return; 1621 1622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1623 const FunctionDecl *First = FD->getFirstDecl(); 1624 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1625 return; // First should already be in the vector. 1626 } 1627 1628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1629 const VarDecl *First = VD->getFirstDecl(); 1630 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1631 return; // First should already be in the vector. 1632 } 1633 1634 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1635 UnusedFileScopedDecls.push_back(D); 1636 } 1637 1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1639 if (D->isInvalidDecl()) 1640 return false; 1641 1642 bool Referenced = false; 1643 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1644 // For a decomposition declaration, warn if none of the bindings are 1645 // referenced, instead of if the variable itself is referenced (which 1646 // it is, by the bindings' expressions). 1647 for (auto *BD : DD->bindings()) { 1648 if (BD->isReferenced()) { 1649 Referenced = true; 1650 break; 1651 } 1652 } 1653 } else if (!D->getDeclName()) { 1654 return false; 1655 } else if (D->isReferenced() || D->isUsed()) { 1656 Referenced = true; 1657 } 1658 1659 if (Referenced || D->hasAttr<UnusedAttr>() || 1660 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1661 return false; 1662 1663 if (isa<LabelDecl>(D)) 1664 return true; 1665 1666 // Except for labels, we only care about unused decls that are local to 1667 // functions. 1668 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1669 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1670 // For dependent types, the diagnostic is deferred. 1671 WithinFunction = 1672 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1673 if (!WithinFunction) 1674 return false; 1675 1676 if (isa<TypedefNameDecl>(D)) 1677 return true; 1678 1679 // White-list anything that isn't a local variable. 1680 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1681 return false; 1682 1683 // Types of valid local variables should be complete, so this should succeed. 1684 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1685 1686 // White-list anything with an __attribute__((unused)) type. 1687 const auto *Ty = VD->getType().getTypePtr(); 1688 1689 // Only look at the outermost level of typedef. 1690 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1691 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1692 return false; 1693 } 1694 1695 // If we failed to complete the type for some reason, or if the type is 1696 // dependent, don't diagnose the variable. 1697 if (Ty->isIncompleteType() || Ty->isDependentType()) 1698 return false; 1699 1700 // Look at the element type to ensure that the warning behaviour is 1701 // consistent for both scalars and arrays. 1702 Ty = Ty->getBaseElementTypeUnsafe(); 1703 1704 if (const TagType *TT = Ty->getAs<TagType>()) { 1705 const TagDecl *Tag = TT->getDecl(); 1706 if (Tag->hasAttr<UnusedAttr>()) 1707 return false; 1708 1709 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1710 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1711 return false; 1712 1713 if (const Expr *Init = VD->getInit()) { 1714 if (const ExprWithCleanups *Cleanups = 1715 dyn_cast<ExprWithCleanups>(Init)) 1716 Init = Cleanups->getSubExpr(); 1717 const CXXConstructExpr *Construct = 1718 dyn_cast<CXXConstructExpr>(Init); 1719 if (Construct && !Construct->isElidable()) { 1720 CXXConstructorDecl *CD = Construct->getConstructor(); 1721 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1722 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1723 return false; 1724 } 1725 } 1726 } 1727 } 1728 1729 // TODO: __attribute__((unused)) templates? 1730 } 1731 1732 return true; 1733 } 1734 1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1736 FixItHint &Hint) { 1737 if (isa<LabelDecl>(D)) { 1738 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1739 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1740 true); 1741 if (AfterColon.isInvalid()) 1742 return; 1743 Hint = FixItHint::CreateRemoval( 1744 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1745 } 1746 } 1747 1748 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1749 if (D->getTypeForDecl()->isDependentType()) 1750 return; 1751 1752 for (auto *TmpD : D->decls()) { 1753 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1754 DiagnoseUnusedDecl(T); 1755 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1756 DiagnoseUnusedNestedTypedefs(R); 1757 } 1758 } 1759 1760 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1761 /// unless they are marked attr(unused). 1762 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1763 if (!ShouldDiagnoseUnusedDecl(D)) 1764 return; 1765 1766 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1767 // typedefs can be referenced later on, so the diagnostics are emitted 1768 // at end-of-translation-unit. 1769 UnusedLocalTypedefNameCandidates.insert(TD); 1770 return; 1771 } 1772 1773 FixItHint Hint; 1774 GenerateFixForUnusedDecl(D, Context, Hint); 1775 1776 unsigned DiagID; 1777 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1778 DiagID = diag::warn_unused_exception_param; 1779 else if (isa<LabelDecl>(D)) 1780 DiagID = diag::warn_unused_label; 1781 else 1782 DiagID = diag::warn_unused_variable; 1783 1784 Diag(D->getLocation(), DiagID) << D << Hint; 1785 } 1786 1787 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1788 // Verify that we have no forward references left. If so, there was a goto 1789 // or address of a label taken, but no definition of it. Label fwd 1790 // definitions are indicated with a null substmt which is also not a resolved 1791 // MS inline assembly label name. 1792 bool Diagnose = false; 1793 if (L->isMSAsmLabel()) 1794 Diagnose = !L->isResolvedMSAsmLabel(); 1795 else 1796 Diagnose = L->getStmt() == nullptr; 1797 if (Diagnose) 1798 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1799 } 1800 1801 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1802 S->mergeNRVOIntoParent(); 1803 1804 if (S->decl_empty()) return; 1805 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1806 "Scope shouldn't contain decls!"); 1807 1808 for (auto *TmpD : S->decls()) { 1809 assert(TmpD && "This decl didn't get pushed??"); 1810 1811 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1812 NamedDecl *D = cast<NamedDecl>(TmpD); 1813 1814 // Diagnose unused variables in this scope. 1815 if (!S->hasUnrecoverableErrorOccurred()) { 1816 DiagnoseUnusedDecl(D); 1817 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1818 DiagnoseUnusedNestedTypedefs(RD); 1819 } 1820 1821 if (!D->getDeclName()) continue; 1822 1823 // If this was a forward reference to a label, verify it was defined. 1824 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1825 CheckPoppedLabel(LD, *this); 1826 1827 // Remove this name from our lexical scope, and warn on it if we haven't 1828 // already. 1829 IdResolver.RemoveDecl(D); 1830 auto ShadowI = ShadowingDecls.find(D); 1831 if (ShadowI != ShadowingDecls.end()) { 1832 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1833 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1834 << D << FD << FD->getParent(); 1835 Diag(FD->getLocation(), diag::note_previous_declaration); 1836 } 1837 ShadowingDecls.erase(ShadowI); 1838 } 1839 } 1840 } 1841 1842 /// Look for an Objective-C class in the translation unit. 1843 /// 1844 /// \param Id The name of the Objective-C class we're looking for. If 1845 /// typo-correction fixes this name, the Id will be updated 1846 /// to the fixed name. 1847 /// 1848 /// \param IdLoc The location of the name in the translation unit. 1849 /// 1850 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1851 /// if there is no class with the given name. 1852 /// 1853 /// \returns The declaration of the named Objective-C class, or NULL if the 1854 /// class could not be found. 1855 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1856 SourceLocation IdLoc, 1857 bool DoTypoCorrection) { 1858 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1859 // creation from this context. 1860 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1861 1862 if (!IDecl && DoTypoCorrection) { 1863 // Perform typo correction at the given location, but only if we 1864 // find an Objective-C class name. 1865 if (TypoCorrection C = CorrectTypo( 1866 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1867 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1868 CTK_ErrorRecovery)) { 1869 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1870 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1871 Id = IDecl->getIdentifier(); 1872 } 1873 } 1874 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1875 // This routine must always return a class definition, if any. 1876 if (Def && Def->getDefinition()) 1877 Def = Def->getDefinition(); 1878 return Def; 1879 } 1880 1881 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1882 /// from S, where a non-field would be declared. This routine copes 1883 /// with the difference between C and C++ scoping rules in structs and 1884 /// unions. For example, the following code is well-formed in C but 1885 /// ill-formed in C++: 1886 /// @code 1887 /// struct S6 { 1888 /// enum { BAR } e; 1889 /// }; 1890 /// 1891 /// void test_S6() { 1892 /// struct S6 a; 1893 /// a.e = BAR; 1894 /// } 1895 /// @endcode 1896 /// For the declaration of BAR, this routine will return a different 1897 /// scope. The scope S will be the scope of the unnamed enumeration 1898 /// within S6. In C++, this routine will return the scope associated 1899 /// with S6, because the enumeration's scope is a transparent 1900 /// context but structures can contain non-field names. In C, this 1901 /// routine will return the translation unit scope, since the 1902 /// enumeration's scope is a transparent context and structures cannot 1903 /// contain non-field names. 1904 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1905 while (((S->getFlags() & Scope::DeclScope) == 0) || 1906 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1907 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1908 S = S->getParent(); 1909 return S; 1910 } 1911 1912 /// Looks up the declaration of "struct objc_super" and 1913 /// saves it for later use in building builtin declaration of 1914 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1915 /// pre-existing declaration exists no action takes place. 1916 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1917 IdentifierInfo *II) { 1918 if (!II->isStr("objc_msgSendSuper")) 1919 return; 1920 ASTContext &Context = ThisSema.Context; 1921 1922 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1923 SourceLocation(), Sema::LookupTagName); 1924 ThisSema.LookupName(Result, S); 1925 if (Result.getResultKind() == LookupResult::Found) 1926 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1927 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1928 } 1929 1930 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1931 switch (Error) { 1932 case ASTContext::GE_None: 1933 return ""; 1934 case ASTContext::GE_Missing_stdio: 1935 return "stdio.h"; 1936 case ASTContext::GE_Missing_setjmp: 1937 return "setjmp.h"; 1938 case ASTContext::GE_Missing_ucontext: 1939 return "ucontext.h"; 1940 } 1941 llvm_unreachable("unhandled error kind"); 1942 } 1943 1944 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1945 /// file scope. lazily create a decl for it. ForRedeclaration is true 1946 /// if we're creating this built-in in anticipation of redeclaring the 1947 /// built-in. 1948 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1949 Scope *S, bool ForRedeclaration, 1950 SourceLocation Loc) { 1951 LookupPredefedObjCSuperType(*this, S, II); 1952 1953 ASTContext::GetBuiltinTypeError Error; 1954 QualType R = Context.GetBuiltinType(ID, Error); 1955 if (Error) { 1956 if (ForRedeclaration) 1957 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1958 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1959 return nullptr; 1960 } 1961 1962 if (!ForRedeclaration && 1963 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1964 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1965 Diag(Loc, diag::ext_implicit_lib_function_decl) 1966 << Context.BuiltinInfo.getName(ID) << R; 1967 if (Context.BuiltinInfo.getHeaderName(ID) && 1968 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1969 Diag(Loc, diag::note_include_header_or_declare) 1970 << Context.BuiltinInfo.getHeaderName(ID) 1971 << Context.BuiltinInfo.getName(ID); 1972 } 1973 1974 if (R.isNull()) 1975 return nullptr; 1976 1977 DeclContext *Parent = Context.getTranslationUnitDecl(); 1978 if (getLangOpts().CPlusPlus) { 1979 LinkageSpecDecl *CLinkageDecl = 1980 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1981 LinkageSpecDecl::lang_c, false); 1982 CLinkageDecl->setImplicit(); 1983 Parent->addDecl(CLinkageDecl); 1984 Parent = CLinkageDecl; 1985 } 1986 1987 FunctionDecl *New = FunctionDecl::Create(Context, 1988 Parent, 1989 Loc, Loc, II, R, /*TInfo=*/nullptr, 1990 SC_Extern, 1991 false, 1992 R->isFunctionProtoType()); 1993 New->setImplicit(); 1994 1995 // Create Decl objects for each parameter, adding them to the 1996 // FunctionDecl. 1997 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1998 SmallVector<ParmVarDecl*, 16> Params; 1999 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2000 ParmVarDecl *parm = 2001 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2002 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2003 SC_None, nullptr); 2004 parm->setScopeInfo(0, i); 2005 Params.push_back(parm); 2006 } 2007 New->setParams(Params); 2008 } 2009 2010 AddKnownFunctionAttributes(New); 2011 RegisterLocallyScopedExternCDecl(New, S); 2012 2013 // TUScope is the translation-unit scope to insert this function into. 2014 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2015 // relate Scopes to DeclContexts, and probably eliminate CurContext 2016 // entirely, but we're not there yet. 2017 DeclContext *SavedContext = CurContext; 2018 CurContext = Parent; 2019 PushOnScopeChains(New, TUScope); 2020 CurContext = SavedContext; 2021 return New; 2022 } 2023 2024 /// Typedef declarations don't have linkage, but they still denote the same 2025 /// entity if their types are the same. 2026 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2027 /// isSameEntity. 2028 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2029 TypedefNameDecl *Decl, 2030 LookupResult &Previous) { 2031 // This is only interesting when modules are enabled. 2032 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2033 return; 2034 2035 // Empty sets are uninteresting. 2036 if (Previous.empty()) 2037 return; 2038 2039 LookupResult::Filter Filter = Previous.makeFilter(); 2040 while (Filter.hasNext()) { 2041 NamedDecl *Old = Filter.next(); 2042 2043 // Non-hidden declarations are never ignored. 2044 if (S.isVisible(Old)) 2045 continue; 2046 2047 // Declarations of the same entity are not ignored, even if they have 2048 // different linkages. 2049 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2050 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2051 Decl->getUnderlyingType())) 2052 continue; 2053 2054 // If both declarations give a tag declaration a typedef name for linkage 2055 // purposes, then they declare the same entity. 2056 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2057 Decl->getAnonDeclWithTypedefName()) 2058 continue; 2059 } 2060 2061 Filter.erase(); 2062 } 2063 2064 Filter.done(); 2065 } 2066 2067 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2068 QualType OldType; 2069 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2070 OldType = OldTypedef->getUnderlyingType(); 2071 else 2072 OldType = Context.getTypeDeclType(Old); 2073 QualType NewType = New->getUnderlyingType(); 2074 2075 if (NewType->isVariablyModifiedType()) { 2076 // Must not redefine a typedef with a variably-modified type. 2077 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2078 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2079 << Kind << NewType; 2080 if (Old->getLocation().isValid()) 2081 notePreviousDefinition(Old, New->getLocation()); 2082 New->setInvalidDecl(); 2083 return true; 2084 } 2085 2086 if (OldType != NewType && 2087 !OldType->isDependentType() && 2088 !NewType->isDependentType() && 2089 !Context.hasSameType(OldType, NewType)) { 2090 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2091 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2092 << Kind << NewType << OldType; 2093 if (Old->getLocation().isValid()) 2094 notePreviousDefinition(Old, New->getLocation()); 2095 New->setInvalidDecl(); 2096 return true; 2097 } 2098 return false; 2099 } 2100 2101 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2102 /// same name and scope as a previous declaration 'Old'. Figure out 2103 /// how to resolve this situation, merging decls or emitting 2104 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2105 /// 2106 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2107 LookupResult &OldDecls) { 2108 // If the new decl is known invalid already, don't bother doing any 2109 // merging checks. 2110 if (New->isInvalidDecl()) return; 2111 2112 // Allow multiple definitions for ObjC built-in typedefs. 2113 // FIXME: Verify the underlying types are equivalent! 2114 if (getLangOpts().ObjC) { 2115 const IdentifierInfo *TypeID = New->getIdentifier(); 2116 switch (TypeID->getLength()) { 2117 default: break; 2118 case 2: 2119 { 2120 if (!TypeID->isStr("id")) 2121 break; 2122 QualType T = New->getUnderlyingType(); 2123 if (!T->isPointerType()) 2124 break; 2125 if (!T->isVoidPointerType()) { 2126 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2127 if (!PT->isStructureType()) 2128 break; 2129 } 2130 Context.setObjCIdRedefinitionType(T); 2131 // Install the built-in type for 'id', ignoring the current definition. 2132 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2133 return; 2134 } 2135 case 5: 2136 if (!TypeID->isStr("Class")) 2137 break; 2138 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2139 // Install the built-in type for 'Class', ignoring the current definition. 2140 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2141 return; 2142 case 3: 2143 if (!TypeID->isStr("SEL")) 2144 break; 2145 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2146 // Install the built-in type for 'SEL', ignoring the current definition. 2147 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2148 return; 2149 } 2150 // Fall through - the typedef name was not a builtin type. 2151 } 2152 2153 // Verify the old decl was also a type. 2154 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2155 if (!Old) { 2156 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2157 << New->getDeclName(); 2158 2159 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2160 if (OldD->getLocation().isValid()) 2161 notePreviousDefinition(OldD, New->getLocation()); 2162 2163 return New->setInvalidDecl(); 2164 } 2165 2166 // If the old declaration is invalid, just give up here. 2167 if (Old->isInvalidDecl()) 2168 return New->setInvalidDecl(); 2169 2170 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2171 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2172 auto *NewTag = New->getAnonDeclWithTypedefName(); 2173 NamedDecl *Hidden = nullptr; 2174 if (OldTag && NewTag && 2175 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2176 !hasVisibleDefinition(OldTag, &Hidden)) { 2177 // There is a definition of this tag, but it is not visible. Use it 2178 // instead of our tag. 2179 New->setTypeForDecl(OldTD->getTypeForDecl()); 2180 if (OldTD->isModed()) 2181 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2182 OldTD->getUnderlyingType()); 2183 else 2184 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2185 2186 // Make the old tag definition visible. 2187 makeMergedDefinitionVisible(Hidden); 2188 2189 // If this was an unscoped enumeration, yank all of its enumerators 2190 // out of the scope. 2191 if (isa<EnumDecl>(NewTag)) { 2192 Scope *EnumScope = getNonFieldDeclScope(S); 2193 for (auto *D : NewTag->decls()) { 2194 auto *ED = cast<EnumConstantDecl>(D); 2195 assert(EnumScope->isDeclScope(ED)); 2196 EnumScope->RemoveDecl(ED); 2197 IdResolver.RemoveDecl(ED); 2198 ED->getLexicalDeclContext()->removeDecl(ED); 2199 } 2200 } 2201 } 2202 } 2203 2204 // If the typedef types are not identical, reject them in all languages and 2205 // with any extensions enabled. 2206 if (isIncompatibleTypedef(Old, New)) 2207 return; 2208 2209 // The types match. Link up the redeclaration chain and merge attributes if 2210 // the old declaration was a typedef. 2211 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2212 New->setPreviousDecl(Typedef); 2213 mergeDeclAttributes(New, Old); 2214 } 2215 2216 if (getLangOpts().MicrosoftExt) 2217 return; 2218 2219 if (getLangOpts().CPlusPlus) { 2220 // C++ [dcl.typedef]p2: 2221 // In a given non-class scope, a typedef specifier can be used to 2222 // redefine the name of any type declared in that scope to refer 2223 // to the type to which it already refers. 2224 if (!isa<CXXRecordDecl>(CurContext)) 2225 return; 2226 2227 // C++0x [dcl.typedef]p4: 2228 // In a given class scope, a typedef specifier can be used to redefine 2229 // any class-name declared in that scope that is not also a typedef-name 2230 // to refer to the type to which it already refers. 2231 // 2232 // This wording came in via DR424, which was a correction to the 2233 // wording in DR56, which accidentally banned code like: 2234 // 2235 // struct S { 2236 // typedef struct A { } A; 2237 // }; 2238 // 2239 // in the C++03 standard. We implement the C++0x semantics, which 2240 // allow the above but disallow 2241 // 2242 // struct S { 2243 // typedef int I; 2244 // typedef int I; 2245 // }; 2246 // 2247 // since that was the intent of DR56. 2248 if (!isa<TypedefNameDecl>(Old)) 2249 return; 2250 2251 Diag(New->getLocation(), diag::err_redefinition) 2252 << New->getDeclName(); 2253 notePreviousDefinition(Old, New->getLocation()); 2254 return New->setInvalidDecl(); 2255 } 2256 2257 // Modules always permit redefinition of typedefs, as does C11. 2258 if (getLangOpts().Modules || getLangOpts().C11) 2259 return; 2260 2261 // If we have a redefinition of a typedef in C, emit a warning. This warning 2262 // is normally mapped to an error, but can be controlled with 2263 // -Wtypedef-redefinition. If either the original or the redefinition is 2264 // in a system header, don't emit this for compatibility with GCC. 2265 if (getDiagnostics().getSuppressSystemWarnings() && 2266 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2267 (Old->isImplicit() || 2268 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2269 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2270 return; 2271 2272 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2273 << New->getDeclName(); 2274 notePreviousDefinition(Old, New->getLocation()); 2275 } 2276 2277 /// DeclhasAttr - returns true if decl Declaration already has the target 2278 /// attribute. 2279 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2280 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2281 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2282 for (const auto *i : D->attrs()) 2283 if (i->getKind() == A->getKind()) { 2284 if (Ann) { 2285 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2286 return true; 2287 continue; 2288 } 2289 // FIXME: Don't hardcode this check 2290 if (OA && isa<OwnershipAttr>(i)) 2291 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2292 return true; 2293 } 2294 2295 return false; 2296 } 2297 2298 static bool isAttributeTargetADefinition(Decl *D) { 2299 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2300 return VD->isThisDeclarationADefinition(); 2301 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2302 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2303 return true; 2304 } 2305 2306 /// Merge alignment attributes from \p Old to \p New, taking into account the 2307 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2308 /// 2309 /// \return \c true if any attributes were added to \p New. 2310 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2311 // Look for alignas attributes on Old, and pick out whichever attribute 2312 // specifies the strictest alignment requirement. 2313 AlignedAttr *OldAlignasAttr = nullptr; 2314 AlignedAttr *OldStrictestAlignAttr = nullptr; 2315 unsigned OldAlign = 0; 2316 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2317 // FIXME: We have no way of representing inherited dependent alignments 2318 // in a case like: 2319 // template<int A, int B> struct alignas(A) X; 2320 // template<int A, int B> struct alignas(B) X {}; 2321 // For now, we just ignore any alignas attributes which are not on the 2322 // definition in such a case. 2323 if (I->isAlignmentDependent()) 2324 return false; 2325 2326 if (I->isAlignas()) 2327 OldAlignasAttr = I; 2328 2329 unsigned Align = I->getAlignment(S.Context); 2330 if (Align > OldAlign) { 2331 OldAlign = Align; 2332 OldStrictestAlignAttr = I; 2333 } 2334 } 2335 2336 // Look for alignas attributes on New. 2337 AlignedAttr *NewAlignasAttr = nullptr; 2338 unsigned NewAlign = 0; 2339 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2340 if (I->isAlignmentDependent()) 2341 return false; 2342 2343 if (I->isAlignas()) 2344 NewAlignasAttr = I; 2345 2346 unsigned Align = I->getAlignment(S.Context); 2347 if (Align > NewAlign) 2348 NewAlign = Align; 2349 } 2350 2351 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2352 // Both declarations have 'alignas' attributes. We require them to match. 2353 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2354 // fall short. (If two declarations both have alignas, they must both match 2355 // every definition, and so must match each other if there is a definition.) 2356 2357 // If either declaration only contains 'alignas(0)' specifiers, then it 2358 // specifies the natural alignment for the type. 2359 if (OldAlign == 0 || NewAlign == 0) { 2360 QualType Ty; 2361 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2362 Ty = VD->getType(); 2363 else 2364 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2365 2366 if (OldAlign == 0) 2367 OldAlign = S.Context.getTypeAlign(Ty); 2368 if (NewAlign == 0) 2369 NewAlign = S.Context.getTypeAlign(Ty); 2370 } 2371 2372 if (OldAlign != NewAlign) { 2373 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2374 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2375 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2376 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2377 } 2378 } 2379 2380 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2381 // C++11 [dcl.align]p6: 2382 // if any declaration of an entity has an alignment-specifier, 2383 // every defining declaration of that entity shall specify an 2384 // equivalent alignment. 2385 // C11 6.7.5/7: 2386 // If the definition of an object does not have an alignment 2387 // specifier, any other declaration of that object shall also 2388 // have no alignment specifier. 2389 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2390 << OldAlignasAttr; 2391 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2392 << OldAlignasAttr; 2393 } 2394 2395 bool AnyAdded = false; 2396 2397 // Ensure we have an attribute representing the strictest alignment. 2398 if (OldAlign > NewAlign) { 2399 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2400 Clone->setInherited(true); 2401 New->addAttr(Clone); 2402 AnyAdded = true; 2403 } 2404 2405 // Ensure we have an alignas attribute if the old declaration had one. 2406 if (OldAlignasAttr && !NewAlignasAttr && 2407 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2408 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2409 Clone->setInherited(true); 2410 New->addAttr(Clone); 2411 AnyAdded = true; 2412 } 2413 2414 return AnyAdded; 2415 } 2416 2417 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2418 const InheritableAttr *Attr, 2419 Sema::AvailabilityMergeKind AMK) { 2420 // This function copies an attribute Attr from a previous declaration to the 2421 // new declaration D if the new declaration doesn't itself have that attribute 2422 // yet or if that attribute allows duplicates. 2423 // If you're adding a new attribute that requires logic different from 2424 // "use explicit attribute on decl if present, else use attribute from 2425 // previous decl", for example if the attribute needs to be consistent 2426 // between redeclarations, you need to call a custom merge function here. 2427 InheritableAttr *NewAttr = nullptr; 2428 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2429 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2430 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2431 AA->isImplicit(), AA->getIntroduced(), 2432 AA->getDeprecated(), 2433 AA->getObsoleted(), AA->getUnavailable(), 2434 AA->getMessage(), AA->getStrict(), 2435 AA->getReplacement(), AMK, 2436 AttrSpellingListIndex); 2437 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2438 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2439 AttrSpellingListIndex); 2440 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2441 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2442 AttrSpellingListIndex); 2443 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2444 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2445 AttrSpellingListIndex); 2446 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2447 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2448 AttrSpellingListIndex); 2449 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2450 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2451 FA->getFormatIdx(), FA->getFirstArg(), 2452 AttrSpellingListIndex); 2453 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2454 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2455 AttrSpellingListIndex); 2456 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2457 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(), 2458 AttrSpellingListIndex); 2459 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2460 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2461 AttrSpellingListIndex, 2462 IA->getSemanticSpelling()); 2463 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2464 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2465 &S.Context.Idents.get(AA->getSpelling()), 2466 AttrSpellingListIndex); 2467 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2468 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2469 isa<CUDAGlobalAttr>(Attr))) { 2470 // CUDA target attributes are part of function signature for 2471 // overloading purposes and must not be merged. 2472 return false; 2473 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2474 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2475 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2476 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2477 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2478 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2479 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2480 NewAttr = S.mergeCommonAttr(D, *CommonA); 2481 else if (isa<AlignedAttr>(Attr)) 2482 // AlignedAttrs are handled separately, because we need to handle all 2483 // such attributes on a declaration at the same time. 2484 NewAttr = nullptr; 2485 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2486 (AMK == Sema::AMK_Override || 2487 AMK == Sema::AMK_ProtocolImplementation)) 2488 NewAttr = nullptr; 2489 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2490 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2491 UA->getGuid()); 2492 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2493 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2494 2495 if (NewAttr) { 2496 NewAttr->setInherited(true); 2497 D->addAttr(NewAttr); 2498 if (isa<MSInheritanceAttr>(NewAttr)) 2499 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2500 return true; 2501 } 2502 2503 return false; 2504 } 2505 2506 static const NamedDecl *getDefinition(const Decl *D) { 2507 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2508 return TD->getDefinition(); 2509 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2510 const VarDecl *Def = VD->getDefinition(); 2511 if (Def) 2512 return Def; 2513 return VD->getActingDefinition(); 2514 } 2515 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2516 return FD->getDefinition(); 2517 return nullptr; 2518 } 2519 2520 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2521 for (const auto *Attribute : D->attrs()) 2522 if (Attribute->getKind() == Kind) 2523 return true; 2524 return false; 2525 } 2526 2527 /// checkNewAttributesAfterDef - If we already have a definition, check that 2528 /// there are no new attributes in this declaration. 2529 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2530 if (!New->hasAttrs()) 2531 return; 2532 2533 const NamedDecl *Def = getDefinition(Old); 2534 if (!Def || Def == New) 2535 return; 2536 2537 AttrVec &NewAttributes = New->getAttrs(); 2538 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2539 const Attr *NewAttribute = NewAttributes[I]; 2540 2541 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2542 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2543 Sema::SkipBodyInfo SkipBody; 2544 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2545 2546 // If we're skipping this definition, drop the "alias" attribute. 2547 if (SkipBody.ShouldSkip) { 2548 NewAttributes.erase(NewAttributes.begin() + I); 2549 --E; 2550 continue; 2551 } 2552 } else { 2553 VarDecl *VD = cast<VarDecl>(New); 2554 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2555 VarDecl::TentativeDefinition 2556 ? diag::err_alias_after_tentative 2557 : diag::err_redefinition; 2558 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2559 if (Diag == diag::err_redefinition) 2560 S.notePreviousDefinition(Def, VD->getLocation()); 2561 else 2562 S.Diag(Def->getLocation(), diag::note_previous_definition); 2563 VD->setInvalidDecl(); 2564 } 2565 ++I; 2566 continue; 2567 } 2568 2569 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2570 // Tentative definitions are only interesting for the alias check above. 2571 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2572 ++I; 2573 continue; 2574 } 2575 } 2576 2577 if (hasAttribute(Def, NewAttribute->getKind())) { 2578 ++I; 2579 continue; // regular attr merging will take care of validating this. 2580 } 2581 2582 if (isa<C11NoReturnAttr>(NewAttribute)) { 2583 // C's _Noreturn is allowed to be added to a function after it is defined. 2584 ++I; 2585 continue; 2586 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2587 if (AA->isAlignas()) { 2588 // C++11 [dcl.align]p6: 2589 // if any declaration of an entity has an alignment-specifier, 2590 // every defining declaration of that entity shall specify an 2591 // equivalent alignment. 2592 // C11 6.7.5/7: 2593 // If the definition of an object does not have an alignment 2594 // specifier, any other declaration of that object shall also 2595 // have no alignment specifier. 2596 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2597 << AA; 2598 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2599 << AA; 2600 NewAttributes.erase(NewAttributes.begin() + I); 2601 --E; 2602 continue; 2603 } 2604 } 2605 2606 S.Diag(NewAttribute->getLocation(), 2607 diag::warn_attribute_precede_definition); 2608 S.Diag(Def->getLocation(), diag::note_previous_definition); 2609 NewAttributes.erase(NewAttributes.begin() + I); 2610 --E; 2611 } 2612 } 2613 2614 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2615 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2616 AvailabilityMergeKind AMK) { 2617 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2618 UsedAttr *NewAttr = OldAttr->clone(Context); 2619 NewAttr->setInherited(true); 2620 New->addAttr(NewAttr); 2621 } 2622 2623 if (!Old->hasAttrs() && !New->hasAttrs()) 2624 return; 2625 2626 // Attributes declared post-definition are currently ignored. 2627 checkNewAttributesAfterDef(*this, New, Old); 2628 2629 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2630 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2631 if (OldA->getLabel() != NewA->getLabel()) { 2632 // This redeclaration changes __asm__ label. 2633 Diag(New->getLocation(), diag::err_different_asm_label); 2634 Diag(OldA->getLocation(), diag::note_previous_declaration); 2635 } 2636 } else if (Old->isUsed()) { 2637 // This redeclaration adds an __asm__ label to a declaration that has 2638 // already been ODR-used. 2639 Diag(New->getLocation(), diag::err_late_asm_label_name) 2640 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2641 } 2642 } 2643 2644 // Re-declaration cannot add abi_tag's. 2645 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2646 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2647 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2648 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2649 NewTag) == OldAbiTagAttr->tags_end()) { 2650 Diag(NewAbiTagAttr->getLocation(), 2651 diag::err_new_abi_tag_on_redeclaration) 2652 << NewTag; 2653 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2654 } 2655 } 2656 } else { 2657 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2658 Diag(Old->getLocation(), diag::note_previous_declaration); 2659 } 2660 } 2661 2662 // This redeclaration adds a section attribute. 2663 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2664 if (auto *VD = dyn_cast<VarDecl>(New)) { 2665 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2666 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2667 Diag(Old->getLocation(), diag::note_previous_declaration); 2668 } 2669 } 2670 } 2671 2672 // Redeclaration adds code-seg attribute. 2673 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2674 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2675 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2676 Diag(New->getLocation(), diag::warn_mismatched_section) 2677 << 0 /*codeseg*/; 2678 Diag(Old->getLocation(), diag::note_previous_declaration); 2679 } 2680 2681 if (!Old->hasAttrs()) 2682 return; 2683 2684 bool foundAny = New->hasAttrs(); 2685 2686 // Ensure that any moving of objects within the allocated map is done before 2687 // we process them. 2688 if (!foundAny) New->setAttrs(AttrVec()); 2689 2690 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2691 // Ignore deprecated/unavailable/availability attributes if requested. 2692 AvailabilityMergeKind LocalAMK = AMK_None; 2693 if (isa<DeprecatedAttr>(I) || 2694 isa<UnavailableAttr>(I) || 2695 isa<AvailabilityAttr>(I)) { 2696 switch (AMK) { 2697 case AMK_None: 2698 continue; 2699 2700 case AMK_Redeclaration: 2701 case AMK_Override: 2702 case AMK_ProtocolImplementation: 2703 LocalAMK = AMK; 2704 break; 2705 } 2706 } 2707 2708 // Already handled. 2709 if (isa<UsedAttr>(I)) 2710 continue; 2711 2712 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2713 foundAny = true; 2714 } 2715 2716 if (mergeAlignedAttrs(*this, New, Old)) 2717 foundAny = true; 2718 2719 if (!foundAny) New->dropAttrs(); 2720 } 2721 2722 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2723 /// to the new one. 2724 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2725 const ParmVarDecl *oldDecl, 2726 Sema &S) { 2727 // C++11 [dcl.attr.depend]p2: 2728 // The first declaration of a function shall specify the 2729 // carries_dependency attribute for its declarator-id if any declaration 2730 // of the function specifies the carries_dependency attribute. 2731 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2732 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2733 S.Diag(CDA->getLocation(), 2734 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2735 // Find the first declaration of the parameter. 2736 // FIXME: Should we build redeclaration chains for function parameters? 2737 const FunctionDecl *FirstFD = 2738 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2739 const ParmVarDecl *FirstVD = 2740 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2741 S.Diag(FirstVD->getLocation(), 2742 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2743 } 2744 2745 if (!oldDecl->hasAttrs()) 2746 return; 2747 2748 bool foundAny = newDecl->hasAttrs(); 2749 2750 // Ensure that any moving of objects within the allocated map is 2751 // done before we process them. 2752 if (!foundAny) newDecl->setAttrs(AttrVec()); 2753 2754 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2755 if (!DeclHasAttr(newDecl, I)) { 2756 InheritableAttr *newAttr = 2757 cast<InheritableParamAttr>(I->clone(S.Context)); 2758 newAttr->setInherited(true); 2759 newDecl->addAttr(newAttr); 2760 foundAny = true; 2761 } 2762 } 2763 2764 if (!foundAny) newDecl->dropAttrs(); 2765 } 2766 2767 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2768 const ParmVarDecl *OldParam, 2769 Sema &S) { 2770 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2771 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2772 if (*Oldnullability != *Newnullability) { 2773 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2774 << DiagNullabilityKind( 2775 *Newnullability, 2776 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2777 != 0)) 2778 << DiagNullabilityKind( 2779 *Oldnullability, 2780 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2781 != 0)); 2782 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2783 } 2784 } else { 2785 QualType NewT = NewParam->getType(); 2786 NewT = S.Context.getAttributedType( 2787 AttributedType::getNullabilityAttrKind(*Oldnullability), 2788 NewT, NewT); 2789 NewParam->setType(NewT); 2790 } 2791 } 2792 } 2793 2794 namespace { 2795 2796 /// Used in MergeFunctionDecl to keep track of function parameters in 2797 /// C. 2798 struct GNUCompatibleParamWarning { 2799 ParmVarDecl *OldParm; 2800 ParmVarDecl *NewParm; 2801 QualType PromotedType; 2802 }; 2803 2804 } // end anonymous namespace 2805 2806 /// getSpecialMember - get the special member enum for a method. 2807 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2808 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2809 if (Ctor->isDefaultConstructor()) 2810 return Sema::CXXDefaultConstructor; 2811 2812 if (Ctor->isCopyConstructor()) 2813 return Sema::CXXCopyConstructor; 2814 2815 if (Ctor->isMoveConstructor()) 2816 return Sema::CXXMoveConstructor; 2817 } else if (isa<CXXDestructorDecl>(MD)) { 2818 return Sema::CXXDestructor; 2819 } else if (MD->isCopyAssignmentOperator()) { 2820 return Sema::CXXCopyAssignment; 2821 } else if (MD->isMoveAssignmentOperator()) { 2822 return Sema::CXXMoveAssignment; 2823 } 2824 2825 return Sema::CXXInvalid; 2826 } 2827 2828 // Determine whether the previous declaration was a definition, implicit 2829 // declaration, or a declaration. 2830 template <typename T> 2831 static std::pair<diag::kind, SourceLocation> 2832 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2833 diag::kind PrevDiag; 2834 SourceLocation OldLocation = Old->getLocation(); 2835 if (Old->isThisDeclarationADefinition()) 2836 PrevDiag = diag::note_previous_definition; 2837 else if (Old->isImplicit()) { 2838 PrevDiag = diag::note_previous_implicit_declaration; 2839 if (OldLocation.isInvalid()) 2840 OldLocation = New->getLocation(); 2841 } else 2842 PrevDiag = diag::note_previous_declaration; 2843 return std::make_pair(PrevDiag, OldLocation); 2844 } 2845 2846 /// canRedefineFunction - checks if a function can be redefined. Currently, 2847 /// only extern inline functions can be redefined, and even then only in 2848 /// GNU89 mode. 2849 static bool canRedefineFunction(const FunctionDecl *FD, 2850 const LangOptions& LangOpts) { 2851 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2852 !LangOpts.CPlusPlus && 2853 FD->isInlineSpecified() && 2854 FD->getStorageClass() == SC_Extern); 2855 } 2856 2857 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2858 const AttributedType *AT = T->getAs<AttributedType>(); 2859 while (AT && !AT->isCallingConv()) 2860 AT = AT->getModifiedType()->getAs<AttributedType>(); 2861 return AT; 2862 } 2863 2864 template <typename T> 2865 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2866 const DeclContext *DC = Old->getDeclContext(); 2867 if (DC->isRecord()) 2868 return false; 2869 2870 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2871 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2872 return true; 2873 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2874 return true; 2875 return false; 2876 } 2877 2878 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2879 static bool isExternC(VarTemplateDecl *) { return false; } 2880 2881 /// Check whether a redeclaration of an entity introduced by a 2882 /// using-declaration is valid, given that we know it's not an overload 2883 /// (nor a hidden tag declaration). 2884 template<typename ExpectedDecl> 2885 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2886 ExpectedDecl *New) { 2887 // C++11 [basic.scope.declarative]p4: 2888 // Given a set of declarations in a single declarative region, each of 2889 // which specifies the same unqualified name, 2890 // -- they shall all refer to the same entity, or all refer to functions 2891 // and function templates; or 2892 // -- exactly one declaration shall declare a class name or enumeration 2893 // name that is not a typedef name and the other declarations shall all 2894 // refer to the same variable or enumerator, or all refer to functions 2895 // and function templates; in this case the class name or enumeration 2896 // name is hidden (3.3.10). 2897 2898 // C++11 [namespace.udecl]p14: 2899 // If a function declaration in namespace scope or block scope has the 2900 // same name and the same parameter-type-list as a function introduced 2901 // by a using-declaration, and the declarations do not declare the same 2902 // function, the program is ill-formed. 2903 2904 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2905 if (Old && 2906 !Old->getDeclContext()->getRedeclContext()->Equals( 2907 New->getDeclContext()->getRedeclContext()) && 2908 !(isExternC(Old) && isExternC(New))) 2909 Old = nullptr; 2910 2911 if (!Old) { 2912 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2913 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2914 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2915 return true; 2916 } 2917 return false; 2918 } 2919 2920 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2921 const FunctionDecl *B) { 2922 assert(A->getNumParams() == B->getNumParams()); 2923 2924 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2925 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2926 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2927 if (AttrA == AttrB) 2928 return true; 2929 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2930 }; 2931 2932 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2933 } 2934 2935 /// If necessary, adjust the semantic declaration context for a qualified 2936 /// declaration to name the correct inline namespace within the qualifier. 2937 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2938 DeclaratorDecl *OldD) { 2939 // The only case where we need to update the DeclContext is when 2940 // redeclaration lookup for a qualified name finds a declaration 2941 // in an inline namespace within the context named by the qualifier: 2942 // 2943 // inline namespace N { int f(); } 2944 // int ::f(); // Sema DC needs adjusting from :: to N::. 2945 // 2946 // For unqualified declarations, the semantic context *can* change 2947 // along the redeclaration chain (for local extern declarations, 2948 // extern "C" declarations, and friend declarations in particular). 2949 if (!NewD->getQualifier()) 2950 return; 2951 2952 // NewD is probably already in the right context. 2953 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2954 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2955 if (NamedDC->Equals(SemaDC)) 2956 return; 2957 2958 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2959 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2960 "unexpected context for redeclaration"); 2961 2962 auto *LexDC = NewD->getLexicalDeclContext(); 2963 auto FixSemaDC = [=](NamedDecl *D) { 2964 if (!D) 2965 return; 2966 D->setDeclContext(SemaDC); 2967 D->setLexicalDeclContext(LexDC); 2968 }; 2969 2970 FixSemaDC(NewD); 2971 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 2972 FixSemaDC(FD->getDescribedFunctionTemplate()); 2973 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 2974 FixSemaDC(VD->getDescribedVarTemplate()); 2975 } 2976 2977 /// MergeFunctionDecl - We just parsed a function 'New' from 2978 /// declarator D which has the same name and scope as a previous 2979 /// declaration 'Old'. Figure out how to resolve this situation, 2980 /// merging decls or emitting diagnostics as appropriate. 2981 /// 2982 /// In C++, New and Old must be declarations that are not 2983 /// overloaded. Use IsOverload to determine whether New and Old are 2984 /// overloaded, and to select the Old declaration that New should be 2985 /// merged with. 2986 /// 2987 /// Returns true if there was an error, false otherwise. 2988 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2989 Scope *S, bool MergeTypeWithOld) { 2990 // Verify the old decl was also a function. 2991 FunctionDecl *Old = OldD->getAsFunction(); 2992 if (!Old) { 2993 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2994 if (New->getFriendObjectKind()) { 2995 Diag(New->getLocation(), diag::err_using_decl_friend); 2996 Diag(Shadow->getTargetDecl()->getLocation(), 2997 diag::note_using_decl_target); 2998 Diag(Shadow->getUsingDecl()->getLocation(), 2999 diag::note_using_decl) << 0; 3000 return true; 3001 } 3002 3003 // Check whether the two declarations might declare the same function. 3004 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3005 return true; 3006 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3007 } else { 3008 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3009 << New->getDeclName(); 3010 notePreviousDefinition(OldD, New->getLocation()); 3011 return true; 3012 } 3013 } 3014 3015 // If the old declaration is invalid, just give up here. 3016 if (Old->isInvalidDecl()) 3017 return true; 3018 3019 // Disallow redeclaration of some builtins. 3020 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3021 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3022 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3023 << Old << Old->getType(); 3024 return true; 3025 } 3026 3027 diag::kind PrevDiag; 3028 SourceLocation OldLocation; 3029 std::tie(PrevDiag, OldLocation) = 3030 getNoteDiagForInvalidRedeclaration(Old, New); 3031 3032 // Don't complain about this if we're in GNU89 mode and the old function 3033 // is an extern inline function. 3034 // Don't complain about specializations. They are not supposed to have 3035 // storage classes. 3036 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3037 New->getStorageClass() == SC_Static && 3038 Old->hasExternalFormalLinkage() && 3039 !New->getTemplateSpecializationInfo() && 3040 !canRedefineFunction(Old, getLangOpts())) { 3041 if (getLangOpts().MicrosoftExt) { 3042 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3043 Diag(OldLocation, PrevDiag); 3044 } else { 3045 Diag(New->getLocation(), diag::err_static_non_static) << New; 3046 Diag(OldLocation, PrevDiag); 3047 return true; 3048 } 3049 } 3050 3051 if (New->hasAttr<InternalLinkageAttr>() && 3052 !Old->hasAttr<InternalLinkageAttr>()) { 3053 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3054 << New->getDeclName(); 3055 notePreviousDefinition(Old, New->getLocation()); 3056 New->dropAttr<InternalLinkageAttr>(); 3057 } 3058 3059 if (CheckRedeclarationModuleOwnership(New, Old)) 3060 return true; 3061 3062 if (!getLangOpts().CPlusPlus) { 3063 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3064 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3065 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3066 << New << OldOvl; 3067 3068 // Try our best to find a decl that actually has the overloadable 3069 // attribute for the note. In most cases (e.g. programs with only one 3070 // broken declaration/definition), this won't matter. 3071 // 3072 // FIXME: We could do this if we juggled some extra state in 3073 // OverloadableAttr, rather than just removing it. 3074 const Decl *DiagOld = Old; 3075 if (OldOvl) { 3076 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3077 const auto *A = D->getAttr<OverloadableAttr>(); 3078 return A && !A->isImplicit(); 3079 }); 3080 // If we've implicitly added *all* of the overloadable attrs to this 3081 // chain, emitting a "previous redecl" note is pointless. 3082 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3083 } 3084 3085 if (DiagOld) 3086 Diag(DiagOld->getLocation(), 3087 diag::note_attribute_overloadable_prev_overload) 3088 << OldOvl; 3089 3090 if (OldOvl) 3091 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3092 else 3093 New->dropAttr<OverloadableAttr>(); 3094 } 3095 } 3096 3097 // If a function is first declared with a calling convention, but is later 3098 // declared or defined without one, all following decls assume the calling 3099 // convention of the first. 3100 // 3101 // It's OK if a function is first declared without a calling convention, 3102 // but is later declared or defined with the default calling convention. 3103 // 3104 // To test if either decl has an explicit calling convention, we look for 3105 // AttributedType sugar nodes on the type as written. If they are missing or 3106 // were canonicalized away, we assume the calling convention was implicit. 3107 // 3108 // Note also that we DO NOT return at this point, because we still have 3109 // other tests to run. 3110 QualType OldQType = Context.getCanonicalType(Old->getType()); 3111 QualType NewQType = Context.getCanonicalType(New->getType()); 3112 const FunctionType *OldType = cast<FunctionType>(OldQType); 3113 const FunctionType *NewType = cast<FunctionType>(NewQType); 3114 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3115 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3116 bool RequiresAdjustment = false; 3117 3118 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3119 FunctionDecl *First = Old->getFirstDecl(); 3120 const FunctionType *FT = 3121 First->getType().getCanonicalType()->castAs<FunctionType>(); 3122 FunctionType::ExtInfo FI = FT->getExtInfo(); 3123 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3124 if (!NewCCExplicit) { 3125 // Inherit the CC from the previous declaration if it was specified 3126 // there but not here. 3127 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3128 RequiresAdjustment = true; 3129 } else { 3130 // Calling conventions aren't compatible, so complain. 3131 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3132 Diag(New->getLocation(), diag::err_cconv_change) 3133 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3134 << !FirstCCExplicit 3135 << (!FirstCCExplicit ? "" : 3136 FunctionType::getNameForCallConv(FI.getCC())); 3137 3138 // Put the note on the first decl, since it is the one that matters. 3139 Diag(First->getLocation(), diag::note_previous_declaration); 3140 return true; 3141 } 3142 } 3143 3144 // FIXME: diagnose the other way around? 3145 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3146 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3147 RequiresAdjustment = true; 3148 } 3149 3150 // Merge regparm attribute. 3151 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3152 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3153 if (NewTypeInfo.getHasRegParm()) { 3154 Diag(New->getLocation(), diag::err_regparm_mismatch) 3155 << NewType->getRegParmType() 3156 << OldType->getRegParmType(); 3157 Diag(OldLocation, diag::note_previous_declaration); 3158 return true; 3159 } 3160 3161 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3162 RequiresAdjustment = true; 3163 } 3164 3165 // Merge ns_returns_retained attribute. 3166 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3167 if (NewTypeInfo.getProducesResult()) { 3168 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3169 << "'ns_returns_retained'"; 3170 Diag(OldLocation, diag::note_previous_declaration); 3171 return true; 3172 } 3173 3174 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3175 RequiresAdjustment = true; 3176 } 3177 3178 if (OldTypeInfo.getNoCallerSavedRegs() != 3179 NewTypeInfo.getNoCallerSavedRegs()) { 3180 if (NewTypeInfo.getNoCallerSavedRegs()) { 3181 AnyX86NoCallerSavedRegistersAttr *Attr = 3182 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3183 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3184 Diag(OldLocation, diag::note_previous_declaration); 3185 return true; 3186 } 3187 3188 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3189 RequiresAdjustment = true; 3190 } 3191 3192 if (RequiresAdjustment) { 3193 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3194 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3195 3196 QualType AdjustedQT = QualType(AdjustedType, 0); 3197 LangAS AS = Old->getType().getAddressSpace(); 3198 AdjustedQT = Context.getAddrSpaceQualType(AdjustedQT, AS); 3199 3200 New->setType(AdjustedQT); 3201 NewQType = Context.getCanonicalType(New->getType()); 3202 NewType = cast<FunctionType>(NewQType); 3203 } 3204 3205 // If this redeclaration makes the function inline, we may need to add it to 3206 // UndefinedButUsed. 3207 if (!Old->isInlined() && New->isInlined() && 3208 !New->hasAttr<GNUInlineAttr>() && 3209 !getLangOpts().GNUInline && 3210 Old->isUsed(false) && 3211 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3212 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3213 SourceLocation())); 3214 3215 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3216 // about it. 3217 if (New->hasAttr<GNUInlineAttr>() && 3218 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3219 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3220 } 3221 3222 // If pass_object_size params don't match up perfectly, this isn't a valid 3223 // redeclaration. 3224 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3225 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3226 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3227 << New->getDeclName(); 3228 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3229 return true; 3230 } 3231 3232 if (getLangOpts().CPlusPlus) { 3233 // C++1z [over.load]p2 3234 // Certain function declarations cannot be overloaded: 3235 // -- Function declarations that differ only in the return type, 3236 // the exception specification, or both cannot be overloaded. 3237 3238 // Check the exception specifications match. This may recompute the type of 3239 // both Old and New if it resolved exception specifications, so grab the 3240 // types again after this. Because this updates the type, we do this before 3241 // any of the other checks below, which may update the "de facto" NewQType 3242 // but do not necessarily update the type of New. 3243 if (CheckEquivalentExceptionSpec(Old, New)) 3244 return true; 3245 OldQType = Context.getCanonicalType(Old->getType()); 3246 NewQType = Context.getCanonicalType(New->getType()); 3247 3248 // Go back to the type source info to compare the declared return types, 3249 // per C++1y [dcl.type.auto]p13: 3250 // Redeclarations or specializations of a function or function template 3251 // with a declared return type that uses a placeholder type shall also 3252 // use that placeholder, not a deduced type. 3253 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3254 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3255 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3256 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3257 OldDeclaredReturnType)) { 3258 QualType ResQT; 3259 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3260 OldDeclaredReturnType->isObjCObjectPointerType()) 3261 // FIXME: This does the wrong thing for a deduced return type. 3262 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3263 if (ResQT.isNull()) { 3264 if (New->isCXXClassMember() && New->isOutOfLine()) 3265 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3266 << New << New->getReturnTypeSourceRange(); 3267 else 3268 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3269 << New->getReturnTypeSourceRange(); 3270 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3271 << Old->getReturnTypeSourceRange(); 3272 return true; 3273 } 3274 else 3275 NewQType = ResQT; 3276 } 3277 3278 QualType OldReturnType = OldType->getReturnType(); 3279 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3280 if (OldReturnType != NewReturnType) { 3281 // If this function has a deduced return type and has already been 3282 // defined, copy the deduced value from the old declaration. 3283 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3284 if (OldAT && OldAT->isDeduced()) { 3285 New->setType( 3286 SubstAutoType(New->getType(), 3287 OldAT->isDependentType() ? Context.DependentTy 3288 : OldAT->getDeducedType())); 3289 NewQType = Context.getCanonicalType( 3290 SubstAutoType(NewQType, 3291 OldAT->isDependentType() ? Context.DependentTy 3292 : OldAT->getDeducedType())); 3293 } 3294 } 3295 3296 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3297 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3298 if (OldMethod && NewMethod) { 3299 // Preserve triviality. 3300 NewMethod->setTrivial(OldMethod->isTrivial()); 3301 3302 // MSVC allows explicit template specialization at class scope: 3303 // 2 CXXMethodDecls referring to the same function will be injected. 3304 // We don't want a redeclaration error. 3305 bool IsClassScopeExplicitSpecialization = 3306 OldMethod->isFunctionTemplateSpecialization() && 3307 NewMethod->isFunctionTemplateSpecialization(); 3308 bool isFriend = NewMethod->getFriendObjectKind(); 3309 3310 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3311 !IsClassScopeExplicitSpecialization) { 3312 // -- Member function declarations with the same name and the 3313 // same parameter types cannot be overloaded if any of them 3314 // is a static member function declaration. 3315 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3316 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3317 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3318 return true; 3319 } 3320 3321 // C++ [class.mem]p1: 3322 // [...] A member shall not be declared twice in the 3323 // member-specification, except that a nested class or member 3324 // class template can be declared and then later defined. 3325 if (!inTemplateInstantiation()) { 3326 unsigned NewDiag; 3327 if (isa<CXXConstructorDecl>(OldMethod)) 3328 NewDiag = diag::err_constructor_redeclared; 3329 else if (isa<CXXDestructorDecl>(NewMethod)) 3330 NewDiag = diag::err_destructor_redeclared; 3331 else if (isa<CXXConversionDecl>(NewMethod)) 3332 NewDiag = diag::err_conv_function_redeclared; 3333 else 3334 NewDiag = diag::err_member_redeclared; 3335 3336 Diag(New->getLocation(), NewDiag); 3337 } else { 3338 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3339 << New << New->getType(); 3340 } 3341 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3342 return true; 3343 3344 // Complain if this is an explicit declaration of a special 3345 // member that was initially declared implicitly. 3346 // 3347 // As an exception, it's okay to befriend such methods in order 3348 // to permit the implicit constructor/destructor/operator calls. 3349 } else if (OldMethod->isImplicit()) { 3350 if (isFriend) { 3351 NewMethod->setImplicit(); 3352 } else { 3353 Diag(NewMethod->getLocation(), 3354 diag::err_definition_of_implicitly_declared_member) 3355 << New << getSpecialMember(OldMethod); 3356 return true; 3357 } 3358 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3359 Diag(NewMethod->getLocation(), 3360 diag::err_definition_of_explicitly_defaulted_member) 3361 << getSpecialMember(OldMethod); 3362 return true; 3363 } 3364 } 3365 3366 // C++11 [dcl.attr.noreturn]p1: 3367 // The first declaration of a function shall specify the noreturn 3368 // attribute if any declaration of that function specifies the noreturn 3369 // attribute. 3370 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3371 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3372 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3373 Diag(Old->getFirstDecl()->getLocation(), 3374 diag::note_noreturn_missing_first_decl); 3375 } 3376 3377 // C++11 [dcl.attr.depend]p2: 3378 // The first declaration of a function shall specify the 3379 // carries_dependency attribute for its declarator-id if any declaration 3380 // of the function specifies the carries_dependency attribute. 3381 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3382 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3383 Diag(CDA->getLocation(), 3384 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3385 Diag(Old->getFirstDecl()->getLocation(), 3386 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3387 } 3388 3389 // (C++98 8.3.5p3): 3390 // All declarations for a function shall agree exactly in both the 3391 // return type and the parameter-type-list. 3392 // We also want to respect all the extended bits except noreturn. 3393 3394 // noreturn should now match unless the old type info didn't have it. 3395 QualType OldQTypeForComparison = OldQType; 3396 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3397 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3398 const FunctionType *OldTypeForComparison 3399 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3400 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3401 assert(OldQTypeForComparison.isCanonical()); 3402 } 3403 3404 if (haveIncompatibleLanguageLinkages(Old, New)) { 3405 // As a special case, retain the language linkage from previous 3406 // declarations of a friend function as an extension. 3407 // 3408 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3409 // and is useful because there's otherwise no way to specify language 3410 // linkage within class scope. 3411 // 3412 // Check cautiously as the friend object kind isn't yet complete. 3413 if (New->getFriendObjectKind() != Decl::FOK_None) { 3414 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3415 Diag(OldLocation, PrevDiag); 3416 } else { 3417 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3418 Diag(OldLocation, PrevDiag); 3419 return true; 3420 } 3421 } 3422 3423 if (OldQTypeForComparison == NewQType) 3424 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3425 3426 // If the types are imprecise (due to dependent constructs in friends or 3427 // local extern declarations), it's OK if they differ. We'll check again 3428 // during instantiation. 3429 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3430 return false; 3431 3432 // Fall through for conflicting redeclarations and redefinitions. 3433 } 3434 3435 // C: Function types need to be compatible, not identical. This handles 3436 // duplicate function decls like "void f(int); void f(enum X);" properly. 3437 if (!getLangOpts().CPlusPlus && 3438 Context.typesAreCompatible(OldQType, NewQType)) { 3439 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3440 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3441 const FunctionProtoType *OldProto = nullptr; 3442 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3443 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3444 // The old declaration provided a function prototype, but the 3445 // new declaration does not. Merge in the prototype. 3446 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3447 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3448 NewQType = 3449 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3450 OldProto->getExtProtoInfo()); 3451 New->setType(NewQType); 3452 New->setHasInheritedPrototype(); 3453 3454 // Synthesize parameters with the same types. 3455 SmallVector<ParmVarDecl*, 16> Params; 3456 for (const auto &ParamType : OldProto->param_types()) { 3457 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3458 SourceLocation(), nullptr, 3459 ParamType, /*TInfo=*/nullptr, 3460 SC_None, nullptr); 3461 Param->setScopeInfo(0, Params.size()); 3462 Param->setImplicit(); 3463 Params.push_back(Param); 3464 } 3465 3466 New->setParams(Params); 3467 } 3468 3469 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3470 } 3471 3472 // GNU C permits a K&R definition to follow a prototype declaration 3473 // if the declared types of the parameters in the K&R definition 3474 // match the types in the prototype declaration, even when the 3475 // promoted types of the parameters from the K&R definition differ 3476 // from the types in the prototype. GCC then keeps the types from 3477 // the prototype. 3478 // 3479 // If a variadic prototype is followed by a non-variadic K&R definition, 3480 // the K&R definition becomes variadic. This is sort of an edge case, but 3481 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3482 // C99 6.9.1p8. 3483 if (!getLangOpts().CPlusPlus && 3484 Old->hasPrototype() && !New->hasPrototype() && 3485 New->getType()->getAs<FunctionProtoType>() && 3486 Old->getNumParams() == New->getNumParams()) { 3487 SmallVector<QualType, 16> ArgTypes; 3488 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3489 const FunctionProtoType *OldProto 3490 = Old->getType()->getAs<FunctionProtoType>(); 3491 const FunctionProtoType *NewProto 3492 = New->getType()->getAs<FunctionProtoType>(); 3493 3494 // Determine whether this is the GNU C extension. 3495 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3496 NewProto->getReturnType()); 3497 bool LooseCompatible = !MergedReturn.isNull(); 3498 for (unsigned Idx = 0, End = Old->getNumParams(); 3499 LooseCompatible && Idx != End; ++Idx) { 3500 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3501 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3502 if (Context.typesAreCompatible(OldParm->getType(), 3503 NewProto->getParamType(Idx))) { 3504 ArgTypes.push_back(NewParm->getType()); 3505 } else if (Context.typesAreCompatible(OldParm->getType(), 3506 NewParm->getType(), 3507 /*CompareUnqualified=*/true)) { 3508 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3509 NewProto->getParamType(Idx) }; 3510 Warnings.push_back(Warn); 3511 ArgTypes.push_back(NewParm->getType()); 3512 } else 3513 LooseCompatible = false; 3514 } 3515 3516 if (LooseCompatible) { 3517 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3518 Diag(Warnings[Warn].NewParm->getLocation(), 3519 diag::ext_param_promoted_not_compatible_with_prototype) 3520 << Warnings[Warn].PromotedType 3521 << Warnings[Warn].OldParm->getType(); 3522 if (Warnings[Warn].OldParm->getLocation().isValid()) 3523 Diag(Warnings[Warn].OldParm->getLocation(), 3524 diag::note_previous_declaration); 3525 } 3526 3527 if (MergeTypeWithOld) 3528 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3529 OldProto->getExtProtoInfo())); 3530 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3531 } 3532 3533 // Fall through to diagnose conflicting types. 3534 } 3535 3536 // A function that has already been declared has been redeclared or 3537 // defined with a different type; show an appropriate diagnostic. 3538 3539 // If the previous declaration was an implicitly-generated builtin 3540 // declaration, then at the very least we should use a specialized note. 3541 unsigned BuiltinID; 3542 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3543 // If it's actually a library-defined builtin function like 'malloc' 3544 // or 'printf', just warn about the incompatible redeclaration. 3545 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3546 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3547 Diag(OldLocation, diag::note_previous_builtin_declaration) 3548 << Old << Old->getType(); 3549 3550 // If this is a global redeclaration, just forget hereafter 3551 // about the "builtin-ness" of the function. 3552 // 3553 // Doing this for local extern declarations is problematic. If 3554 // the builtin declaration remains visible, a second invalid 3555 // local declaration will produce a hard error; if it doesn't 3556 // remain visible, a single bogus local redeclaration (which is 3557 // actually only a warning) could break all the downstream code. 3558 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3559 New->getIdentifier()->revertBuiltin(); 3560 3561 return false; 3562 } 3563 3564 PrevDiag = diag::note_previous_builtin_declaration; 3565 } 3566 3567 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3568 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3569 return true; 3570 } 3571 3572 /// Completes the merge of two function declarations that are 3573 /// known to be compatible. 3574 /// 3575 /// This routine handles the merging of attributes and other 3576 /// properties of function declarations from the old declaration to 3577 /// the new declaration, once we know that New is in fact a 3578 /// redeclaration of Old. 3579 /// 3580 /// \returns false 3581 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3582 Scope *S, bool MergeTypeWithOld) { 3583 // Merge the attributes 3584 mergeDeclAttributes(New, Old); 3585 3586 // Merge "pure" flag. 3587 if (Old->isPure()) 3588 New->setPure(); 3589 3590 // Merge "used" flag. 3591 if (Old->getMostRecentDecl()->isUsed(false)) 3592 New->setIsUsed(); 3593 3594 // Merge attributes from the parameters. These can mismatch with K&R 3595 // declarations. 3596 if (New->getNumParams() == Old->getNumParams()) 3597 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3598 ParmVarDecl *NewParam = New->getParamDecl(i); 3599 ParmVarDecl *OldParam = Old->getParamDecl(i); 3600 mergeParamDeclAttributes(NewParam, OldParam, *this); 3601 mergeParamDeclTypes(NewParam, OldParam, *this); 3602 } 3603 3604 if (getLangOpts().CPlusPlus) 3605 return MergeCXXFunctionDecl(New, Old, S); 3606 3607 // Merge the function types so the we get the composite types for the return 3608 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3609 // was visible. 3610 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3611 if (!Merged.isNull() && MergeTypeWithOld) 3612 New->setType(Merged); 3613 3614 return false; 3615 } 3616 3617 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3618 ObjCMethodDecl *oldMethod) { 3619 // Merge the attributes, including deprecated/unavailable 3620 AvailabilityMergeKind MergeKind = 3621 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3622 ? AMK_ProtocolImplementation 3623 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3624 : AMK_Override; 3625 3626 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3627 3628 // Merge attributes from the parameters. 3629 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3630 oe = oldMethod->param_end(); 3631 for (ObjCMethodDecl::param_iterator 3632 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3633 ni != ne && oi != oe; ++ni, ++oi) 3634 mergeParamDeclAttributes(*ni, *oi, *this); 3635 3636 CheckObjCMethodOverride(newMethod, oldMethod); 3637 } 3638 3639 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3640 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3641 3642 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3643 ? diag::err_redefinition_different_type 3644 : diag::err_redeclaration_different_type) 3645 << New->getDeclName() << New->getType() << Old->getType(); 3646 3647 diag::kind PrevDiag; 3648 SourceLocation OldLocation; 3649 std::tie(PrevDiag, OldLocation) 3650 = getNoteDiagForInvalidRedeclaration(Old, New); 3651 S.Diag(OldLocation, PrevDiag); 3652 New->setInvalidDecl(); 3653 } 3654 3655 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3656 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3657 /// emitting diagnostics as appropriate. 3658 /// 3659 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3660 /// to here in AddInitializerToDecl. We can't check them before the initializer 3661 /// is attached. 3662 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3663 bool MergeTypeWithOld) { 3664 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3665 return; 3666 3667 QualType MergedT; 3668 if (getLangOpts().CPlusPlus) { 3669 if (New->getType()->isUndeducedType()) { 3670 // We don't know what the new type is until the initializer is attached. 3671 return; 3672 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3673 // These could still be something that needs exception specs checked. 3674 return MergeVarDeclExceptionSpecs(New, Old); 3675 } 3676 // C++ [basic.link]p10: 3677 // [...] the types specified by all declarations referring to a given 3678 // object or function shall be identical, except that declarations for an 3679 // array object can specify array types that differ by the presence or 3680 // absence of a major array bound (8.3.4). 3681 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3682 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3683 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3684 3685 // We are merging a variable declaration New into Old. If it has an array 3686 // bound, and that bound differs from Old's bound, we should diagnose the 3687 // mismatch. 3688 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3689 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3690 PrevVD = PrevVD->getPreviousDecl()) { 3691 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3692 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3693 continue; 3694 3695 if (!Context.hasSameType(NewArray, PrevVDTy)) 3696 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3697 } 3698 } 3699 3700 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3701 if (Context.hasSameType(OldArray->getElementType(), 3702 NewArray->getElementType())) 3703 MergedT = New->getType(); 3704 } 3705 // FIXME: Check visibility. New is hidden but has a complete type. If New 3706 // has no array bound, it should not inherit one from Old, if Old is not 3707 // visible. 3708 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3709 if (Context.hasSameType(OldArray->getElementType(), 3710 NewArray->getElementType())) 3711 MergedT = Old->getType(); 3712 } 3713 } 3714 else if (New->getType()->isObjCObjectPointerType() && 3715 Old->getType()->isObjCObjectPointerType()) { 3716 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3717 Old->getType()); 3718 } 3719 } else { 3720 // C 6.2.7p2: 3721 // All declarations that refer to the same object or function shall have 3722 // compatible type. 3723 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3724 } 3725 if (MergedT.isNull()) { 3726 // It's OK if we couldn't merge types if either type is dependent, for a 3727 // block-scope variable. In other cases (static data members of class 3728 // templates, variable templates, ...), we require the types to be 3729 // equivalent. 3730 // FIXME: The C++ standard doesn't say anything about this. 3731 if ((New->getType()->isDependentType() || 3732 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3733 // If the old type was dependent, we can't merge with it, so the new type 3734 // becomes dependent for now. We'll reproduce the original type when we 3735 // instantiate the TypeSourceInfo for the variable. 3736 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3737 New->setType(Context.DependentTy); 3738 return; 3739 } 3740 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3741 } 3742 3743 // Don't actually update the type on the new declaration if the old 3744 // declaration was an extern declaration in a different scope. 3745 if (MergeTypeWithOld) 3746 New->setType(MergedT); 3747 } 3748 3749 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3750 LookupResult &Previous) { 3751 // C11 6.2.7p4: 3752 // For an identifier with internal or external linkage declared 3753 // in a scope in which a prior declaration of that identifier is 3754 // visible, if the prior declaration specifies internal or 3755 // external linkage, the type of the identifier at the later 3756 // declaration becomes the composite type. 3757 // 3758 // If the variable isn't visible, we do not merge with its type. 3759 if (Previous.isShadowed()) 3760 return false; 3761 3762 if (S.getLangOpts().CPlusPlus) { 3763 // C++11 [dcl.array]p3: 3764 // If there is a preceding declaration of the entity in the same 3765 // scope in which the bound was specified, an omitted array bound 3766 // is taken to be the same as in that earlier declaration. 3767 return NewVD->isPreviousDeclInSameBlockScope() || 3768 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3769 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3770 } else { 3771 // If the old declaration was function-local, don't merge with its 3772 // type unless we're in the same function. 3773 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3774 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3775 } 3776 } 3777 3778 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3779 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3780 /// situation, merging decls or emitting diagnostics as appropriate. 3781 /// 3782 /// Tentative definition rules (C99 6.9.2p2) are checked by 3783 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3784 /// definitions here, since the initializer hasn't been attached. 3785 /// 3786 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3787 // If the new decl is already invalid, don't do any other checking. 3788 if (New->isInvalidDecl()) 3789 return; 3790 3791 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3792 return; 3793 3794 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3795 3796 // Verify the old decl was also a variable or variable template. 3797 VarDecl *Old = nullptr; 3798 VarTemplateDecl *OldTemplate = nullptr; 3799 if (Previous.isSingleResult()) { 3800 if (NewTemplate) { 3801 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3802 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3803 3804 if (auto *Shadow = 3805 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3806 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3807 return New->setInvalidDecl(); 3808 } else { 3809 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3810 3811 if (auto *Shadow = 3812 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3813 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3814 return New->setInvalidDecl(); 3815 } 3816 } 3817 if (!Old) { 3818 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3819 << New->getDeclName(); 3820 notePreviousDefinition(Previous.getRepresentativeDecl(), 3821 New->getLocation()); 3822 return New->setInvalidDecl(); 3823 } 3824 3825 // Ensure the template parameters are compatible. 3826 if (NewTemplate && 3827 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3828 OldTemplate->getTemplateParameters(), 3829 /*Complain=*/true, TPL_TemplateMatch)) 3830 return New->setInvalidDecl(); 3831 3832 // C++ [class.mem]p1: 3833 // A member shall not be declared twice in the member-specification [...] 3834 // 3835 // Here, we need only consider static data members. 3836 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3837 Diag(New->getLocation(), diag::err_duplicate_member) 3838 << New->getIdentifier(); 3839 Diag(Old->getLocation(), diag::note_previous_declaration); 3840 New->setInvalidDecl(); 3841 } 3842 3843 mergeDeclAttributes(New, Old); 3844 // Warn if an already-declared variable is made a weak_import in a subsequent 3845 // declaration 3846 if (New->hasAttr<WeakImportAttr>() && 3847 Old->getStorageClass() == SC_None && 3848 !Old->hasAttr<WeakImportAttr>()) { 3849 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3850 notePreviousDefinition(Old, New->getLocation()); 3851 // Remove weak_import attribute on new declaration. 3852 New->dropAttr<WeakImportAttr>(); 3853 } 3854 3855 if (New->hasAttr<InternalLinkageAttr>() && 3856 !Old->hasAttr<InternalLinkageAttr>()) { 3857 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3858 << New->getDeclName(); 3859 notePreviousDefinition(Old, New->getLocation()); 3860 New->dropAttr<InternalLinkageAttr>(); 3861 } 3862 3863 // Merge the types. 3864 VarDecl *MostRecent = Old->getMostRecentDecl(); 3865 if (MostRecent != Old) { 3866 MergeVarDeclTypes(New, MostRecent, 3867 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3868 if (New->isInvalidDecl()) 3869 return; 3870 } 3871 3872 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3873 if (New->isInvalidDecl()) 3874 return; 3875 3876 diag::kind PrevDiag; 3877 SourceLocation OldLocation; 3878 std::tie(PrevDiag, OldLocation) = 3879 getNoteDiagForInvalidRedeclaration(Old, New); 3880 3881 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3882 if (New->getStorageClass() == SC_Static && 3883 !New->isStaticDataMember() && 3884 Old->hasExternalFormalLinkage()) { 3885 if (getLangOpts().MicrosoftExt) { 3886 Diag(New->getLocation(), diag::ext_static_non_static) 3887 << New->getDeclName(); 3888 Diag(OldLocation, PrevDiag); 3889 } else { 3890 Diag(New->getLocation(), diag::err_static_non_static) 3891 << New->getDeclName(); 3892 Diag(OldLocation, PrevDiag); 3893 return New->setInvalidDecl(); 3894 } 3895 } 3896 // C99 6.2.2p4: 3897 // For an identifier declared with the storage-class specifier 3898 // extern in a scope in which a prior declaration of that 3899 // identifier is visible,23) if the prior declaration specifies 3900 // internal or external linkage, the linkage of the identifier at 3901 // the later declaration is the same as the linkage specified at 3902 // the prior declaration. If no prior declaration is visible, or 3903 // if the prior declaration specifies no linkage, then the 3904 // identifier has external linkage. 3905 if (New->hasExternalStorage() && Old->hasLinkage()) 3906 /* Okay */; 3907 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3908 !New->isStaticDataMember() && 3909 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3910 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3911 Diag(OldLocation, PrevDiag); 3912 return New->setInvalidDecl(); 3913 } 3914 3915 // Check if extern is followed by non-extern and vice-versa. 3916 if (New->hasExternalStorage() && 3917 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3918 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3919 Diag(OldLocation, PrevDiag); 3920 return New->setInvalidDecl(); 3921 } 3922 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3923 !New->hasExternalStorage()) { 3924 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3925 Diag(OldLocation, PrevDiag); 3926 return New->setInvalidDecl(); 3927 } 3928 3929 if (CheckRedeclarationModuleOwnership(New, Old)) 3930 return; 3931 3932 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3933 3934 // FIXME: The test for external storage here seems wrong? We still 3935 // need to check for mismatches. 3936 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3937 // Don't complain about out-of-line definitions of static members. 3938 !(Old->getLexicalDeclContext()->isRecord() && 3939 !New->getLexicalDeclContext()->isRecord())) { 3940 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3941 Diag(OldLocation, PrevDiag); 3942 return New->setInvalidDecl(); 3943 } 3944 3945 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3946 if (VarDecl *Def = Old->getDefinition()) { 3947 // C++1z [dcl.fcn.spec]p4: 3948 // If the definition of a variable appears in a translation unit before 3949 // its first declaration as inline, the program is ill-formed. 3950 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3951 Diag(Def->getLocation(), diag::note_previous_definition); 3952 } 3953 } 3954 3955 // If this redeclaration makes the variable inline, we may need to add it to 3956 // UndefinedButUsed. 3957 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3958 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3959 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3960 SourceLocation())); 3961 3962 if (New->getTLSKind() != Old->getTLSKind()) { 3963 if (!Old->getTLSKind()) { 3964 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3965 Diag(OldLocation, PrevDiag); 3966 } else if (!New->getTLSKind()) { 3967 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3968 Diag(OldLocation, PrevDiag); 3969 } else { 3970 // Do not allow redeclaration to change the variable between requiring 3971 // static and dynamic initialization. 3972 // FIXME: GCC allows this, but uses the TLS keyword on the first 3973 // declaration to determine the kind. Do we need to be compatible here? 3974 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3975 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3976 Diag(OldLocation, PrevDiag); 3977 } 3978 } 3979 3980 // C++ doesn't have tentative definitions, so go right ahead and check here. 3981 if (getLangOpts().CPlusPlus && 3982 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3983 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3984 Old->getCanonicalDecl()->isConstexpr()) { 3985 // This definition won't be a definition any more once it's been merged. 3986 Diag(New->getLocation(), 3987 diag::warn_deprecated_redundant_constexpr_static_def); 3988 } else if (VarDecl *Def = Old->getDefinition()) { 3989 if (checkVarDeclRedefinition(Def, New)) 3990 return; 3991 } 3992 } 3993 3994 if (haveIncompatibleLanguageLinkages(Old, New)) { 3995 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3996 Diag(OldLocation, PrevDiag); 3997 New->setInvalidDecl(); 3998 return; 3999 } 4000 4001 // Merge "used" flag. 4002 if (Old->getMostRecentDecl()->isUsed(false)) 4003 New->setIsUsed(); 4004 4005 // Keep a chain of previous declarations. 4006 New->setPreviousDecl(Old); 4007 if (NewTemplate) 4008 NewTemplate->setPreviousDecl(OldTemplate); 4009 adjustDeclContextForDeclaratorDecl(New, Old); 4010 4011 // Inherit access appropriately. 4012 New->setAccess(Old->getAccess()); 4013 if (NewTemplate) 4014 NewTemplate->setAccess(New->getAccess()); 4015 4016 if (Old->isInline()) 4017 New->setImplicitlyInline(); 4018 } 4019 4020 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4021 SourceManager &SrcMgr = getSourceManager(); 4022 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4023 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4024 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4025 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4026 auto &HSI = PP.getHeaderSearchInfo(); 4027 StringRef HdrFilename = 4028 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4029 4030 auto noteFromModuleOrInclude = [&](Module *Mod, 4031 SourceLocation IncLoc) -> bool { 4032 // Redefinition errors with modules are common with non modular mapped 4033 // headers, example: a non-modular header H in module A that also gets 4034 // included directly in a TU. Pointing twice to the same header/definition 4035 // is confusing, try to get better diagnostics when modules is on. 4036 if (IncLoc.isValid()) { 4037 if (Mod) { 4038 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4039 << HdrFilename.str() << Mod->getFullModuleName(); 4040 if (!Mod->DefinitionLoc.isInvalid()) 4041 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4042 << Mod->getFullModuleName(); 4043 } else { 4044 Diag(IncLoc, diag::note_redefinition_include_same_file) 4045 << HdrFilename.str(); 4046 } 4047 return true; 4048 } 4049 4050 return false; 4051 }; 4052 4053 // Is it the same file and same offset? Provide more information on why 4054 // this leads to a redefinition error. 4055 bool EmittedDiag = false; 4056 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4057 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4058 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4059 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4060 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4061 4062 // If the header has no guards, emit a note suggesting one. 4063 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4064 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4065 4066 if (EmittedDiag) 4067 return; 4068 } 4069 4070 // Redefinition coming from different files or couldn't do better above. 4071 if (Old->getLocation().isValid()) 4072 Diag(Old->getLocation(), diag::note_previous_definition); 4073 } 4074 4075 /// We've just determined that \p Old and \p New both appear to be definitions 4076 /// of the same variable. Either diagnose or fix the problem. 4077 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4078 if (!hasVisibleDefinition(Old) && 4079 (New->getFormalLinkage() == InternalLinkage || 4080 New->isInline() || 4081 New->getDescribedVarTemplate() || 4082 New->getNumTemplateParameterLists() || 4083 New->getDeclContext()->isDependentContext())) { 4084 // The previous definition is hidden, and multiple definitions are 4085 // permitted (in separate TUs). Demote this to a declaration. 4086 New->demoteThisDefinitionToDeclaration(); 4087 4088 // Make the canonical definition visible. 4089 if (auto *OldTD = Old->getDescribedVarTemplate()) 4090 makeMergedDefinitionVisible(OldTD); 4091 makeMergedDefinitionVisible(Old); 4092 return false; 4093 } else { 4094 Diag(New->getLocation(), diag::err_redefinition) << New; 4095 notePreviousDefinition(Old, New->getLocation()); 4096 New->setInvalidDecl(); 4097 return true; 4098 } 4099 } 4100 4101 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4102 /// no declarator (e.g. "struct foo;") is parsed. 4103 Decl * 4104 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4105 RecordDecl *&AnonRecord) { 4106 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4107 AnonRecord); 4108 } 4109 4110 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4111 // disambiguate entities defined in different scopes. 4112 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4113 // compatibility. 4114 // We will pick our mangling number depending on which version of MSVC is being 4115 // targeted. 4116 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4117 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4118 ? S->getMSCurManglingNumber() 4119 : S->getMSLastManglingNumber(); 4120 } 4121 4122 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4123 if (!Context.getLangOpts().CPlusPlus) 4124 return; 4125 4126 if (isa<CXXRecordDecl>(Tag->getParent())) { 4127 // If this tag is the direct child of a class, number it if 4128 // it is anonymous. 4129 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4130 return; 4131 MangleNumberingContext &MCtx = 4132 Context.getManglingNumberContext(Tag->getParent()); 4133 Context.setManglingNumber( 4134 Tag, MCtx.getManglingNumber( 4135 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4136 return; 4137 } 4138 4139 // If this tag isn't a direct child of a class, number it if it is local. 4140 Decl *ManglingContextDecl; 4141 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4142 Tag->getDeclContext(), ManglingContextDecl)) { 4143 Context.setManglingNumber( 4144 Tag, MCtx->getManglingNumber( 4145 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4146 } 4147 } 4148 4149 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4150 TypedefNameDecl *NewTD) { 4151 if (TagFromDeclSpec->isInvalidDecl()) 4152 return; 4153 4154 // Do nothing if the tag already has a name for linkage purposes. 4155 if (TagFromDeclSpec->hasNameForLinkage()) 4156 return; 4157 4158 // A well-formed anonymous tag must always be a TUK_Definition. 4159 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4160 4161 // The type must match the tag exactly; no qualifiers allowed. 4162 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4163 Context.getTagDeclType(TagFromDeclSpec))) { 4164 if (getLangOpts().CPlusPlus) 4165 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4166 return; 4167 } 4168 4169 // If we've already computed linkage for the anonymous tag, then 4170 // adding a typedef name for the anonymous decl can change that 4171 // linkage, which might be a serious problem. Diagnose this as 4172 // unsupported and ignore the typedef name. TODO: we should 4173 // pursue this as a language defect and establish a formal rule 4174 // for how to handle it. 4175 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4176 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4177 4178 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4179 tagLoc = getLocForEndOfToken(tagLoc); 4180 4181 llvm::SmallString<40> textToInsert; 4182 textToInsert += ' '; 4183 textToInsert += NewTD->getIdentifier()->getName(); 4184 Diag(tagLoc, diag::note_typedef_changes_linkage) 4185 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4186 return; 4187 } 4188 4189 // Otherwise, set this is the anon-decl typedef for the tag. 4190 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4191 } 4192 4193 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4194 switch (T) { 4195 case DeclSpec::TST_class: 4196 return 0; 4197 case DeclSpec::TST_struct: 4198 return 1; 4199 case DeclSpec::TST_interface: 4200 return 2; 4201 case DeclSpec::TST_union: 4202 return 3; 4203 case DeclSpec::TST_enum: 4204 return 4; 4205 default: 4206 llvm_unreachable("unexpected type specifier"); 4207 } 4208 } 4209 4210 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4211 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4212 /// parameters to cope with template friend declarations. 4213 Decl * 4214 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4215 MultiTemplateParamsArg TemplateParams, 4216 bool IsExplicitInstantiation, 4217 RecordDecl *&AnonRecord) { 4218 Decl *TagD = nullptr; 4219 TagDecl *Tag = nullptr; 4220 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4221 DS.getTypeSpecType() == DeclSpec::TST_struct || 4222 DS.getTypeSpecType() == DeclSpec::TST_interface || 4223 DS.getTypeSpecType() == DeclSpec::TST_union || 4224 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4225 TagD = DS.getRepAsDecl(); 4226 4227 if (!TagD) // We probably had an error 4228 return nullptr; 4229 4230 // Note that the above type specs guarantee that the 4231 // type rep is a Decl, whereas in many of the others 4232 // it's a Type. 4233 if (isa<TagDecl>(TagD)) 4234 Tag = cast<TagDecl>(TagD); 4235 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4236 Tag = CTD->getTemplatedDecl(); 4237 } 4238 4239 if (Tag) { 4240 handleTagNumbering(Tag, S); 4241 Tag->setFreeStanding(); 4242 if (Tag->isInvalidDecl()) 4243 return Tag; 4244 } 4245 4246 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4247 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4248 // or incomplete types shall not be restrict-qualified." 4249 if (TypeQuals & DeclSpec::TQ_restrict) 4250 Diag(DS.getRestrictSpecLoc(), 4251 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4252 << DS.getSourceRange(); 4253 } 4254 4255 if (DS.isInlineSpecified()) 4256 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4257 << getLangOpts().CPlusPlus17; 4258 4259 if (DS.isConstexprSpecified()) { 4260 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4261 // and definitions of functions and variables. 4262 if (Tag) 4263 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4264 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4265 else 4266 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4267 // Don't emit warnings after this error. 4268 return TagD; 4269 } 4270 4271 DiagnoseFunctionSpecifiers(DS); 4272 4273 if (DS.isFriendSpecified()) { 4274 // If we're dealing with a decl but not a TagDecl, assume that 4275 // whatever routines created it handled the friendship aspect. 4276 if (TagD && !Tag) 4277 return nullptr; 4278 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4279 } 4280 4281 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4282 bool IsExplicitSpecialization = 4283 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4284 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4285 !IsExplicitInstantiation && !IsExplicitSpecialization && 4286 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4287 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4288 // nested-name-specifier unless it is an explicit instantiation 4289 // or an explicit specialization. 4290 // 4291 // FIXME: We allow class template partial specializations here too, per the 4292 // obvious intent of DR1819. 4293 // 4294 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4295 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4296 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4297 return nullptr; 4298 } 4299 4300 // Track whether this decl-specifier declares anything. 4301 bool DeclaresAnything = true; 4302 4303 // Handle anonymous struct definitions. 4304 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4305 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4306 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4307 if (getLangOpts().CPlusPlus || 4308 Record->getDeclContext()->isRecord()) { 4309 // If CurContext is a DeclContext that can contain statements, 4310 // RecursiveASTVisitor won't visit the decls that 4311 // BuildAnonymousStructOrUnion() will put into CurContext. 4312 // Also store them here so that they can be part of the 4313 // DeclStmt that gets created in this case. 4314 // FIXME: Also return the IndirectFieldDecls created by 4315 // BuildAnonymousStructOr union, for the same reason? 4316 if (CurContext->isFunctionOrMethod()) 4317 AnonRecord = Record; 4318 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4319 Context.getPrintingPolicy()); 4320 } 4321 4322 DeclaresAnything = false; 4323 } 4324 } 4325 4326 // C11 6.7.2.1p2: 4327 // A struct-declaration that does not declare an anonymous structure or 4328 // anonymous union shall contain a struct-declarator-list. 4329 // 4330 // This rule also existed in C89 and C99; the grammar for struct-declaration 4331 // did not permit a struct-declaration without a struct-declarator-list. 4332 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4333 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4334 // Check for Microsoft C extension: anonymous struct/union member. 4335 // Handle 2 kinds of anonymous struct/union: 4336 // struct STRUCT; 4337 // union UNION; 4338 // and 4339 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4340 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4341 if ((Tag && Tag->getDeclName()) || 4342 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4343 RecordDecl *Record = nullptr; 4344 if (Tag) 4345 Record = dyn_cast<RecordDecl>(Tag); 4346 else if (const RecordType *RT = 4347 DS.getRepAsType().get()->getAsStructureType()) 4348 Record = RT->getDecl(); 4349 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4350 Record = UT->getDecl(); 4351 4352 if (Record && getLangOpts().MicrosoftExt) { 4353 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4354 << Record->isUnion() << DS.getSourceRange(); 4355 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4356 } 4357 4358 DeclaresAnything = false; 4359 } 4360 } 4361 4362 // Skip all the checks below if we have a type error. 4363 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4364 (TagD && TagD->isInvalidDecl())) 4365 return TagD; 4366 4367 if (getLangOpts().CPlusPlus && 4368 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4369 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4370 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4371 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4372 DeclaresAnything = false; 4373 4374 if (!DS.isMissingDeclaratorOk()) { 4375 // Customize diagnostic for a typedef missing a name. 4376 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4377 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4378 << DS.getSourceRange(); 4379 else 4380 DeclaresAnything = false; 4381 } 4382 4383 if (DS.isModulePrivateSpecified() && 4384 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4385 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4386 << Tag->getTagKind() 4387 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4388 4389 ActOnDocumentableDecl(TagD); 4390 4391 // C 6.7/2: 4392 // A declaration [...] shall declare at least a declarator [...], a tag, 4393 // or the members of an enumeration. 4394 // C++ [dcl.dcl]p3: 4395 // [If there are no declarators], and except for the declaration of an 4396 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4397 // names into the program, or shall redeclare a name introduced by a 4398 // previous declaration. 4399 if (!DeclaresAnything) { 4400 // In C, we allow this as a (popular) extension / bug. Don't bother 4401 // producing further diagnostics for redundant qualifiers after this. 4402 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4403 return TagD; 4404 } 4405 4406 // C++ [dcl.stc]p1: 4407 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4408 // init-declarator-list of the declaration shall not be empty. 4409 // C++ [dcl.fct.spec]p1: 4410 // If a cv-qualifier appears in a decl-specifier-seq, the 4411 // init-declarator-list of the declaration shall not be empty. 4412 // 4413 // Spurious qualifiers here appear to be valid in C. 4414 unsigned DiagID = diag::warn_standalone_specifier; 4415 if (getLangOpts().CPlusPlus) 4416 DiagID = diag::ext_standalone_specifier; 4417 4418 // Note that a linkage-specification sets a storage class, but 4419 // 'extern "C" struct foo;' is actually valid and not theoretically 4420 // useless. 4421 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4422 if (SCS == DeclSpec::SCS_mutable) 4423 // Since mutable is not a viable storage class specifier in C, there is 4424 // no reason to treat it as an extension. Instead, diagnose as an error. 4425 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4426 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4427 Diag(DS.getStorageClassSpecLoc(), DiagID) 4428 << DeclSpec::getSpecifierName(SCS); 4429 } 4430 4431 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4432 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4433 << DeclSpec::getSpecifierName(TSCS); 4434 if (DS.getTypeQualifiers()) { 4435 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4436 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4437 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4438 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4439 // Restrict is covered above. 4440 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4441 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4442 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4443 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4444 } 4445 4446 // Warn about ignored type attributes, for example: 4447 // __attribute__((aligned)) struct A; 4448 // Attributes should be placed after tag to apply to type declaration. 4449 if (!DS.getAttributes().empty()) { 4450 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4451 if (TypeSpecType == DeclSpec::TST_class || 4452 TypeSpecType == DeclSpec::TST_struct || 4453 TypeSpecType == DeclSpec::TST_interface || 4454 TypeSpecType == DeclSpec::TST_union || 4455 TypeSpecType == DeclSpec::TST_enum) { 4456 for (const ParsedAttr &AL : DS.getAttributes()) 4457 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4458 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4459 } 4460 } 4461 4462 return TagD; 4463 } 4464 4465 /// We are trying to inject an anonymous member into the given scope; 4466 /// check if there's an existing declaration that can't be overloaded. 4467 /// 4468 /// \return true if this is a forbidden redeclaration 4469 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4470 Scope *S, 4471 DeclContext *Owner, 4472 DeclarationName Name, 4473 SourceLocation NameLoc, 4474 bool IsUnion) { 4475 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4476 Sema::ForVisibleRedeclaration); 4477 if (!SemaRef.LookupName(R, S)) return false; 4478 4479 // Pick a representative declaration. 4480 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4481 assert(PrevDecl && "Expected a non-null Decl"); 4482 4483 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4484 return false; 4485 4486 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4487 << IsUnion << Name; 4488 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4489 4490 return true; 4491 } 4492 4493 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4494 /// anonymous struct or union AnonRecord into the owning context Owner 4495 /// and scope S. This routine will be invoked just after we realize 4496 /// that an unnamed union or struct is actually an anonymous union or 4497 /// struct, e.g., 4498 /// 4499 /// @code 4500 /// union { 4501 /// int i; 4502 /// float f; 4503 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4504 /// // f into the surrounding scope.x 4505 /// @endcode 4506 /// 4507 /// This routine is recursive, injecting the names of nested anonymous 4508 /// structs/unions into the owning context and scope as well. 4509 static bool 4510 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4511 RecordDecl *AnonRecord, AccessSpecifier AS, 4512 SmallVectorImpl<NamedDecl *> &Chaining) { 4513 bool Invalid = false; 4514 4515 // Look every FieldDecl and IndirectFieldDecl with a name. 4516 for (auto *D : AnonRecord->decls()) { 4517 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4518 cast<NamedDecl>(D)->getDeclName()) { 4519 ValueDecl *VD = cast<ValueDecl>(D); 4520 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4521 VD->getLocation(), 4522 AnonRecord->isUnion())) { 4523 // C++ [class.union]p2: 4524 // The names of the members of an anonymous union shall be 4525 // distinct from the names of any other entity in the 4526 // scope in which the anonymous union is declared. 4527 Invalid = true; 4528 } else { 4529 // C++ [class.union]p2: 4530 // For the purpose of name lookup, after the anonymous union 4531 // definition, the members of the anonymous union are 4532 // considered to have been defined in the scope in which the 4533 // anonymous union is declared. 4534 unsigned OldChainingSize = Chaining.size(); 4535 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4536 Chaining.append(IF->chain_begin(), IF->chain_end()); 4537 else 4538 Chaining.push_back(VD); 4539 4540 assert(Chaining.size() >= 2); 4541 NamedDecl **NamedChain = 4542 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4543 for (unsigned i = 0; i < Chaining.size(); i++) 4544 NamedChain[i] = Chaining[i]; 4545 4546 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4547 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4548 VD->getType(), {NamedChain, Chaining.size()}); 4549 4550 for (const auto *Attr : VD->attrs()) 4551 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4552 4553 IndirectField->setAccess(AS); 4554 IndirectField->setImplicit(); 4555 SemaRef.PushOnScopeChains(IndirectField, S); 4556 4557 // That includes picking up the appropriate access specifier. 4558 if (AS != AS_none) IndirectField->setAccess(AS); 4559 4560 Chaining.resize(OldChainingSize); 4561 } 4562 } 4563 } 4564 4565 return Invalid; 4566 } 4567 4568 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4569 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4570 /// illegal input values are mapped to SC_None. 4571 static StorageClass 4572 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4573 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4574 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4575 "Parser allowed 'typedef' as storage class VarDecl."); 4576 switch (StorageClassSpec) { 4577 case DeclSpec::SCS_unspecified: return SC_None; 4578 case DeclSpec::SCS_extern: 4579 if (DS.isExternInLinkageSpec()) 4580 return SC_None; 4581 return SC_Extern; 4582 case DeclSpec::SCS_static: return SC_Static; 4583 case DeclSpec::SCS_auto: return SC_Auto; 4584 case DeclSpec::SCS_register: return SC_Register; 4585 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4586 // Illegal SCSs map to None: error reporting is up to the caller. 4587 case DeclSpec::SCS_mutable: // Fall through. 4588 case DeclSpec::SCS_typedef: return SC_None; 4589 } 4590 llvm_unreachable("unknown storage class specifier"); 4591 } 4592 4593 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4594 assert(Record->hasInClassInitializer()); 4595 4596 for (const auto *I : Record->decls()) { 4597 const auto *FD = dyn_cast<FieldDecl>(I); 4598 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4599 FD = IFD->getAnonField(); 4600 if (FD && FD->hasInClassInitializer()) 4601 return FD->getLocation(); 4602 } 4603 4604 llvm_unreachable("couldn't find in-class initializer"); 4605 } 4606 4607 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4608 SourceLocation DefaultInitLoc) { 4609 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4610 return; 4611 4612 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4613 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4614 } 4615 4616 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4617 CXXRecordDecl *AnonUnion) { 4618 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4619 return; 4620 4621 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4622 } 4623 4624 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4625 /// anonymous structure or union. Anonymous unions are a C++ feature 4626 /// (C++ [class.union]) and a C11 feature; anonymous structures 4627 /// are a C11 feature and GNU C++ extension. 4628 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4629 AccessSpecifier AS, 4630 RecordDecl *Record, 4631 const PrintingPolicy &Policy) { 4632 DeclContext *Owner = Record->getDeclContext(); 4633 4634 // Diagnose whether this anonymous struct/union is an extension. 4635 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4636 Diag(Record->getLocation(), diag::ext_anonymous_union); 4637 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4638 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4639 else if (!Record->isUnion() && !getLangOpts().C11) 4640 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4641 4642 // C and C++ require different kinds of checks for anonymous 4643 // structs/unions. 4644 bool Invalid = false; 4645 if (getLangOpts().CPlusPlus) { 4646 const char *PrevSpec = nullptr; 4647 unsigned DiagID; 4648 if (Record->isUnion()) { 4649 // C++ [class.union]p6: 4650 // C++17 [class.union.anon]p2: 4651 // Anonymous unions declared in a named namespace or in the 4652 // global namespace shall be declared static. 4653 DeclContext *OwnerScope = Owner->getRedeclContext(); 4654 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4655 (OwnerScope->isTranslationUnit() || 4656 (OwnerScope->isNamespace() && 4657 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4658 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4659 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4660 4661 // Recover by adding 'static'. 4662 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4663 PrevSpec, DiagID, Policy); 4664 } 4665 // C++ [class.union]p6: 4666 // A storage class is not allowed in a declaration of an 4667 // anonymous union in a class scope. 4668 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4669 isa<RecordDecl>(Owner)) { 4670 Diag(DS.getStorageClassSpecLoc(), 4671 diag::err_anonymous_union_with_storage_spec) 4672 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4673 4674 // Recover by removing the storage specifier. 4675 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4676 SourceLocation(), 4677 PrevSpec, DiagID, Context.getPrintingPolicy()); 4678 } 4679 } 4680 4681 // Ignore const/volatile/restrict qualifiers. 4682 if (DS.getTypeQualifiers()) { 4683 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4684 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4685 << Record->isUnion() << "const" 4686 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4687 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4688 Diag(DS.getVolatileSpecLoc(), 4689 diag::ext_anonymous_struct_union_qualified) 4690 << Record->isUnion() << "volatile" 4691 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4692 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4693 Diag(DS.getRestrictSpecLoc(), 4694 diag::ext_anonymous_struct_union_qualified) 4695 << Record->isUnion() << "restrict" 4696 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4697 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4698 Diag(DS.getAtomicSpecLoc(), 4699 diag::ext_anonymous_struct_union_qualified) 4700 << Record->isUnion() << "_Atomic" 4701 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4702 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4703 Diag(DS.getUnalignedSpecLoc(), 4704 diag::ext_anonymous_struct_union_qualified) 4705 << Record->isUnion() << "__unaligned" 4706 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4707 4708 DS.ClearTypeQualifiers(); 4709 } 4710 4711 // C++ [class.union]p2: 4712 // The member-specification of an anonymous union shall only 4713 // define non-static data members. [Note: nested types and 4714 // functions cannot be declared within an anonymous union. ] 4715 for (auto *Mem : Record->decls()) { 4716 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4717 // C++ [class.union]p3: 4718 // An anonymous union shall not have private or protected 4719 // members (clause 11). 4720 assert(FD->getAccess() != AS_none); 4721 if (FD->getAccess() != AS_public) { 4722 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4723 << Record->isUnion() << (FD->getAccess() == AS_protected); 4724 Invalid = true; 4725 } 4726 4727 // C++ [class.union]p1 4728 // An object of a class with a non-trivial constructor, a non-trivial 4729 // copy constructor, a non-trivial destructor, or a non-trivial copy 4730 // assignment operator cannot be a member of a union, nor can an 4731 // array of such objects. 4732 if (CheckNontrivialField(FD)) 4733 Invalid = true; 4734 } else if (Mem->isImplicit()) { 4735 // Any implicit members are fine. 4736 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4737 // This is a type that showed up in an 4738 // elaborated-type-specifier inside the anonymous struct or 4739 // union, but which actually declares a type outside of the 4740 // anonymous struct or union. It's okay. 4741 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4742 if (!MemRecord->isAnonymousStructOrUnion() && 4743 MemRecord->getDeclName()) { 4744 // Visual C++ allows type definition in anonymous struct or union. 4745 if (getLangOpts().MicrosoftExt) 4746 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4747 << Record->isUnion(); 4748 else { 4749 // This is a nested type declaration. 4750 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4751 << Record->isUnion(); 4752 Invalid = true; 4753 } 4754 } else { 4755 // This is an anonymous type definition within another anonymous type. 4756 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4757 // not part of standard C++. 4758 Diag(MemRecord->getLocation(), 4759 diag::ext_anonymous_record_with_anonymous_type) 4760 << Record->isUnion(); 4761 } 4762 } else if (isa<AccessSpecDecl>(Mem)) { 4763 // Any access specifier is fine. 4764 } else if (isa<StaticAssertDecl>(Mem)) { 4765 // In C++1z, static_assert declarations are also fine. 4766 } else { 4767 // We have something that isn't a non-static data 4768 // member. Complain about it. 4769 unsigned DK = diag::err_anonymous_record_bad_member; 4770 if (isa<TypeDecl>(Mem)) 4771 DK = diag::err_anonymous_record_with_type; 4772 else if (isa<FunctionDecl>(Mem)) 4773 DK = diag::err_anonymous_record_with_function; 4774 else if (isa<VarDecl>(Mem)) 4775 DK = diag::err_anonymous_record_with_static; 4776 4777 // Visual C++ allows type definition in anonymous struct or union. 4778 if (getLangOpts().MicrosoftExt && 4779 DK == diag::err_anonymous_record_with_type) 4780 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4781 << Record->isUnion(); 4782 else { 4783 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4784 Invalid = true; 4785 } 4786 } 4787 } 4788 4789 // C++11 [class.union]p8 (DR1460): 4790 // At most one variant member of a union may have a 4791 // brace-or-equal-initializer. 4792 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4793 Owner->isRecord()) 4794 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4795 cast<CXXRecordDecl>(Record)); 4796 } 4797 4798 if (!Record->isUnion() && !Owner->isRecord()) { 4799 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4800 << getLangOpts().CPlusPlus; 4801 Invalid = true; 4802 } 4803 4804 // Mock up a declarator. 4805 Declarator Dc(DS, DeclaratorContext::MemberContext); 4806 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4807 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4808 4809 // Create a declaration for this anonymous struct/union. 4810 NamedDecl *Anon = nullptr; 4811 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4812 Anon = FieldDecl::Create( 4813 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 4814 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 4815 /*BitWidth=*/nullptr, /*Mutable=*/false, 4816 /*InitStyle=*/ICIS_NoInit); 4817 Anon->setAccess(AS); 4818 if (getLangOpts().CPlusPlus) 4819 FieldCollector->Add(cast<FieldDecl>(Anon)); 4820 } else { 4821 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4822 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4823 if (SCSpec == DeclSpec::SCS_mutable) { 4824 // mutable can only appear on non-static class members, so it's always 4825 // an error here 4826 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4827 Invalid = true; 4828 SC = SC_None; 4829 } 4830 4831 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 4832 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4833 Context.getTypeDeclType(Record), TInfo, SC); 4834 4835 // Default-initialize the implicit variable. This initialization will be 4836 // trivial in almost all cases, except if a union member has an in-class 4837 // initializer: 4838 // union { int n = 0; }; 4839 ActOnUninitializedDecl(Anon); 4840 } 4841 Anon->setImplicit(); 4842 4843 // Mark this as an anonymous struct/union type. 4844 Record->setAnonymousStructOrUnion(true); 4845 4846 // Add the anonymous struct/union object to the current 4847 // context. We'll be referencing this object when we refer to one of 4848 // its members. 4849 Owner->addDecl(Anon); 4850 4851 // Inject the members of the anonymous struct/union into the owning 4852 // context and into the identifier resolver chain for name lookup 4853 // purposes. 4854 SmallVector<NamedDecl*, 2> Chain; 4855 Chain.push_back(Anon); 4856 4857 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4858 Invalid = true; 4859 4860 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4861 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4862 Decl *ManglingContextDecl; 4863 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4864 NewVD->getDeclContext(), ManglingContextDecl)) { 4865 Context.setManglingNumber( 4866 NewVD, MCtx->getManglingNumber( 4867 NewVD, getMSManglingNumber(getLangOpts(), S))); 4868 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4869 } 4870 } 4871 } 4872 4873 if (Invalid) 4874 Anon->setInvalidDecl(); 4875 4876 return Anon; 4877 } 4878 4879 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4880 /// Microsoft C anonymous structure. 4881 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4882 /// Example: 4883 /// 4884 /// struct A { int a; }; 4885 /// struct B { struct A; int b; }; 4886 /// 4887 /// void foo() { 4888 /// B var; 4889 /// var.a = 3; 4890 /// } 4891 /// 4892 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4893 RecordDecl *Record) { 4894 assert(Record && "expected a record!"); 4895 4896 // Mock up a declarator. 4897 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4898 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4899 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4900 4901 auto *ParentDecl = cast<RecordDecl>(CurContext); 4902 QualType RecTy = Context.getTypeDeclType(Record); 4903 4904 // Create a declaration for this anonymous struct. 4905 NamedDecl *Anon = 4906 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 4907 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 4908 /*BitWidth=*/nullptr, /*Mutable=*/false, 4909 /*InitStyle=*/ICIS_NoInit); 4910 Anon->setImplicit(); 4911 4912 // Add the anonymous struct object to the current context. 4913 CurContext->addDecl(Anon); 4914 4915 // Inject the members of the anonymous struct into the current 4916 // context and into the identifier resolver chain for name lookup 4917 // purposes. 4918 SmallVector<NamedDecl*, 2> Chain; 4919 Chain.push_back(Anon); 4920 4921 RecordDecl *RecordDef = Record->getDefinition(); 4922 if (RequireCompleteType(Anon->getLocation(), RecTy, 4923 diag::err_field_incomplete) || 4924 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4925 AS_none, Chain)) { 4926 Anon->setInvalidDecl(); 4927 ParentDecl->setInvalidDecl(); 4928 } 4929 4930 return Anon; 4931 } 4932 4933 /// GetNameForDeclarator - Determine the full declaration name for the 4934 /// given Declarator. 4935 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4936 return GetNameFromUnqualifiedId(D.getName()); 4937 } 4938 4939 /// Retrieves the declaration name from a parsed unqualified-id. 4940 DeclarationNameInfo 4941 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4942 DeclarationNameInfo NameInfo; 4943 NameInfo.setLoc(Name.StartLocation); 4944 4945 switch (Name.getKind()) { 4946 4947 case UnqualifiedIdKind::IK_ImplicitSelfParam: 4948 case UnqualifiedIdKind::IK_Identifier: 4949 NameInfo.setName(Name.Identifier); 4950 return NameInfo; 4951 4952 case UnqualifiedIdKind::IK_DeductionGuideName: { 4953 // C++ [temp.deduct.guide]p3: 4954 // The simple-template-id shall name a class template specialization. 4955 // The template-name shall be the same identifier as the template-name 4956 // of the simple-template-id. 4957 // These together intend to imply that the template-name shall name a 4958 // class template. 4959 // FIXME: template<typename T> struct X {}; 4960 // template<typename T> using Y = X<T>; 4961 // Y(int) -> Y<int>; 4962 // satisfies these rules but does not name a class template. 4963 TemplateName TN = Name.TemplateName.get().get(); 4964 auto *Template = TN.getAsTemplateDecl(); 4965 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4966 Diag(Name.StartLocation, 4967 diag::err_deduction_guide_name_not_class_template) 4968 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4969 if (Template) 4970 Diag(Template->getLocation(), diag::note_template_decl_here); 4971 return DeclarationNameInfo(); 4972 } 4973 4974 NameInfo.setName( 4975 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4976 return NameInfo; 4977 } 4978 4979 case UnqualifiedIdKind::IK_OperatorFunctionId: 4980 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4981 Name.OperatorFunctionId.Operator)); 4982 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4983 = Name.OperatorFunctionId.SymbolLocations[0]; 4984 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4985 = Name.EndLocation.getRawEncoding(); 4986 return NameInfo; 4987 4988 case UnqualifiedIdKind::IK_LiteralOperatorId: 4989 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4990 Name.Identifier)); 4991 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4992 return NameInfo; 4993 4994 case UnqualifiedIdKind::IK_ConversionFunctionId: { 4995 TypeSourceInfo *TInfo; 4996 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4997 if (Ty.isNull()) 4998 return DeclarationNameInfo(); 4999 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5000 Context.getCanonicalType(Ty))); 5001 NameInfo.setNamedTypeInfo(TInfo); 5002 return NameInfo; 5003 } 5004 5005 case UnqualifiedIdKind::IK_ConstructorName: { 5006 TypeSourceInfo *TInfo; 5007 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5008 if (Ty.isNull()) 5009 return DeclarationNameInfo(); 5010 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5011 Context.getCanonicalType(Ty))); 5012 NameInfo.setNamedTypeInfo(TInfo); 5013 return NameInfo; 5014 } 5015 5016 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5017 // In well-formed code, we can only have a constructor 5018 // template-id that refers to the current context, so go there 5019 // to find the actual type being constructed. 5020 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5021 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5022 return DeclarationNameInfo(); 5023 5024 // Determine the type of the class being constructed. 5025 QualType CurClassType = Context.getTypeDeclType(CurClass); 5026 5027 // FIXME: Check two things: that the template-id names the same type as 5028 // CurClassType, and that the template-id does not occur when the name 5029 // was qualified. 5030 5031 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5032 Context.getCanonicalType(CurClassType))); 5033 // FIXME: should we retrieve TypeSourceInfo? 5034 NameInfo.setNamedTypeInfo(nullptr); 5035 return NameInfo; 5036 } 5037 5038 case UnqualifiedIdKind::IK_DestructorName: { 5039 TypeSourceInfo *TInfo; 5040 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5041 if (Ty.isNull()) 5042 return DeclarationNameInfo(); 5043 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5044 Context.getCanonicalType(Ty))); 5045 NameInfo.setNamedTypeInfo(TInfo); 5046 return NameInfo; 5047 } 5048 5049 case UnqualifiedIdKind::IK_TemplateId: { 5050 TemplateName TName = Name.TemplateId->Template.get(); 5051 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5052 return Context.getNameForTemplate(TName, TNameLoc); 5053 } 5054 5055 } // switch (Name.getKind()) 5056 5057 llvm_unreachable("Unknown name kind"); 5058 } 5059 5060 static QualType getCoreType(QualType Ty) { 5061 do { 5062 if (Ty->isPointerType() || Ty->isReferenceType()) 5063 Ty = Ty->getPointeeType(); 5064 else if (Ty->isArrayType()) 5065 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5066 else 5067 return Ty.withoutLocalFastQualifiers(); 5068 } while (true); 5069 } 5070 5071 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5072 /// and Definition have "nearly" matching parameters. This heuristic is 5073 /// used to improve diagnostics in the case where an out-of-line function 5074 /// definition doesn't match any declaration within the class or namespace. 5075 /// Also sets Params to the list of indices to the parameters that differ 5076 /// between the declaration and the definition. If hasSimilarParameters 5077 /// returns true and Params is empty, then all of the parameters match. 5078 static bool hasSimilarParameters(ASTContext &Context, 5079 FunctionDecl *Declaration, 5080 FunctionDecl *Definition, 5081 SmallVectorImpl<unsigned> &Params) { 5082 Params.clear(); 5083 if (Declaration->param_size() != Definition->param_size()) 5084 return false; 5085 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5086 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5087 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5088 5089 // The parameter types are identical 5090 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5091 continue; 5092 5093 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5094 QualType DefParamBaseTy = getCoreType(DefParamTy); 5095 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5096 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5097 5098 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5099 (DeclTyName && DeclTyName == DefTyName)) 5100 Params.push_back(Idx); 5101 else // The two parameters aren't even close 5102 return false; 5103 } 5104 5105 return true; 5106 } 5107 5108 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5109 /// declarator needs to be rebuilt in the current instantiation. 5110 /// Any bits of declarator which appear before the name are valid for 5111 /// consideration here. That's specifically the type in the decl spec 5112 /// and the base type in any member-pointer chunks. 5113 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5114 DeclarationName Name) { 5115 // The types we specifically need to rebuild are: 5116 // - typenames, typeofs, and decltypes 5117 // - types which will become injected class names 5118 // Of course, we also need to rebuild any type referencing such a 5119 // type. It's safest to just say "dependent", but we call out a 5120 // few cases here. 5121 5122 DeclSpec &DS = D.getMutableDeclSpec(); 5123 switch (DS.getTypeSpecType()) { 5124 case DeclSpec::TST_typename: 5125 case DeclSpec::TST_typeofType: 5126 case DeclSpec::TST_underlyingType: 5127 case DeclSpec::TST_atomic: { 5128 // Grab the type from the parser. 5129 TypeSourceInfo *TSI = nullptr; 5130 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5131 if (T.isNull() || !T->isDependentType()) break; 5132 5133 // Make sure there's a type source info. This isn't really much 5134 // of a waste; most dependent types should have type source info 5135 // attached already. 5136 if (!TSI) 5137 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5138 5139 // Rebuild the type in the current instantiation. 5140 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5141 if (!TSI) return true; 5142 5143 // Store the new type back in the decl spec. 5144 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5145 DS.UpdateTypeRep(LocType); 5146 break; 5147 } 5148 5149 case DeclSpec::TST_decltype: 5150 case DeclSpec::TST_typeofExpr: { 5151 Expr *E = DS.getRepAsExpr(); 5152 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5153 if (Result.isInvalid()) return true; 5154 DS.UpdateExprRep(Result.get()); 5155 break; 5156 } 5157 5158 default: 5159 // Nothing to do for these decl specs. 5160 break; 5161 } 5162 5163 // It doesn't matter what order we do this in. 5164 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5165 DeclaratorChunk &Chunk = D.getTypeObject(I); 5166 5167 // The only type information in the declarator which can come 5168 // before the declaration name is the base type of a member 5169 // pointer. 5170 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5171 continue; 5172 5173 // Rebuild the scope specifier in-place. 5174 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5175 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5176 return true; 5177 } 5178 5179 return false; 5180 } 5181 5182 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5183 D.setFunctionDefinitionKind(FDK_Declaration); 5184 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5185 5186 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5187 Dcl && Dcl->getDeclContext()->isFileContext()) 5188 Dcl->setTopLevelDeclInObjCContainer(); 5189 5190 if (getLangOpts().OpenCL) 5191 setCurrentOpenCLExtensionForDecl(Dcl); 5192 5193 return Dcl; 5194 } 5195 5196 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5197 /// If T is the name of a class, then each of the following shall have a 5198 /// name different from T: 5199 /// - every static data member of class T; 5200 /// - every member function of class T 5201 /// - every member of class T that is itself a type; 5202 /// \returns true if the declaration name violates these rules. 5203 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5204 DeclarationNameInfo NameInfo) { 5205 DeclarationName Name = NameInfo.getName(); 5206 5207 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5208 while (Record && Record->isAnonymousStructOrUnion()) 5209 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5210 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5211 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5212 return true; 5213 } 5214 5215 return false; 5216 } 5217 5218 /// Diagnose a declaration whose declarator-id has the given 5219 /// nested-name-specifier. 5220 /// 5221 /// \param SS The nested-name-specifier of the declarator-id. 5222 /// 5223 /// \param DC The declaration context to which the nested-name-specifier 5224 /// resolves. 5225 /// 5226 /// \param Name The name of the entity being declared. 5227 /// 5228 /// \param Loc The location of the name of the entity being declared. 5229 /// 5230 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5231 /// we're declaring an explicit / partial specialization / instantiation. 5232 /// 5233 /// \returns true if we cannot safely recover from this error, false otherwise. 5234 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5235 DeclarationName Name, 5236 SourceLocation Loc, bool IsTemplateId) { 5237 DeclContext *Cur = CurContext; 5238 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5239 Cur = Cur->getParent(); 5240 5241 // If the user provided a superfluous scope specifier that refers back to the 5242 // class in which the entity is already declared, diagnose and ignore it. 5243 // 5244 // class X { 5245 // void X::f(); 5246 // }; 5247 // 5248 // Note, it was once ill-formed to give redundant qualification in all 5249 // contexts, but that rule was removed by DR482. 5250 if (Cur->Equals(DC)) { 5251 if (Cur->isRecord()) { 5252 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5253 : diag::err_member_extra_qualification) 5254 << Name << FixItHint::CreateRemoval(SS.getRange()); 5255 SS.clear(); 5256 } else { 5257 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5258 } 5259 return false; 5260 } 5261 5262 // Check whether the qualifying scope encloses the scope of the original 5263 // declaration. For a template-id, we perform the checks in 5264 // CheckTemplateSpecializationScope. 5265 if (!Cur->Encloses(DC) && !IsTemplateId) { 5266 if (Cur->isRecord()) 5267 Diag(Loc, diag::err_member_qualification) 5268 << Name << SS.getRange(); 5269 else if (isa<TranslationUnitDecl>(DC)) 5270 Diag(Loc, diag::err_invalid_declarator_global_scope) 5271 << Name << SS.getRange(); 5272 else if (isa<FunctionDecl>(Cur)) 5273 Diag(Loc, diag::err_invalid_declarator_in_function) 5274 << Name << SS.getRange(); 5275 else if (isa<BlockDecl>(Cur)) 5276 Diag(Loc, diag::err_invalid_declarator_in_block) 5277 << Name << SS.getRange(); 5278 else 5279 Diag(Loc, diag::err_invalid_declarator_scope) 5280 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5281 5282 return true; 5283 } 5284 5285 if (Cur->isRecord()) { 5286 // Cannot qualify members within a class. 5287 Diag(Loc, diag::err_member_qualification) 5288 << Name << SS.getRange(); 5289 SS.clear(); 5290 5291 // C++ constructors and destructors with incorrect scopes can break 5292 // our AST invariants by having the wrong underlying types. If 5293 // that's the case, then drop this declaration entirely. 5294 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5295 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5296 !Context.hasSameType(Name.getCXXNameType(), 5297 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5298 return true; 5299 5300 return false; 5301 } 5302 5303 // C++11 [dcl.meaning]p1: 5304 // [...] "The nested-name-specifier of the qualified declarator-id shall 5305 // not begin with a decltype-specifer" 5306 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5307 while (SpecLoc.getPrefix()) 5308 SpecLoc = SpecLoc.getPrefix(); 5309 if (dyn_cast_or_null<DecltypeType>( 5310 SpecLoc.getNestedNameSpecifier()->getAsType())) 5311 Diag(Loc, diag::err_decltype_in_declarator) 5312 << SpecLoc.getTypeLoc().getSourceRange(); 5313 5314 return false; 5315 } 5316 5317 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5318 MultiTemplateParamsArg TemplateParamLists) { 5319 // TODO: consider using NameInfo for diagnostic. 5320 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5321 DeclarationName Name = NameInfo.getName(); 5322 5323 // All of these full declarators require an identifier. If it doesn't have 5324 // one, the ParsedFreeStandingDeclSpec action should be used. 5325 if (D.isDecompositionDeclarator()) { 5326 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5327 } else if (!Name) { 5328 if (!D.isInvalidType()) // Reject this if we think it is valid. 5329 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5330 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5331 return nullptr; 5332 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5333 return nullptr; 5334 5335 // The scope passed in may not be a decl scope. Zip up the scope tree until 5336 // we find one that is. 5337 while ((S->getFlags() & Scope::DeclScope) == 0 || 5338 (S->getFlags() & Scope::TemplateParamScope) != 0) 5339 S = S->getParent(); 5340 5341 DeclContext *DC = CurContext; 5342 if (D.getCXXScopeSpec().isInvalid()) 5343 D.setInvalidType(); 5344 else if (D.getCXXScopeSpec().isSet()) { 5345 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5346 UPPC_DeclarationQualifier)) 5347 return nullptr; 5348 5349 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5350 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5351 if (!DC || isa<EnumDecl>(DC)) { 5352 // If we could not compute the declaration context, it's because the 5353 // declaration context is dependent but does not refer to a class, 5354 // class template, or class template partial specialization. Complain 5355 // and return early, to avoid the coming semantic disaster. 5356 Diag(D.getIdentifierLoc(), 5357 diag::err_template_qualified_declarator_no_match) 5358 << D.getCXXScopeSpec().getScopeRep() 5359 << D.getCXXScopeSpec().getRange(); 5360 return nullptr; 5361 } 5362 bool IsDependentContext = DC->isDependentContext(); 5363 5364 if (!IsDependentContext && 5365 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5366 return nullptr; 5367 5368 // If a class is incomplete, do not parse entities inside it. 5369 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5370 Diag(D.getIdentifierLoc(), 5371 diag::err_member_def_undefined_record) 5372 << Name << DC << D.getCXXScopeSpec().getRange(); 5373 return nullptr; 5374 } 5375 if (!D.getDeclSpec().isFriendSpecified()) { 5376 if (diagnoseQualifiedDeclaration( 5377 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5378 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5379 if (DC->isRecord()) 5380 return nullptr; 5381 5382 D.setInvalidType(); 5383 } 5384 } 5385 5386 // Check whether we need to rebuild the type of the given 5387 // declaration in the current instantiation. 5388 if (EnteringContext && IsDependentContext && 5389 TemplateParamLists.size() != 0) { 5390 ContextRAII SavedContext(*this, DC); 5391 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5392 D.setInvalidType(); 5393 } 5394 } 5395 5396 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5397 QualType R = TInfo->getType(); 5398 5399 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5400 UPPC_DeclarationType)) 5401 D.setInvalidType(); 5402 5403 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5404 forRedeclarationInCurContext()); 5405 5406 // See if this is a redefinition of a variable in the same scope. 5407 if (!D.getCXXScopeSpec().isSet()) { 5408 bool IsLinkageLookup = false; 5409 bool CreateBuiltins = false; 5410 5411 // If the declaration we're planning to build will be a function 5412 // or object with linkage, then look for another declaration with 5413 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5414 // 5415 // If the declaration we're planning to build will be declared with 5416 // external linkage in the translation unit, create any builtin with 5417 // the same name. 5418 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5419 /* Do nothing*/; 5420 else if (CurContext->isFunctionOrMethod() && 5421 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5422 R->isFunctionType())) { 5423 IsLinkageLookup = true; 5424 CreateBuiltins = 5425 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5426 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5427 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5428 CreateBuiltins = true; 5429 5430 if (IsLinkageLookup) { 5431 Previous.clear(LookupRedeclarationWithLinkage); 5432 Previous.setRedeclarationKind(ForExternalRedeclaration); 5433 } 5434 5435 LookupName(Previous, S, CreateBuiltins); 5436 } else { // Something like "int foo::x;" 5437 LookupQualifiedName(Previous, DC); 5438 5439 // C++ [dcl.meaning]p1: 5440 // When the declarator-id is qualified, the declaration shall refer to a 5441 // previously declared member of the class or namespace to which the 5442 // qualifier refers (or, in the case of a namespace, of an element of the 5443 // inline namespace set of that namespace (7.3.1)) or to a specialization 5444 // thereof; [...] 5445 // 5446 // Note that we already checked the context above, and that we do not have 5447 // enough information to make sure that Previous contains the declaration 5448 // we want to match. For example, given: 5449 // 5450 // class X { 5451 // void f(); 5452 // void f(float); 5453 // }; 5454 // 5455 // void X::f(int) { } // ill-formed 5456 // 5457 // In this case, Previous will point to the overload set 5458 // containing the two f's declared in X, but neither of them 5459 // matches. 5460 5461 // C++ [dcl.meaning]p1: 5462 // [...] the member shall not merely have been introduced by a 5463 // using-declaration in the scope of the class or namespace nominated by 5464 // the nested-name-specifier of the declarator-id. 5465 RemoveUsingDecls(Previous); 5466 } 5467 5468 if (Previous.isSingleResult() && 5469 Previous.getFoundDecl()->isTemplateParameter()) { 5470 // Maybe we will complain about the shadowed template parameter. 5471 if (!D.isInvalidType()) 5472 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5473 Previous.getFoundDecl()); 5474 5475 // Just pretend that we didn't see the previous declaration. 5476 Previous.clear(); 5477 } 5478 5479 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5480 // Forget that the previous declaration is the injected-class-name. 5481 Previous.clear(); 5482 5483 // In C++, the previous declaration we find might be a tag type 5484 // (class or enum). In this case, the new declaration will hide the 5485 // tag type. Note that this applies to functions, function templates, and 5486 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5487 if (Previous.isSingleTagDecl() && 5488 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5489 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5490 Previous.clear(); 5491 5492 // Check that there are no default arguments other than in the parameters 5493 // of a function declaration (C++ only). 5494 if (getLangOpts().CPlusPlus) 5495 CheckExtraCXXDefaultArguments(D); 5496 5497 NamedDecl *New; 5498 5499 bool AddToScope = true; 5500 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5501 if (TemplateParamLists.size()) { 5502 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5503 return nullptr; 5504 } 5505 5506 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5507 } else if (R->isFunctionType()) { 5508 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5509 TemplateParamLists, 5510 AddToScope); 5511 } else { 5512 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5513 AddToScope); 5514 } 5515 5516 if (!New) 5517 return nullptr; 5518 5519 // If this has an identifier and is not a function template specialization, 5520 // add it to the scope stack. 5521 if (New->getDeclName() && AddToScope) 5522 PushOnScopeChains(New, S); 5523 5524 if (isInOpenMPDeclareTargetContext()) 5525 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5526 5527 return New; 5528 } 5529 5530 /// Helper method to turn variable array types into constant array 5531 /// types in certain situations which would otherwise be errors (for 5532 /// GCC compatibility). 5533 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5534 ASTContext &Context, 5535 bool &SizeIsNegative, 5536 llvm::APSInt &Oversized) { 5537 // This method tries to turn a variable array into a constant 5538 // array even when the size isn't an ICE. This is necessary 5539 // for compatibility with code that depends on gcc's buggy 5540 // constant expression folding, like struct {char x[(int)(char*)2];} 5541 SizeIsNegative = false; 5542 Oversized = 0; 5543 5544 if (T->isDependentType()) 5545 return QualType(); 5546 5547 QualifierCollector Qs; 5548 const Type *Ty = Qs.strip(T); 5549 5550 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5551 QualType Pointee = PTy->getPointeeType(); 5552 QualType FixedType = 5553 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5554 Oversized); 5555 if (FixedType.isNull()) return FixedType; 5556 FixedType = Context.getPointerType(FixedType); 5557 return Qs.apply(Context, FixedType); 5558 } 5559 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5560 QualType Inner = PTy->getInnerType(); 5561 QualType FixedType = 5562 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5563 Oversized); 5564 if (FixedType.isNull()) return FixedType; 5565 FixedType = Context.getParenType(FixedType); 5566 return Qs.apply(Context, FixedType); 5567 } 5568 5569 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5570 if (!VLATy) 5571 return QualType(); 5572 // FIXME: We should probably handle this case 5573 if (VLATy->getElementType()->isVariablyModifiedType()) 5574 return QualType(); 5575 5576 Expr::EvalResult Result; 5577 if (!VLATy->getSizeExpr() || 5578 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5579 return QualType(); 5580 5581 llvm::APSInt Res = Result.Val.getInt(); 5582 5583 // Check whether the array size is negative. 5584 if (Res.isSigned() && Res.isNegative()) { 5585 SizeIsNegative = true; 5586 return QualType(); 5587 } 5588 5589 // Check whether the array is too large to be addressed. 5590 unsigned ActiveSizeBits 5591 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5592 Res); 5593 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5594 Oversized = Res; 5595 return QualType(); 5596 } 5597 5598 return Context.getConstantArrayType(VLATy->getElementType(), 5599 Res, ArrayType::Normal, 0); 5600 } 5601 5602 static void 5603 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5604 SrcTL = SrcTL.getUnqualifiedLoc(); 5605 DstTL = DstTL.getUnqualifiedLoc(); 5606 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5607 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5608 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5609 DstPTL.getPointeeLoc()); 5610 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5611 return; 5612 } 5613 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5614 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5615 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5616 DstPTL.getInnerLoc()); 5617 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5618 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5619 return; 5620 } 5621 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5622 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5623 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5624 TypeLoc DstElemTL = DstATL.getElementLoc(); 5625 DstElemTL.initializeFullCopy(SrcElemTL); 5626 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5627 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5628 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5629 } 5630 5631 /// Helper method to turn variable array types into constant array 5632 /// types in certain situations which would otherwise be errors (for 5633 /// GCC compatibility). 5634 static TypeSourceInfo* 5635 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5636 ASTContext &Context, 5637 bool &SizeIsNegative, 5638 llvm::APSInt &Oversized) { 5639 QualType FixedTy 5640 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5641 SizeIsNegative, Oversized); 5642 if (FixedTy.isNull()) 5643 return nullptr; 5644 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5645 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5646 FixedTInfo->getTypeLoc()); 5647 return FixedTInfo; 5648 } 5649 5650 /// Register the given locally-scoped extern "C" declaration so 5651 /// that it can be found later for redeclarations. We include any extern "C" 5652 /// declaration that is not visible in the translation unit here, not just 5653 /// function-scope declarations. 5654 void 5655 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5656 if (!getLangOpts().CPlusPlus && 5657 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5658 // Don't need to track declarations in the TU in C. 5659 return; 5660 5661 // Note that we have a locally-scoped external with this name. 5662 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5663 } 5664 5665 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5666 // FIXME: We can have multiple results via __attribute__((overloadable)). 5667 auto Result = Context.getExternCContextDecl()->lookup(Name); 5668 return Result.empty() ? nullptr : *Result.begin(); 5669 } 5670 5671 /// Diagnose function specifiers on a declaration of an identifier that 5672 /// does not identify a function. 5673 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5674 // FIXME: We should probably indicate the identifier in question to avoid 5675 // confusion for constructs like "virtual int a(), b;" 5676 if (DS.isVirtualSpecified()) 5677 Diag(DS.getVirtualSpecLoc(), 5678 diag::err_virtual_non_function); 5679 5680 if (DS.isExplicitSpecified()) 5681 Diag(DS.getExplicitSpecLoc(), 5682 diag::err_explicit_non_function); 5683 5684 if (DS.isNoreturnSpecified()) 5685 Diag(DS.getNoreturnSpecLoc(), 5686 diag::err_noreturn_non_function); 5687 } 5688 5689 NamedDecl* 5690 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5691 TypeSourceInfo *TInfo, LookupResult &Previous) { 5692 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5693 if (D.getCXXScopeSpec().isSet()) { 5694 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5695 << D.getCXXScopeSpec().getRange(); 5696 D.setInvalidType(); 5697 // Pretend we didn't see the scope specifier. 5698 DC = CurContext; 5699 Previous.clear(); 5700 } 5701 5702 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5703 5704 if (D.getDeclSpec().isInlineSpecified()) 5705 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5706 << getLangOpts().CPlusPlus17; 5707 if (D.getDeclSpec().isConstexprSpecified()) 5708 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5709 << 1; 5710 5711 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5712 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5713 Diag(D.getName().StartLocation, 5714 diag::err_deduction_guide_invalid_specifier) 5715 << "typedef"; 5716 else 5717 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5718 << D.getName().getSourceRange(); 5719 return nullptr; 5720 } 5721 5722 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5723 if (!NewTD) return nullptr; 5724 5725 // Handle attributes prior to checking for duplicates in MergeVarDecl 5726 ProcessDeclAttributes(S, NewTD, D); 5727 5728 CheckTypedefForVariablyModifiedType(S, NewTD); 5729 5730 bool Redeclaration = D.isRedeclaration(); 5731 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5732 D.setRedeclaration(Redeclaration); 5733 return ND; 5734 } 5735 5736 void 5737 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5738 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5739 // then it shall have block scope. 5740 // Note that variably modified types must be fixed before merging the decl so 5741 // that redeclarations will match. 5742 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5743 QualType T = TInfo->getType(); 5744 if (T->isVariablyModifiedType()) { 5745 setFunctionHasBranchProtectedScope(); 5746 5747 if (S->getFnParent() == nullptr) { 5748 bool SizeIsNegative; 5749 llvm::APSInt Oversized; 5750 TypeSourceInfo *FixedTInfo = 5751 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5752 SizeIsNegative, 5753 Oversized); 5754 if (FixedTInfo) { 5755 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5756 NewTD->setTypeSourceInfo(FixedTInfo); 5757 } else { 5758 if (SizeIsNegative) 5759 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5760 else if (T->isVariableArrayType()) 5761 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5762 else if (Oversized.getBoolValue()) 5763 Diag(NewTD->getLocation(), diag::err_array_too_large) 5764 << Oversized.toString(10); 5765 else 5766 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5767 NewTD->setInvalidDecl(); 5768 } 5769 } 5770 } 5771 } 5772 5773 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5774 /// declares a typedef-name, either using the 'typedef' type specifier or via 5775 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5776 NamedDecl* 5777 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5778 LookupResult &Previous, bool &Redeclaration) { 5779 5780 // Find the shadowed declaration before filtering for scope. 5781 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5782 5783 // Merge the decl with the existing one if appropriate. If the decl is 5784 // in an outer scope, it isn't the same thing. 5785 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5786 /*AllowInlineNamespace*/false); 5787 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5788 if (!Previous.empty()) { 5789 Redeclaration = true; 5790 MergeTypedefNameDecl(S, NewTD, Previous); 5791 } 5792 5793 if (ShadowedDecl && !Redeclaration) 5794 CheckShadow(NewTD, ShadowedDecl, Previous); 5795 5796 // If this is the C FILE type, notify the AST context. 5797 if (IdentifierInfo *II = NewTD->getIdentifier()) 5798 if (!NewTD->isInvalidDecl() && 5799 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5800 if (II->isStr("FILE")) 5801 Context.setFILEDecl(NewTD); 5802 else if (II->isStr("jmp_buf")) 5803 Context.setjmp_bufDecl(NewTD); 5804 else if (II->isStr("sigjmp_buf")) 5805 Context.setsigjmp_bufDecl(NewTD); 5806 else if (II->isStr("ucontext_t")) 5807 Context.setucontext_tDecl(NewTD); 5808 } 5809 5810 return NewTD; 5811 } 5812 5813 /// Determines whether the given declaration is an out-of-scope 5814 /// previous declaration. 5815 /// 5816 /// This routine should be invoked when name lookup has found a 5817 /// previous declaration (PrevDecl) that is not in the scope where a 5818 /// new declaration by the same name is being introduced. If the new 5819 /// declaration occurs in a local scope, previous declarations with 5820 /// linkage may still be considered previous declarations (C99 5821 /// 6.2.2p4-5, C++ [basic.link]p6). 5822 /// 5823 /// \param PrevDecl the previous declaration found by name 5824 /// lookup 5825 /// 5826 /// \param DC the context in which the new declaration is being 5827 /// declared. 5828 /// 5829 /// \returns true if PrevDecl is an out-of-scope previous declaration 5830 /// for a new delcaration with the same name. 5831 static bool 5832 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5833 ASTContext &Context) { 5834 if (!PrevDecl) 5835 return false; 5836 5837 if (!PrevDecl->hasLinkage()) 5838 return false; 5839 5840 if (Context.getLangOpts().CPlusPlus) { 5841 // C++ [basic.link]p6: 5842 // If there is a visible declaration of an entity with linkage 5843 // having the same name and type, ignoring entities declared 5844 // outside the innermost enclosing namespace scope, the block 5845 // scope declaration declares that same entity and receives the 5846 // linkage of the previous declaration. 5847 DeclContext *OuterContext = DC->getRedeclContext(); 5848 if (!OuterContext->isFunctionOrMethod()) 5849 // This rule only applies to block-scope declarations. 5850 return false; 5851 5852 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5853 if (PrevOuterContext->isRecord()) 5854 // We found a member function: ignore it. 5855 return false; 5856 5857 // Find the innermost enclosing namespace for the new and 5858 // previous declarations. 5859 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5860 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5861 5862 // The previous declaration is in a different namespace, so it 5863 // isn't the same function. 5864 if (!OuterContext->Equals(PrevOuterContext)) 5865 return false; 5866 } 5867 5868 return true; 5869 } 5870 5871 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 5872 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5873 if (!SS.isSet()) return; 5874 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 5875 } 5876 5877 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5878 QualType type = decl->getType(); 5879 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5880 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5881 // Various kinds of declaration aren't allowed to be __autoreleasing. 5882 unsigned kind = -1U; 5883 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5884 if (var->hasAttr<BlocksAttr>()) 5885 kind = 0; // __block 5886 else if (!var->hasLocalStorage()) 5887 kind = 1; // global 5888 } else if (isa<ObjCIvarDecl>(decl)) { 5889 kind = 3; // ivar 5890 } else if (isa<FieldDecl>(decl)) { 5891 kind = 2; // field 5892 } 5893 5894 if (kind != -1U) { 5895 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5896 << kind; 5897 } 5898 } else if (lifetime == Qualifiers::OCL_None) { 5899 // Try to infer lifetime. 5900 if (!type->isObjCLifetimeType()) 5901 return false; 5902 5903 lifetime = type->getObjCARCImplicitLifetime(); 5904 type = Context.getLifetimeQualifiedType(type, lifetime); 5905 decl->setType(type); 5906 } 5907 5908 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5909 // Thread-local variables cannot have lifetime. 5910 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5911 var->getTLSKind()) { 5912 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5913 << var->getType(); 5914 return true; 5915 } 5916 } 5917 5918 return false; 5919 } 5920 5921 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5922 // Ensure that an auto decl is deduced otherwise the checks below might cache 5923 // the wrong linkage. 5924 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5925 5926 // 'weak' only applies to declarations with external linkage. 5927 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5928 if (!ND.isExternallyVisible()) { 5929 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5930 ND.dropAttr<WeakAttr>(); 5931 } 5932 } 5933 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5934 if (ND.isExternallyVisible()) { 5935 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5936 ND.dropAttr<WeakRefAttr>(); 5937 ND.dropAttr<AliasAttr>(); 5938 } 5939 } 5940 5941 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5942 if (VD->hasInit()) { 5943 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5944 assert(VD->isThisDeclarationADefinition() && 5945 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5946 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5947 VD->dropAttr<AliasAttr>(); 5948 } 5949 } 5950 } 5951 5952 // 'selectany' only applies to externally visible variable declarations. 5953 // It does not apply to functions. 5954 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5955 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5956 S.Diag(Attr->getLocation(), 5957 diag::err_attribute_selectany_non_extern_data); 5958 ND.dropAttr<SelectAnyAttr>(); 5959 } 5960 } 5961 5962 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5963 // dll attributes require external linkage. Static locals may have external 5964 // linkage but still cannot be explicitly imported or exported. 5965 auto *VD = dyn_cast<VarDecl>(&ND); 5966 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5967 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5968 << &ND << Attr; 5969 ND.setInvalidDecl(); 5970 } 5971 } 5972 5973 // Virtual functions cannot be marked as 'notail'. 5974 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5975 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5976 if (MD->isVirtual()) { 5977 S.Diag(ND.getLocation(), 5978 diag::err_invalid_attribute_on_virtual_function) 5979 << Attr; 5980 ND.dropAttr<NotTailCalledAttr>(); 5981 } 5982 5983 // Check the attributes on the function type, if any. 5984 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 5985 // Don't declare this variable in the second operand of the for-statement; 5986 // GCC miscompiles that by ending its lifetime before evaluating the 5987 // third operand. See gcc.gnu.org/PR86769. 5988 AttributedTypeLoc ATL; 5989 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 5990 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 5991 TL = ATL.getModifiedLoc()) { 5992 // The [[lifetimebound]] attribute can be applied to the implicit object 5993 // parameter of a non-static member function (other than a ctor or dtor) 5994 // by applying it to the function type. 5995 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 5996 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 5997 if (!MD || MD->isStatic()) { 5998 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 5999 << !MD << A->getRange(); 6000 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6001 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6002 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6003 } 6004 } 6005 } 6006 } 6007 } 6008 6009 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6010 NamedDecl *NewDecl, 6011 bool IsSpecialization, 6012 bool IsDefinition) { 6013 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6014 return; 6015 6016 bool IsTemplate = false; 6017 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6018 OldDecl = OldTD->getTemplatedDecl(); 6019 IsTemplate = true; 6020 if (!IsSpecialization) 6021 IsDefinition = false; 6022 } 6023 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6024 NewDecl = NewTD->getTemplatedDecl(); 6025 IsTemplate = true; 6026 } 6027 6028 if (!OldDecl || !NewDecl) 6029 return; 6030 6031 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6032 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6033 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6034 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6035 6036 // dllimport and dllexport are inheritable attributes so we have to exclude 6037 // inherited attribute instances. 6038 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6039 (NewExportAttr && !NewExportAttr->isInherited()); 6040 6041 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6042 // the only exception being explicit specializations. 6043 // Implicitly generated declarations are also excluded for now because there 6044 // is no other way to switch these to use dllimport or dllexport. 6045 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6046 6047 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6048 // Allow with a warning for free functions and global variables. 6049 bool JustWarn = false; 6050 if (!OldDecl->isCXXClassMember()) { 6051 auto *VD = dyn_cast<VarDecl>(OldDecl); 6052 if (VD && !VD->getDescribedVarTemplate()) 6053 JustWarn = true; 6054 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6055 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6056 JustWarn = true; 6057 } 6058 6059 // We cannot change a declaration that's been used because IR has already 6060 // been emitted. Dllimported functions will still work though (modulo 6061 // address equality) as they can use the thunk. 6062 if (OldDecl->isUsed()) 6063 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6064 JustWarn = false; 6065 6066 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6067 : diag::err_attribute_dll_redeclaration; 6068 S.Diag(NewDecl->getLocation(), DiagID) 6069 << NewDecl 6070 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6071 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6072 if (!JustWarn) { 6073 NewDecl->setInvalidDecl(); 6074 return; 6075 } 6076 } 6077 6078 // A redeclaration is not allowed to drop a dllimport attribute, the only 6079 // exceptions being inline function definitions (except for function 6080 // templates), local extern declarations, qualified friend declarations or 6081 // special MSVC extension: in the last case, the declaration is treated as if 6082 // it were marked dllexport. 6083 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6084 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6085 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6086 // Ignore static data because out-of-line definitions are diagnosed 6087 // separately. 6088 IsStaticDataMember = VD->isStaticDataMember(); 6089 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6090 VarDecl::DeclarationOnly; 6091 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6092 IsInline = FD->isInlined(); 6093 IsQualifiedFriend = FD->getQualifier() && 6094 FD->getFriendObjectKind() == Decl::FOK_Declared; 6095 } 6096 6097 if (OldImportAttr && !HasNewAttr && 6098 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6099 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6100 if (IsMicrosoft && IsDefinition) { 6101 S.Diag(NewDecl->getLocation(), 6102 diag::warn_redeclaration_without_import_attribute) 6103 << NewDecl; 6104 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6105 NewDecl->dropAttr<DLLImportAttr>(); 6106 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6107 NewImportAttr->getRange(), S.Context, 6108 NewImportAttr->getSpellingListIndex())); 6109 } else { 6110 S.Diag(NewDecl->getLocation(), 6111 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6112 << NewDecl << OldImportAttr; 6113 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6114 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6115 OldDecl->dropAttr<DLLImportAttr>(); 6116 NewDecl->dropAttr<DLLImportAttr>(); 6117 } 6118 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6119 // In MinGW, seeing a function declared inline drops the dllimport 6120 // attribute. 6121 OldDecl->dropAttr<DLLImportAttr>(); 6122 NewDecl->dropAttr<DLLImportAttr>(); 6123 S.Diag(NewDecl->getLocation(), 6124 diag::warn_dllimport_dropped_from_inline_function) 6125 << NewDecl << OldImportAttr; 6126 } 6127 6128 // A specialization of a class template member function is processed here 6129 // since it's a redeclaration. If the parent class is dllexport, the 6130 // specialization inherits that attribute. This doesn't happen automatically 6131 // since the parent class isn't instantiated until later. 6132 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6133 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6134 !NewImportAttr && !NewExportAttr) { 6135 if (const DLLExportAttr *ParentExportAttr = 6136 MD->getParent()->getAttr<DLLExportAttr>()) { 6137 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6138 NewAttr->setInherited(true); 6139 NewDecl->addAttr(NewAttr); 6140 } 6141 } 6142 } 6143 } 6144 6145 /// Given that we are within the definition of the given function, 6146 /// will that definition behave like C99's 'inline', where the 6147 /// definition is discarded except for optimization purposes? 6148 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6149 // Try to avoid calling GetGVALinkageForFunction. 6150 6151 // All cases of this require the 'inline' keyword. 6152 if (!FD->isInlined()) return false; 6153 6154 // This is only possible in C++ with the gnu_inline attribute. 6155 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6156 return false; 6157 6158 // Okay, go ahead and call the relatively-more-expensive function. 6159 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6160 } 6161 6162 /// Determine whether a variable is extern "C" prior to attaching 6163 /// an initializer. We can't just call isExternC() here, because that 6164 /// will also compute and cache whether the declaration is externally 6165 /// visible, which might change when we attach the initializer. 6166 /// 6167 /// This can only be used if the declaration is known to not be a 6168 /// redeclaration of an internal linkage declaration. 6169 /// 6170 /// For instance: 6171 /// 6172 /// auto x = []{}; 6173 /// 6174 /// Attaching the initializer here makes this declaration not externally 6175 /// visible, because its type has internal linkage. 6176 /// 6177 /// FIXME: This is a hack. 6178 template<typename T> 6179 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6180 if (S.getLangOpts().CPlusPlus) { 6181 // In C++, the overloadable attribute negates the effects of extern "C". 6182 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6183 return false; 6184 6185 // So do CUDA's host/device attributes. 6186 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6187 D->template hasAttr<CUDAHostAttr>())) 6188 return false; 6189 } 6190 return D->isExternC(); 6191 } 6192 6193 static bool shouldConsiderLinkage(const VarDecl *VD) { 6194 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6195 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6196 return VD->hasExternalStorage(); 6197 if (DC->isFileContext()) 6198 return true; 6199 if (DC->isRecord()) 6200 return false; 6201 llvm_unreachable("Unexpected context"); 6202 } 6203 6204 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6205 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6206 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6207 isa<OMPDeclareReductionDecl>(DC)) 6208 return true; 6209 if (DC->isRecord()) 6210 return false; 6211 llvm_unreachable("Unexpected context"); 6212 } 6213 6214 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6215 ParsedAttr::Kind Kind) { 6216 // Check decl attributes on the DeclSpec. 6217 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6218 return true; 6219 6220 // Walk the declarator structure, checking decl attributes that were in a type 6221 // position to the decl itself. 6222 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6223 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6224 return true; 6225 } 6226 6227 // Finally, check attributes on the decl itself. 6228 return PD.getAttributes().hasAttribute(Kind); 6229 } 6230 6231 /// Adjust the \c DeclContext for a function or variable that might be a 6232 /// function-local external declaration. 6233 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6234 if (!DC->isFunctionOrMethod()) 6235 return false; 6236 6237 // If this is a local extern function or variable declared within a function 6238 // template, don't add it into the enclosing namespace scope until it is 6239 // instantiated; it might have a dependent type right now. 6240 if (DC->isDependentContext()) 6241 return true; 6242 6243 // C++11 [basic.link]p7: 6244 // When a block scope declaration of an entity with linkage is not found to 6245 // refer to some other declaration, then that entity is a member of the 6246 // innermost enclosing namespace. 6247 // 6248 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6249 // semantically-enclosing namespace, not a lexically-enclosing one. 6250 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6251 DC = DC->getParent(); 6252 return true; 6253 } 6254 6255 /// Returns true if given declaration has external C language linkage. 6256 static bool isDeclExternC(const Decl *D) { 6257 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6258 return FD->isExternC(); 6259 if (const auto *VD = dyn_cast<VarDecl>(D)) 6260 return VD->isExternC(); 6261 6262 llvm_unreachable("Unknown type of decl!"); 6263 } 6264 6265 NamedDecl *Sema::ActOnVariableDeclarator( 6266 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6267 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6268 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6269 QualType R = TInfo->getType(); 6270 DeclarationName Name = GetNameForDeclarator(D).getName(); 6271 6272 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6273 6274 if (D.isDecompositionDeclarator()) { 6275 // Take the name of the first declarator as our name for diagnostic 6276 // purposes. 6277 auto &Decomp = D.getDecompositionDeclarator(); 6278 if (!Decomp.bindings().empty()) { 6279 II = Decomp.bindings()[0].Name; 6280 Name = II; 6281 } 6282 } else if (!II) { 6283 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6284 return nullptr; 6285 } 6286 6287 if (getLangOpts().OpenCL) { 6288 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6289 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6290 // argument. 6291 if (R->isImageType() || R->isPipeType()) { 6292 Diag(D.getIdentifierLoc(), 6293 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6294 << R; 6295 D.setInvalidType(); 6296 return nullptr; 6297 } 6298 6299 // OpenCL v1.2 s6.9.r: 6300 // The event type cannot be used to declare a program scope variable. 6301 // OpenCL v2.0 s6.9.q: 6302 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6303 if (NULL == S->getParent()) { 6304 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6305 Diag(D.getIdentifierLoc(), 6306 diag::err_invalid_type_for_program_scope_var) << R; 6307 D.setInvalidType(); 6308 return nullptr; 6309 } 6310 } 6311 6312 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6313 QualType NR = R; 6314 while (NR->isPointerType()) { 6315 if (NR->isFunctionPointerType()) { 6316 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6317 D.setInvalidType(); 6318 break; 6319 } 6320 NR = NR->getPointeeType(); 6321 } 6322 6323 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6324 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6325 // half array type (unless the cl_khr_fp16 extension is enabled). 6326 if (Context.getBaseElementType(R)->isHalfType()) { 6327 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6328 D.setInvalidType(); 6329 } 6330 } 6331 6332 if (R->isSamplerT()) { 6333 // OpenCL v1.2 s6.9.b p4: 6334 // The sampler type cannot be used with the __local and __global address 6335 // space qualifiers. 6336 if (R.getAddressSpace() == LangAS::opencl_local || 6337 R.getAddressSpace() == LangAS::opencl_global) { 6338 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6339 } 6340 6341 // OpenCL v1.2 s6.12.14.1: 6342 // A global sampler must be declared with either the constant address 6343 // space qualifier or with the const qualifier. 6344 if (DC->isTranslationUnit() && 6345 !(R.getAddressSpace() == LangAS::opencl_constant || 6346 R.isConstQualified())) { 6347 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6348 D.setInvalidType(); 6349 } 6350 } 6351 6352 // OpenCL v1.2 s6.9.r: 6353 // The event type cannot be used with the __local, __constant and __global 6354 // address space qualifiers. 6355 if (R->isEventT()) { 6356 if (R.getAddressSpace() != LangAS::opencl_private) { 6357 Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6358 D.setInvalidType(); 6359 } 6360 } 6361 6362 // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not 6363 // supported. OpenCL C does not support thread_local either, and 6364 // also reject all other thread storage class specifiers. 6365 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6366 if (TSC != TSCS_unspecified) { 6367 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6368 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6369 diag::err_opencl_unknown_type_specifier) 6370 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6371 << DeclSpec::getSpecifierName(TSC) << 1; 6372 D.setInvalidType(); 6373 return nullptr; 6374 } 6375 } 6376 6377 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6378 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6379 6380 // dllimport globals without explicit storage class are treated as extern. We 6381 // have to change the storage class this early to get the right DeclContext. 6382 if (SC == SC_None && !DC->isRecord() && 6383 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6384 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6385 SC = SC_Extern; 6386 6387 DeclContext *OriginalDC = DC; 6388 bool IsLocalExternDecl = SC == SC_Extern && 6389 adjustContextForLocalExternDecl(DC); 6390 6391 if (SCSpec == DeclSpec::SCS_mutable) { 6392 // mutable can only appear on non-static class members, so it's always 6393 // an error here 6394 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6395 D.setInvalidType(); 6396 SC = SC_None; 6397 } 6398 6399 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6400 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6401 D.getDeclSpec().getStorageClassSpecLoc())) { 6402 // In C++11, the 'register' storage class specifier is deprecated. 6403 // Suppress the warning in system macros, it's used in macros in some 6404 // popular C system headers, such as in glibc's htonl() macro. 6405 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6406 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6407 : diag::warn_deprecated_register) 6408 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6409 } 6410 6411 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6412 6413 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6414 // C99 6.9p2: The storage-class specifiers auto and register shall not 6415 // appear in the declaration specifiers in an external declaration. 6416 // Global Register+Asm is a GNU extension we support. 6417 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6418 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6419 D.setInvalidType(); 6420 } 6421 } 6422 6423 bool IsMemberSpecialization = false; 6424 bool IsVariableTemplateSpecialization = false; 6425 bool IsPartialSpecialization = false; 6426 bool IsVariableTemplate = false; 6427 VarDecl *NewVD = nullptr; 6428 VarTemplateDecl *NewTemplate = nullptr; 6429 TemplateParameterList *TemplateParams = nullptr; 6430 if (!getLangOpts().CPlusPlus) { 6431 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6432 II, R, TInfo, SC); 6433 6434 if (R->getContainedDeducedType()) 6435 ParsingInitForAutoVars.insert(NewVD); 6436 6437 if (D.isInvalidType()) 6438 NewVD->setInvalidDecl(); 6439 } else { 6440 bool Invalid = false; 6441 6442 if (DC->isRecord() && !CurContext->isRecord()) { 6443 // This is an out-of-line definition of a static data member. 6444 switch (SC) { 6445 case SC_None: 6446 break; 6447 case SC_Static: 6448 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6449 diag::err_static_out_of_line) 6450 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6451 break; 6452 case SC_Auto: 6453 case SC_Register: 6454 case SC_Extern: 6455 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6456 // to names of variables declared in a block or to function parameters. 6457 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6458 // of class members 6459 6460 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6461 diag::err_storage_class_for_static_member) 6462 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6463 break; 6464 case SC_PrivateExtern: 6465 llvm_unreachable("C storage class in c++!"); 6466 } 6467 } 6468 6469 if (SC == SC_Static && CurContext->isRecord()) { 6470 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6471 if (RD->isLocalClass()) 6472 Diag(D.getIdentifierLoc(), 6473 diag::err_static_data_member_not_allowed_in_local_class) 6474 << Name << RD->getDeclName(); 6475 6476 // C++98 [class.union]p1: If a union contains a static data member, 6477 // the program is ill-formed. C++11 drops this restriction. 6478 if (RD->isUnion()) 6479 Diag(D.getIdentifierLoc(), 6480 getLangOpts().CPlusPlus11 6481 ? diag::warn_cxx98_compat_static_data_member_in_union 6482 : diag::ext_static_data_member_in_union) << Name; 6483 // We conservatively disallow static data members in anonymous structs. 6484 else if (!RD->getDeclName()) 6485 Diag(D.getIdentifierLoc(), 6486 diag::err_static_data_member_not_allowed_in_anon_struct) 6487 << Name << RD->isUnion(); 6488 } 6489 } 6490 6491 // Match up the template parameter lists with the scope specifier, then 6492 // determine whether we have a template or a template specialization. 6493 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6494 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6495 D.getCXXScopeSpec(), 6496 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6497 ? D.getName().TemplateId 6498 : nullptr, 6499 TemplateParamLists, 6500 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6501 6502 if (TemplateParams) { 6503 if (!TemplateParams->size() && 6504 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6505 // There is an extraneous 'template<>' for this variable. Complain 6506 // about it, but allow the declaration of the variable. 6507 Diag(TemplateParams->getTemplateLoc(), 6508 diag::err_template_variable_noparams) 6509 << II 6510 << SourceRange(TemplateParams->getTemplateLoc(), 6511 TemplateParams->getRAngleLoc()); 6512 TemplateParams = nullptr; 6513 } else { 6514 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6515 // This is an explicit specialization or a partial specialization. 6516 // FIXME: Check that we can declare a specialization here. 6517 IsVariableTemplateSpecialization = true; 6518 IsPartialSpecialization = TemplateParams->size() > 0; 6519 } else { // if (TemplateParams->size() > 0) 6520 // This is a template declaration. 6521 IsVariableTemplate = true; 6522 6523 // Check that we can declare a template here. 6524 if (CheckTemplateDeclScope(S, TemplateParams)) 6525 return nullptr; 6526 6527 // Only C++1y supports variable templates (N3651). 6528 Diag(D.getIdentifierLoc(), 6529 getLangOpts().CPlusPlus14 6530 ? diag::warn_cxx11_compat_variable_template 6531 : diag::ext_variable_template); 6532 } 6533 } 6534 } else { 6535 assert((Invalid || 6536 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6537 "should have a 'template<>' for this decl"); 6538 } 6539 6540 if (IsVariableTemplateSpecialization) { 6541 SourceLocation TemplateKWLoc = 6542 TemplateParamLists.size() > 0 6543 ? TemplateParamLists[0]->getTemplateLoc() 6544 : SourceLocation(); 6545 DeclResult Res = ActOnVarTemplateSpecialization( 6546 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6547 IsPartialSpecialization); 6548 if (Res.isInvalid()) 6549 return nullptr; 6550 NewVD = cast<VarDecl>(Res.get()); 6551 AddToScope = false; 6552 } else if (D.isDecompositionDeclarator()) { 6553 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6554 D.getIdentifierLoc(), R, TInfo, SC, 6555 Bindings); 6556 } else 6557 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6558 D.getIdentifierLoc(), II, R, TInfo, SC); 6559 6560 // If this is supposed to be a variable template, create it as such. 6561 if (IsVariableTemplate) { 6562 NewTemplate = 6563 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6564 TemplateParams, NewVD); 6565 NewVD->setDescribedVarTemplate(NewTemplate); 6566 } 6567 6568 // If this decl has an auto type in need of deduction, make a note of the 6569 // Decl so we can diagnose uses of it in its own initializer. 6570 if (R->getContainedDeducedType()) 6571 ParsingInitForAutoVars.insert(NewVD); 6572 6573 if (D.isInvalidType() || Invalid) { 6574 NewVD->setInvalidDecl(); 6575 if (NewTemplate) 6576 NewTemplate->setInvalidDecl(); 6577 } 6578 6579 SetNestedNameSpecifier(*this, NewVD, D); 6580 6581 // If we have any template parameter lists that don't directly belong to 6582 // the variable (matching the scope specifier), store them. 6583 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6584 if (TemplateParamLists.size() > VDTemplateParamLists) 6585 NewVD->setTemplateParameterListsInfo( 6586 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6587 6588 if (D.getDeclSpec().isConstexprSpecified()) { 6589 NewVD->setConstexpr(true); 6590 // C++1z [dcl.spec.constexpr]p1: 6591 // A static data member declared with the constexpr specifier is 6592 // implicitly an inline variable. 6593 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6594 NewVD->setImplicitlyInline(); 6595 } 6596 } 6597 6598 if (D.getDeclSpec().isInlineSpecified()) { 6599 if (!getLangOpts().CPlusPlus) { 6600 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6601 << 0; 6602 } else if (CurContext->isFunctionOrMethod()) { 6603 // 'inline' is not allowed on block scope variable declaration. 6604 Diag(D.getDeclSpec().getInlineSpecLoc(), 6605 diag::err_inline_declaration_block_scope) << Name 6606 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6607 } else { 6608 Diag(D.getDeclSpec().getInlineSpecLoc(), 6609 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6610 : diag::ext_inline_variable); 6611 NewVD->setInlineSpecified(); 6612 } 6613 } 6614 6615 // Set the lexical context. If the declarator has a C++ scope specifier, the 6616 // lexical context will be different from the semantic context. 6617 NewVD->setLexicalDeclContext(CurContext); 6618 if (NewTemplate) 6619 NewTemplate->setLexicalDeclContext(CurContext); 6620 6621 if (IsLocalExternDecl) { 6622 if (D.isDecompositionDeclarator()) 6623 for (auto *B : Bindings) 6624 B->setLocalExternDecl(); 6625 else 6626 NewVD->setLocalExternDecl(); 6627 } 6628 6629 bool EmitTLSUnsupportedError = false; 6630 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6631 // C++11 [dcl.stc]p4: 6632 // When thread_local is applied to a variable of block scope the 6633 // storage-class-specifier static is implied if it does not appear 6634 // explicitly. 6635 // Core issue: 'static' is not implied if the variable is declared 6636 // 'extern'. 6637 if (NewVD->hasLocalStorage() && 6638 (SCSpec != DeclSpec::SCS_unspecified || 6639 TSCS != DeclSpec::TSCS_thread_local || 6640 !DC->isFunctionOrMethod())) 6641 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6642 diag::err_thread_non_global) 6643 << DeclSpec::getSpecifierName(TSCS); 6644 else if (!Context.getTargetInfo().isTLSSupported()) { 6645 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6646 // Postpone error emission until we've collected attributes required to 6647 // figure out whether it's a host or device variable and whether the 6648 // error should be ignored. 6649 EmitTLSUnsupportedError = true; 6650 // We still need to mark the variable as TLS so it shows up in AST with 6651 // proper storage class for other tools to use even if we're not going 6652 // to emit any code for it. 6653 NewVD->setTSCSpec(TSCS); 6654 } else 6655 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6656 diag::err_thread_unsupported); 6657 } else 6658 NewVD->setTSCSpec(TSCS); 6659 } 6660 6661 // C99 6.7.4p3 6662 // An inline definition of a function with external linkage shall 6663 // not contain a definition of a modifiable object with static or 6664 // thread storage duration... 6665 // We only apply this when the function is required to be defined 6666 // elsewhere, i.e. when the function is not 'extern inline'. Note 6667 // that a local variable with thread storage duration still has to 6668 // be marked 'static'. Also note that it's possible to get these 6669 // semantics in C++ using __attribute__((gnu_inline)). 6670 if (SC == SC_Static && S->getFnParent() != nullptr && 6671 !NewVD->getType().isConstQualified()) { 6672 FunctionDecl *CurFD = getCurFunctionDecl(); 6673 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6674 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6675 diag::warn_static_local_in_extern_inline); 6676 MaybeSuggestAddingStaticToDecl(CurFD); 6677 } 6678 } 6679 6680 if (D.getDeclSpec().isModulePrivateSpecified()) { 6681 if (IsVariableTemplateSpecialization) 6682 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6683 << (IsPartialSpecialization ? 1 : 0) 6684 << FixItHint::CreateRemoval( 6685 D.getDeclSpec().getModulePrivateSpecLoc()); 6686 else if (IsMemberSpecialization) 6687 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6688 << 2 6689 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6690 else if (NewVD->hasLocalStorage()) 6691 Diag(NewVD->getLocation(), diag::err_module_private_local) 6692 << 0 << NewVD->getDeclName() 6693 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6694 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6695 else { 6696 NewVD->setModulePrivate(); 6697 if (NewTemplate) 6698 NewTemplate->setModulePrivate(); 6699 for (auto *B : Bindings) 6700 B->setModulePrivate(); 6701 } 6702 } 6703 6704 // Handle attributes prior to checking for duplicates in MergeVarDecl 6705 ProcessDeclAttributes(S, NewVD, D); 6706 6707 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6708 if (EmitTLSUnsupportedError && 6709 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6710 (getLangOpts().OpenMPIsDevice && 6711 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6712 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6713 diag::err_thread_unsupported); 6714 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6715 // storage [duration]." 6716 if (SC == SC_None && S->getFnParent() != nullptr && 6717 (NewVD->hasAttr<CUDASharedAttr>() || 6718 NewVD->hasAttr<CUDAConstantAttr>())) { 6719 NewVD->setStorageClass(SC_Static); 6720 } 6721 } 6722 6723 // Ensure that dllimport globals without explicit storage class are treated as 6724 // extern. The storage class is set above using parsed attributes. Now we can 6725 // check the VarDecl itself. 6726 assert(!NewVD->hasAttr<DLLImportAttr>() || 6727 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6728 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6729 6730 // In auto-retain/release, infer strong retension for variables of 6731 // retainable type. 6732 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6733 NewVD->setInvalidDecl(); 6734 6735 // Handle GNU asm-label extension (encoded as an attribute). 6736 if (Expr *E = (Expr*)D.getAsmLabel()) { 6737 // The parser guarantees this is a string. 6738 StringLiteral *SE = cast<StringLiteral>(E); 6739 StringRef Label = SE->getString(); 6740 if (S->getFnParent() != nullptr) { 6741 switch (SC) { 6742 case SC_None: 6743 case SC_Auto: 6744 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6745 break; 6746 case SC_Register: 6747 // Local Named register 6748 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6749 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6750 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6751 break; 6752 case SC_Static: 6753 case SC_Extern: 6754 case SC_PrivateExtern: 6755 break; 6756 } 6757 } else if (SC == SC_Register) { 6758 // Global Named register 6759 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6760 const auto &TI = Context.getTargetInfo(); 6761 bool HasSizeMismatch; 6762 6763 if (!TI.isValidGCCRegisterName(Label)) 6764 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6765 else if (!TI.validateGlobalRegisterVariable(Label, 6766 Context.getTypeSize(R), 6767 HasSizeMismatch)) 6768 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6769 else if (HasSizeMismatch) 6770 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6771 } 6772 6773 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6774 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 6775 NewVD->setInvalidDecl(true); 6776 } 6777 } 6778 6779 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6780 Context, Label, 0)); 6781 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6782 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6783 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6784 if (I != ExtnameUndeclaredIdentifiers.end()) { 6785 if (isDeclExternC(NewVD)) { 6786 NewVD->addAttr(I->second); 6787 ExtnameUndeclaredIdentifiers.erase(I); 6788 } else 6789 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6790 << /*Variable*/1 << NewVD; 6791 } 6792 } 6793 6794 // Find the shadowed declaration before filtering for scope. 6795 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6796 ? getShadowedDeclaration(NewVD, Previous) 6797 : nullptr; 6798 6799 // Don't consider existing declarations that are in a different 6800 // scope and are out-of-semantic-context declarations (if the new 6801 // declaration has linkage). 6802 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6803 D.getCXXScopeSpec().isNotEmpty() || 6804 IsMemberSpecialization || 6805 IsVariableTemplateSpecialization); 6806 6807 // Check whether the previous declaration is in the same block scope. This 6808 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6809 if (getLangOpts().CPlusPlus && 6810 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6811 NewVD->setPreviousDeclInSameBlockScope( 6812 Previous.isSingleResult() && !Previous.isShadowed() && 6813 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6814 6815 if (!getLangOpts().CPlusPlus) { 6816 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6817 } else { 6818 // If this is an explicit specialization of a static data member, check it. 6819 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6820 CheckMemberSpecialization(NewVD, Previous)) 6821 NewVD->setInvalidDecl(); 6822 6823 // Merge the decl with the existing one if appropriate. 6824 if (!Previous.empty()) { 6825 if (Previous.isSingleResult() && 6826 isa<FieldDecl>(Previous.getFoundDecl()) && 6827 D.getCXXScopeSpec().isSet()) { 6828 // The user tried to define a non-static data member 6829 // out-of-line (C++ [dcl.meaning]p1). 6830 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6831 << D.getCXXScopeSpec().getRange(); 6832 Previous.clear(); 6833 NewVD->setInvalidDecl(); 6834 } 6835 } else if (D.getCXXScopeSpec().isSet()) { 6836 // No previous declaration in the qualifying scope. 6837 Diag(D.getIdentifierLoc(), diag::err_no_member) 6838 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6839 << D.getCXXScopeSpec().getRange(); 6840 NewVD->setInvalidDecl(); 6841 } 6842 6843 if (!IsVariableTemplateSpecialization) 6844 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6845 6846 if (NewTemplate) { 6847 VarTemplateDecl *PrevVarTemplate = 6848 NewVD->getPreviousDecl() 6849 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6850 : nullptr; 6851 6852 // Check the template parameter list of this declaration, possibly 6853 // merging in the template parameter list from the previous variable 6854 // template declaration. 6855 if (CheckTemplateParameterList( 6856 TemplateParams, 6857 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6858 : nullptr, 6859 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6860 DC->isDependentContext()) 6861 ? TPC_ClassTemplateMember 6862 : TPC_VarTemplate)) 6863 NewVD->setInvalidDecl(); 6864 6865 // If we are providing an explicit specialization of a static variable 6866 // template, make a note of that. 6867 if (PrevVarTemplate && 6868 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6869 PrevVarTemplate->setMemberSpecialization(); 6870 } 6871 } 6872 6873 // Diagnose shadowed variables iff this isn't a redeclaration. 6874 if (ShadowedDecl && !D.isRedeclaration()) 6875 CheckShadow(NewVD, ShadowedDecl, Previous); 6876 6877 ProcessPragmaWeak(S, NewVD); 6878 6879 // If this is the first declaration of an extern C variable, update 6880 // the map of such variables. 6881 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6882 isIncompleteDeclExternC(*this, NewVD)) 6883 RegisterLocallyScopedExternCDecl(NewVD, S); 6884 6885 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6886 Decl *ManglingContextDecl; 6887 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6888 NewVD->getDeclContext(), ManglingContextDecl)) { 6889 Context.setManglingNumber( 6890 NewVD, MCtx->getManglingNumber( 6891 NewVD, getMSManglingNumber(getLangOpts(), S))); 6892 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6893 } 6894 } 6895 6896 // Special handling of variable named 'main'. 6897 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6898 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6899 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6900 6901 // C++ [basic.start.main]p3 6902 // A program that declares a variable main at global scope is ill-formed. 6903 if (getLangOpts().CPlusPlus) 6904 Diag(D.getBeginLoc(), diag::err_main_global_variable); 6905 6906 // In C, and external-linkage variable named main results in undefined 6907 // behavior. 6908 else if (NewVD->hasExternalFormalLinkage()) 6909 Diag(D.getBeginLoc(), diag::warn_main_redefined); 6910 } 6911 6912 if (D.isRedeclaration() && !Previous.empty()) { 6913 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6914 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6915 D.isFunctionDefinition()); 6916 } 6917 6918 if (NewTemplate) { 6919 if (NewVD->isInvalidDecl()) 6920 NewTemplate->setInvalidDecl(); 6921 ActOnDocumentableDecl(NewTemplate); 6922 return NewTemplate; 6923 } 6924 6925 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6926 CompleteMemberSpecialization(NewVD, Previous); 6927 6928 return NewVD; 6929 } 6930 6931 /// Enum describing the %select options in diag::warn_decl_shadow. 6932 enum ShadowedDeclKind { 6933 SDK_Local, 6934 SDK_Global, 6935 SDK_StaticMember, 6936 SDK_Field, 6937 SDK_Typedef, 6938 SDK_Using 6939 }; 6940 6941 /// Determine what kind of declaration we're shadowing. 6942 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6943 const DeclContext *OldDC) { 6944 if (isa<TypeAliasDecl>(ShadowedDecl)) 6945 return SDK_Using; 6946 else if (isa<TypedefDecl>(ShadowedDecl)) 6947 return SDK_Typedef; 6948 else if (isa<RecordDecl>(OldDC)) 6949 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6950 6951 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6952 } 6953 6954 /// Return the location of the capture if the given lambda captures the given 6955 /// variable \p VD, or an invalid source location otherwise. 6956 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6957 const VarDecl *VD) { 6958 for (const Capture &Capture : LSI->Captures) { 6959 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6960 return Capture.getLocation(); 6961 } 6962 return SourceLocation(); 6963 } 6964 6965 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6966 const LookupResult &R) { 6967 // Only diagnose if we're shadowing an unambiguous field or variable. 6968 if (R.getResultKind() != LookupResult::Found) 6969 return false; 6970 6971 // Return false if warning is ignored. 6972 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6973 } 6974 6975 /// Return the declaration shadowed by the given variable \p D, or null 6976 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6977 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6978 const LookupResult &R) { 6979 if (!shouldWarnIfShadowedDecl(Diags, R)) 6980 return nullptr; 6981 6982 // Don't diagnose declarations at file scope. 6983 if (D->hasGlobalStorage()) 6984 return nullptr; 6985 6986 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6987 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6988 ? ShadowedDecl 6989 : nullptr; 6990 } 6991 6992 /// Return the declaration shadowed by the given typedef \p D, or null 6993 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6994 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6995 const LookupResult &R) { 6996 // Don't warn if typedef declaration is part of a class 6997 if (D->getDeclContext()->isRecord()) 6998 return nullptr; 6999 7000 if (!shouldWarnIfShadowedDecl(Diags, R)) 7001 return nullptr; 7002 7003 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7004 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7005 } 7006 7007 /// Diagnose variable or built-in function shadowing. Implements 7008 /// -Wshadow. 7009 /// 7010 /// This method is called whenever a VarDecl is added to a "useful" 7011 /// scope. 7012 /// 7013 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7014 /// \param R the lookup of the name 7015 /// 7016 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7017 const LookupResult &R) { 7018 DeclContext *NewDC = D->getDeclContext(); 7019 7020 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7021 // Fields are not shadowed by variables in C++ static methods. 7022 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7023 if (MD->isStatic()) 7024 return; 7025 7026 // Fields shadowed by constructor parameters are a special case. Usually 7027 // the constructor initializes the field with the parameter. 7028 if (isa<CXXConstructorDecl>(NewDC)) 7029 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7030 // Remember that this was shadowed so we can either warn about its 7031 // modification or its existence depending on warning settings. 7032 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7033 return; 7034 } 7035 } 7036 7037 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7038 if (shadowedVar->isExternC()) { 7039 // For shadowing external vars, make sure that we point to the global 7040 // declaration, not a locally scoped extern declaration. 7041 for (auto I : shadowedVar->redecls()) 7042 if (I->isFileVarDecl()) { 7043 ShadowedDecl = I; 7044 break; 7045 } 7046 } 7047 7048 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7049 7050 unsigned WarningDiag = diag::warn_decl_shadow; 7051 SourceLocation CaptureLoc; 7052 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7053 isa<CXXMethodDecl>(NewDC)) { 7054 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7055 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7056 if (RD->getLambdaCaptureDefault() == LCD_None) { 7057 // Try to avoid warnings for lambdas with an explicit capture list. 7058 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7059 // Warn only when the lambda captures the shadowed decl explicitly. 7060 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7061 if (CaptureLoc.isInvalid()) 7062 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7063 } else { 7064 // Remember that this was shadowed so we can avoid the warning if the 7065 // shadowed decl isn't captured and the warning settings allow it. 7066 cast<LambdaScopeInfo>(getCurFunction()) 7067 ->ShadowingDecls.push_back( 7068 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7069 return; 7070 } 7071 } 7072 7073 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7074 // A variable can't shadow a local variable in an enclosing scope, if 7075 // they are separated by a non-capturing declaration context. 7076 for (DeclContext *ParentDC = NewDC; 7077 ParentDC && !ParentDC->Equals(OldDC); 7078 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7079 // Only block literals, captured statements, and lambda expressions 7080 // can capture; other scopes don't. 7081 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7082 !isLambdaCallOperator(ParentDC)) { 7083 return; 7084 } 7085 } 7086 } 7087 } 7088 } 7089 7090 // Only warn about certain kinds of shadowing for class members. 7091 if (NewDC && NewDC->isRecord()) { 7092 // In particular, don't warn about shadowing non-class members. 7093 if (!OldDC->isRecord()) 7094 return; 7095 7096 // TODO: should we warn about static data members shadowing 7097 // static data members from base classes? 7098 7099 // TODO: don't diagnose for inaccessible shadowed members. 7100 // This is hard to do perfectly because we might friend the 7101 // shadowing context, but that's just a false negative. 7102 } 7103 7104 7105 DeclarationName Name = R.getLookupName(); 7106 7107 // Emit warning and note. 7108 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7109 return; 7110 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7111 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7112 if (!CaptureLoc.isInvalid()) 7113 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7114 << Name << /*explicitly*/ 1; 7115 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7116 } 7117 7118 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7119 /// when these variables are captured by the lambda. 7120 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7121 for (const auto &Shadow : LSI->ShadowingDecls) { 7122 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7123 // Try to avoid the warning when the shadowed decl isn't captured. 7124 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7125 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7126 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7127 ? diag::warn_decl_shadow_uncaptured_local 7128 : diag::warn_decl_shadow) 7129 << Shadow.VD->getDeclName() 7130 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7131 if (!CaptureLoc.isInvalid()) 7132 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7133 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7134 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7135 } 7136 } 7137 7138 /// Check -Wshadow without the advantage of a previous lookup. 7139 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7140 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7141 return; 7142 7143 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7144 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7145 LookupName(R, S); 7146 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7147 CheckShadow(D, ShadowedDecl, R); 7148 } 7149 7150 /// Check if 'E', which is an expression that is about to be modified, refers 7151 /// to a constructor parameter that shadows a field. 7152 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7153 // Quickly ignore expressions that can't be shadowing ctor parameters. 7154 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7155 return; 7156 E = E->IgnoreParenImpCasts(); 7157 auto *DRE = dyn_cast<DeclRefExpr>(E); 7158 if (!DRE) 7159 return; 7160 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7161 auto I = ShadowingDecls.find(D); 7162 if (I == ShadowingDecls.end()) 7163 return; 7164 const NamedDecl *ShadowedDecl = I->second; 7165 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7166 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7167 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7168 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7169 7170 // Avoid issuing multiple warnings about the same decl. 7171 ShadowingDecls.erase(I); 7172 } 7173 7174 /// Check for conflict between this global or extern "C" declaration and 7175 /// previous global or extern "C" declarations. This is only used in C++. 7176 template<typename T> 7177 static bool checkGlobalOrExternCConflict( 7178 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7179 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7180 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7181 7182 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7183 // The common case: this global doesn't conflict with any extern "C" 7184 // declaration. 7185 return false; 7186 } 7187 7188 if (Prev) { 7189 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7190 // Both the old and new declarations have C language linkage. This is a 7191 // redeclaration. 7192 Previous.clear(); 7193 Previous.addDecl(Prev); 7194 return true; 7195 } 7196 7197 // This is a global, non-extern "C" declaration, and there is a previous 7198 // non-global extern "C" declaration. Diagnose if this is a variable 7199 // declaration. 7200 if (!isa<VarDecl>(ND)) 7201 return false; 7202 } else { 7203 // The declaration is extern "C". Check for any declaration in the 7204 // translation unit which might conflict. 7205 if (IsGlobal) { 7206 // We have already performed the lookup into the translation unit. 7207 IsGlobal = false; 7208 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7209 I != E; ++I) { 7210 if (isa<VarDecl>(*I)) { 7211 Prev = *I; 7212 break; 7213 } 7214 } 7215 } else { 7216 DeclContext::lookup_result R = 7217 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7218 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7219 I != E; ++I) { 7220 if (isa<VarDecl>(*I)) { 7221 Prev = *I; 7222 break; 7223 } 7224 // FIXME: If we have any other entity with this name in global scope, 7225 // the declaration is ill-formed, but that is a defect: it breaks the 7226 // 'stat' hack, for instance. Only variables can have mangled name 7227 // clashes with extern "C" declarations, so only they deserve a 7228 // diagnostic. 7229 } 7230 } 7231 7232 if (!Prev) 7233 return false; 7234 } 7235 7236 // Use the first declaration's location to ensure we point at something which 7237 // is lexically inside an extern "C" linkage-spec. 7238 assert(Prev && "should have found a previous declaration to diagnose"); 7239 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7240 Prev = FD->getFirstDecl(); 7241 else 7242 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7243 7244 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7245 << IsGlobal << ND; 7246 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7247 << IsGlobal; 7248 return false; 7249 } 7250 7251 /// Apply special rules for handling extern "C" declarations. Returns \c true 7252 /// if we have found that this is a redeclaration of some prior entity. 7253 /// 7254 /// Per C++ [dcl.link]p6: 7255 /// Two declarations [for a function or variable] with C language linkage 7256 /// with the same name that appear in different scopes refer to the same 7257 /// [entity]. An entity with C language linkage shall not be declared with 7258 /// the same name as an entity in global scope. 7259 template<typename T> 7260 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7261 LookupResult &Previous) { 7262 if (!S.getLangOpts().CPlusPlus) { 7263 // In C, when declaring a global variable, look for a corresponding 'extern' 7264 // variable declared in function scope. We don't need this in C++, because 7265 // we find local extern decls in the surrounding file-scope DeclContext. 7266 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7267 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7268 Previous.clear(); 7269 Previous.addDecl(Prev); 7270 return true; 7271 } 7272 } 7273 return false; 7274 } 7275 7276 // A declaration in the translation unit can conflict with an extern "C" 7277 // declaration. 7278 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7279 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7280 7281 // An extern "C" declaration can conflict with a declaration in the 7282 // translation unit or can be a redeclaration of an extern "C" declaration 7283 // in another scope. 7284 if (isIncompleteDeclExternC(S,ND)) 7285 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7286 7287 // Neither global nor extern "C": nothing to do. 7288 return false; 7289 } 7290 7291 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7292 // If the decl is already known invalid, don't check it. 7293 if (NewVD->isInvalidDecl()) 7294 return; 7295 7296 QualType T = NewVD->getType(); 7297 7298 // Defer checking an 'auto' type until its initializer is attached. 7299 if (T->isUndeducedType()) 7300 return; 7301 7302 if (NewVD->hasAttrs()) 7303 CheckAlignasUnderalignment(NewVD); 7304 7305 if (T->isObjCObjectType()) { 7306 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7307 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7308 T = Context.getObjCObjectPointerType(T); 7309 NewVD->setType(T); 7310 } 7311 7312 // Emit an error if an address space was applied to decl with local storage. 7313 // This includes arrays of objects with address space qualifiers, but not 7314 // automatic variables that point to other address spaces. 7315 // ISO/IEC TR 18037 S5.1.2 7316 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7317 T.getAddressSpace() != LangAS::Default) { 7318 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7319 NewVD->setInvalidDecl(); 7320 return; 7321 } 7322 7323 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7324 // scope. 7325 if (getLangOpts().OpenCLVersion == 120 && 7326 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7327 NewVD->isStaticLocal()) { 7328 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7329 NewVD->setInvalidDecl(); 7330 return; 7331 } 7332 7333 if (getLangOpts().OpenCL) { 7334 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7335 if (NewVD->hasAttr<BlocksAttr>()) { 7336 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7337 return; 7338 } 7339 7340 if (T->isBlockPointerType()) { 7341 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7342 // can't use 'extern' storage class. 7343 if (!T.isConstQualified()) { 7344 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7345 << 0 /*const*/; 7346 NewVD->setInvalidDecl(); 7347 return; 7348 } 7349 if (NewVD->hasExternalStorage()) { 7350 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7351 NewVD->setInvalidDecl(); 7352 return; 7353 } 7354 } 7355 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7356 // __constant address space. 7357 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7358 // variables inside a function can also be declared in the global 7359 // address space. 7360 // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local 7361 // address space additionally. 7362 // FIXME: Add local AS for OpenCL C++. 7363 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7364 NewVD->hasExternalStorage()) { 7365 if (!T->isSamplerT() && 7366 !(T.getAddressSpace() == LangAS::opencl_constant || 7367 (T.getAddressSpace() == LangAS::opencl_global && 7368 (getLangOpts().OpenCLVersion == 200 || 7369 getLangOpts().OpenCLCPlusPlus)))) { 7370 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7371 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7372 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7373 << Scope << "global or constant"; 7374 else 7375 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7376 << Scope << "constant"; 7377 NewVD->setInvalidDecl(); 7378 return; 7379 } 7380 } else { 7381 if (T.getAddressSpace() == LangAS::opencl_global) { 7382 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7383 << 1 /*is any function*/ << "global"; 7384 NewVD->setInvalidDecl(); 7385 return; 7386 } 7387 if (T.getAddressSpace() == LangAS::opencl_constant || 7388 T.getAddressSpace() == LangAS::opencl_local) { 7389 FunctionDecl *FD = getCurFunctionDecl(); 7390 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7391 // in functions. 7392 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7393 if (T.getAddressSpace() == LangAS::opencl_constant) 7394 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7395 << 0 /*non-kernel only*/ << "constant"; 7396 else 7397 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7398 << 0 /*non-kernel only*/ << "local"; 7399 NewVD->setInvalidDecl(); 7400 return; 7401 } 7402 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7403 // in the outermost scope of a kernel function. 7404 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7405 if (!getCurScope()->isFunctionScope()) { 7406 if (T.getAddressSpace() == LangAS::opencl_constant) 7407 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7408 << "constant"; 7409 else 7410 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7411 << "local"; 7412 NewVD->setInvalidDecl(); 7413 return; 7414 } 7415 } 7416 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7417 // Do not allow other address spaces on automatic variable. 7418 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7419 NewVD->setInvalidDecl(); 7420 return; 7421 } 7422 } 7423 } 7424 7425 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7426 && !NewVD->hasAttr<BlocksAttr>()) { 7427 if (getLangOpts().getGC() != LangOptions::NonGC) 7428 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7429 else { 7430 assert(!getLangOpts().ObjCAutoRefCount); 7431 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7432 } 7433 } 7434 7435 bool isVM = T->isVariablyModifiedType(); 7436 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7437 NewVD->hasAttr<BlocksAttr>()) 7438 setFunctionHasBranchProtectedScope(); 7439 7440 if ((isVM && NewVD->hasLinkage()) || 7441 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7442 bool SizeIsNegative; 7443 llvm::APSInt Oversized; 7444 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7445 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7446 QualType FixedT; 7447 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7448 FixedT = FixedTInfo->getType(); 7449 else if (FixedTInfo) { 7450 // Type and type-as-written are canonically different. We need to fix up 7451 // both types separately. 7452 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7453 Oversized); 7454 } 7455 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7456 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7457 // FIXME: This won't give the correct result for 7458 // int a[10][n]; 7459 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7460 7461 if (NewVD->isFileVarDecl()) 7462 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7463 << SizeRange; 7464 else if (NewVD->isStaticLocal()) 7465 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7466 << SizeRange; 7467 else 7468 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7469 << SizeRange; 7470 NewVD->setInvalidDecl(); 7471 return; 7472 } 7473 7474 if (!FixedTInfo) { 7475 if (NewVD->isFileVarDecl()) 7476 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7477 else 7478 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7479 NewVD->setInvalidDecl(); 7480 return; 7481 } 7482 7483 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7484 NewVD->setType(FixedT); 7485 NewVD->setTypeSourceInfo(FixedTInfo); 7486 } 7487 7488 if (T->isVoidType()) { 7489 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7490 // of objects and functions. 7491 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7492 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7493 << T; 7494 NewVD->setInvalidDecl(); 7495 return; 7496 } 7497 } 7498 7499 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7500 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7501 NewVD->setInvalidDecl(); 7502 return; 7503 } 7504 7505 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7506 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7507 NewVD->setInvalidDecl(); 7508 return; 7509 } 7510 7511 if (NewVD->isConstexpr() && !T->isDependentType() && 7512 RequireLiteralType(NewVD->getLocation(), T, 7513 diag::err_constexpr_var_non_literal)) { 7514 NewVD->setInvalidDecl(); 7515 return; 7516 } 7517 } 7518 7519 /// Perform semantic checking on a newly-created variable 7520 /// declaration. 7521 /// 7522 /// This routine performs all of the type-checking required for a 7523 /// variable declaration once it has been built. It is used both to 7524 /// check variables after they have been parsed and their declarators 7525 /// have been translated into a declaration, and to check variables 7526 /// that have been instantiated from a template. 7527 /// 7528 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7529 /// 7530 /// Returns true if the variable declaration is a redeclaration. 7531 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7532 CheckVariableDeclarationType(NewVD); 7533 7534 // If the decl is already known invalid, don't check it. 7535 if (NewVD->isInvalidDecl()) 7536 return false; 7537 7538 // If we did not find anything by this name, look for a non-visible 7539 // extern "C" declaration with the same name. 7540 if (Previous.empty() && 7541 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7542 Previous.setShadowed(); 7543 7544 if (!Previous.empty()) { 7545 MergeVarDecl(NewVD, Previous); 7546 return true; 7547 } 7548 return false; 7549 } 7550 7551 namespace { 7552 struct FindOverriddenMethod { 7553 Sema *S; 7554 CXXMethodDecl *Method; 7555 7556 /// Member lookup function that determines whether a given C++ 7557 /// method overrides a method in a base class, to be used with 7558 /// CXXRecordDecl::lookupInBases(). 7559 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7560 RecordDecl *BaseRecord = 7561 Specifier->getType()->getAs<RecordType>()->getDecl(); 7562 7563 DeclarationName Name = Method->getDeclName(); 7564 7565 // FIXME: Do we care about other names here too? 7566 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7567 // We really want to find the base class destructor here. 7568 QualType T = S->Context.getTypeDeclType(BaseRecord); 7569 CanQualType CT = S->Context.getCanonicalType(T); 7570 7571 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7572 } 7573 7574 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7575 Path.Decls = Path.Decls.slice(1)) { 7576 NamedDecl *D = Path.Decls.front(); 7577 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7578 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7579 return true; 7580 } 7581 } 7582 7583 return false; 7584 } 7585 }; 7586 7587 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7588 } // end anonymous namespace 7589 7590 /// Report an error regarding overriding, along with any relevant 7591 /// overridden methods. 7592 /// 7593 /// \param DiagID the primary error to report. 7594 /// \param MD the overriding method. 7595 /// \param OEK which overrides to include as notes. 7596 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7597 OverrideErrorKind OEK = OEK_All) { 7598 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7599 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7600 // This check (& the OEK parameter) could be replaced by a predicate, but 7601 // without lambdas that would be overkill. This is still nicer than writing 7602 // out the diag loop 3 times. 7603 if ((OEK == OEK_All) || 7604 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7605 (OEK == OEK_Deleted && O->isDeleted())) 7606 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7607 } 7608 } 7609 7610 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7611 /// and if so, check that it's a valid override and remember it. 7612 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7613 // Look for methods in base classes that this method might override. 7614 CXXBasePaths Paths; 7615 FindOverriddenMethod FOM; 7616 FOM.Method = MD; 7617 FOM.S = this; 7618 bool hasDeletedOverridenMethods = false; 7619 bool hasNonDeletedOverridenMethods = false; 7620 bool AddedAny = false; 7621 if (DC->lookupInBases(FOM, Paths)) { 7622 for (auto *I : Paths.found_decls()) { 7623 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7624 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7625 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7626 !CheckOverridingFunctionAttributes(MD, OldMD) && 7627 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7628 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7629 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7630 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7631 AddedAny = true; 7632 } 7633 } 7634 } 7635 } 7636 7637 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7638 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7639 } 7640 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7641 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7642 } 7643 7644 return AddedAny; 7645 } 7646 7647 namespace { 7648 // Struct for holding all of the extra arguments needed by 7649 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7650 struct ActOnFDArgs { 7651 Scope *S; 7652 Declarator &D; 7653 MultiTemplateParamsArg TemplateParamLists; 7654 bool AddToScope; 7655 }; 7656 } // end anonymous namespace 7657 7658 namespace { 7659 7660 // Callback to only accept typo corrections that have a non-zero edit distance. 7661 // Also only accept corrections that have the same parent decl. 7662 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7663 public: 7664 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7665 CXXRecordDecl *Parent) 7666 : Context(Context), OriginalFD(TypoFD), 7667 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7668 7669 bool ValidateCandidate(const TypoCorrection &candidate) override { 7670 if (candidate.getEditDistance() == 0) 7671 return false; 7672 7673 SmallVector<unsigned, 1> MismatchedParams; 7674 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7675 CDeclEnd = candidate.end(); 7676 CDecl != CDeclEnd; ++CDecl) { 7677 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7678 7679 if (FD && !FD->hasBody() && 7680 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7681 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7682 CXXRecordDecl *Parent = MD->getParent(); 7683 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7684 return true; 7685 } else if (!ExpectedParent) { 7686 return true; 7687 } 7688 } 7689 } 7690 7691 return false; 7692 } 7693 7694 private: 7695 ASTContext &Context; 7696 FunctionDecl *OriginalFD; 7697 CXXRecordDecl *ExpectedParent; 7698 }; 7699 7700 } // end anonymous namespace 7701 7702 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7703 TypoCorrectedFunctionDefinitions.insert(F); 7704 } 7705 7706 /// Generate diagnostics for an invalid function redeclaration. 7707 /// 7708 /// This routine handles generating the diagnostic messages for an invalid 7709 /// function redeclaration, including finding possible similar declarations 7710 /// or performing typo correction if there are no previous declarations with 7711 /// the same name. 7712 /// 7713 /// Returns a NamedDecl iff typo correction was performed and substituting in 7714 /// the new declaration name does not cause new errors. 7715 static NamedDecl *DiagnoseInvalidRedeclaration( 7716 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7717 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7718 DeclarationName Name = NewFD->getDeclName(); 7719 DeclContext *NewDC = NewFD->getDeclContext(); 7720 SmallVector<unsigned, 1> MismatchedParams; 7721 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7722 TypoCorrection Correction; 7723 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7724 unsigned DiagMsg = 7725 IsLocalFriend ? diag::err_no_matching_local_friend : 7726 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 7727 diag::err_member_decl_does_not_match; 7728 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7729 IsLocalFriend ? Sema::LookupLocalFriendName 7730 : Sema::LookupOrdinaryName, 7731 Sema::ForVisibleRedeclaration); 7732 7733 NewFD->setInvalidDecl(); 7734 if (IsLocalFriend) 7735 SemaRef.LookupName(Prev, S); 7736 else 7737 SemaRef.LookupQualifiedName(Prev, NewDC); 7738 assert(!Prev.isAmbiguous() && 7739 "Cannot have an ambiguity in previous-declaration lookup"); 7740 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7741 if (!Prev.empty()) { 7742 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7743 Func != FuncEnd; ++Func) { 7744 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7745 if (FD && 7746 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7747 // Add 1 to the index so that 0 can mean the mismatch didn't 7748 // involve a parameter 7749 unsigned ParamNum = 7750 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7751 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7752 } 7753 } 7754 // If the qualified name lookup yielded nothing, try typo correction 7755 } else if ((Correction = SemaRef.CorrectTypo( 7756 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7757 &ExtraArgs.D.getCXXScopeSpec(), 7758 llvm::make_unique<DifferentNameValidatorCCC>( 7759 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7760 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7761 // Set up everything for the call to ActOnFunctionDeclarator 7762 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7763 ExtraArgs.D.getIdentifierLoc()); 7764 Previous.clear(); 7765 Previous.setLookupName(Correction.getCorrection()); 7766 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7767 CDeclEnd = Correction.end(); 7768 CDecl != CDeclEnd; ++CDecl) { 7769 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7770 if (FD && !FD->hasBody() && 7771 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7772 Previous.addDecl(FD); 7773 } 7774 } 7775 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7776 7777 NamedDecl *Result; 7778 // Retry building the function declaration with the new previous 7779 // declarations, and with errors suppressed. 7780 { 7781 // Trap errors. 7782 Sema::SFINAETrap Trap(SemaRef); 7783 7784 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7785 // pieces need to verify the typo-corrected C++ declaration and hopefully 7786 // eliminate the need for the parameter pack ExtraArgs. 7787 Result = SemaRef.ActOnFunctionDeclarator( 7788 ExtraArgs.S, ExtraArgs.D, 7789 Correction.getCorrectionDecl()->getDeclContext(), 7790 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7791 ExtraArgs.AddToScope); 7792 7793 if (Trap.hasErrorOccurred()) 7794 Result = nullptr; 7795 } 7796 7797 if (Result) { 7798 // Determine which correction we picked. 7799 Decl *Canonical = Result->getCanonicalDecl(); 7800 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7801 I != E; ++I) 7802 if ((*I)->getCanonicalDecl() == Canonical) 7803 Correction.setCorrectionDecl(*I); 7804 7805 // Let Sema know about the correction. 7806 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7807 SemaRef.diagnoseTypo( 7808 Correction, 7809 SemaRef.PDiag(IsLocalFriend 7810 ? diag::err_no_matching_local_friend_suggest 7811 : diag::err_member_decl_does_not_match_suggest) 7812 << Name << NewDC << IsDefinition); 7813 return Result; 7814 } 7815 7816 // Pretend the typo correction never occurred 7817 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7818 ExtraArgs.D.getIdentifierLoc()); 7819 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7820 Previous.clear(); 7821 Previous.setLookupName(Name); 7822 } 7823 7824 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7825 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7826 7827 bool NewFDisConst = false; 7828 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7829 NewFDisConst = NewMD->isConst(); 7830 7831 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7832 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7833 NearMatch != NearMatchEnd; ++NearMatch) { 7834 FunctionDecl *FD = NearMatch->first; 7835 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7836 bool FDisConst = MD && MD->isConst(); 7837 bool IsMember = MD || !IsLocalFriend; 7838 7839 // FIXME: These notes are poorly worded for the local friend case. 7840 if (unsigned Idx = NearMatch->second) { 7841 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7842 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7843 if (Loc.isInvalid()) Loc = FD->getLocation(); 7844 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7845 : diag::note_local_decl_close_param_match) 7846 << Idx << FDParam->getType() 7847 << NewFD->getParamDecl(Idx - 1)->getType(); 7848 } else if (FDisConst != NewFDisConst) { 7849 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7850 << NewFDisConst << FD->getSourceRange().getEnd(); 7851 } else 7852 SemaRef.Diag(FD->getLocation(), 7853 IsMember ? diag::note_member_def_close_match 7854 : diag::note_local_decl_close_match); 7855 } 7856 return nullptr; 7857 } 7858 7859 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7860 switch (D.getDeclSpec().getStorageClassSpec()) { 7861 default: llvm_unreachable("Unknown storage class!"); 7862 case DeclSpec::SCS_auto: 7863 case DeclSpec::SCS_register: 7864 case DeclSpec::SCS_mutable: 7865 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7866 diag::err_typecheck_sclass_func); 7867 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7868 D.setInvalidType(); 7869 break; 7870 case DeclSpec::SCS_unspecified: break; 7871 case DeclSpec::SCS_extern: 7872 if (D.getDeclSpec().isExternInLinkageSpec()) 7873 return SC_None; 7874 return SC_Extern; 7875 case DeclSpec::SCS_static: { 7876 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7877 // C99 6.7.1p5: 7878 // The declaration of an identifier for a function that has 7879 // block scope shall have no explicit storage-class specifier 7880 // other than extern 7881 // See also (C++ [dcl.stc]p4). 7882 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7883 diag::err_static_block_func); 7884 break; 7885 } else 7886 return SC_Static; 7887 } 7888 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7889 } 7890 7891 // No explicit storage class has already been returned 7892 return SC_None; 7893 } 7894 7895 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7896 DeclContext *DC, QualType &R, 7897 TypeSourceInfo *TInfo, 7898 StorageClass SC, 7899 bool &IsVirtualOkay) { 7900 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7901 DeclarationName Name = NameInfo.getName(); 7902 7903 FunctionDecl *NewFD = nullptr; 7904 bool isInline = D.getDeclSpec().isInlineSpecified(); 7905 7906 if (!SemaRef.getLangOpts().CPlusPlus) { 7907 // Determine whether the function was written with a 7908 // prototype. This true when: 7909 // - there is a prototype in the declarator, or 7910 // - the type R of the function is some kind of typedef or other non- 7911 // attributed reference to a type name (which eventually refers to a 7912 // function type). 7913 bool HasPrototype = 7914 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7915 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7916 7917 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 7918 R, TInfo, SC, isInline, HasPrototype, false); 7919 if (D.isInvalidType()) 7920 NewFD->setInvalidDecl(); 7921 7922 return NewFD; 7923 } 7924 7925 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7926 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7927 7928 // Check that the return type is not an abstract class type. 7929 // For record types, this is done by the AbstractClassUsageDiagnoser once 7930 // the class has been completely parsed. 7931 if (!DC->isRecord() && 7932 SemaRef.RequireNonAbstractType( 7933 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7934 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7935 D.setInvalidType(); 7936 7937 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7938 // This is a C++ constructor declaration. 7939 assert(DC->isRecord() && 7940 "Constructors can only be declared in a member context"); 7941 7942 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7943 return CXXConstructorDecl::Create( 7944 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 7945 TInfo, isExplicit, isInline, 7946 /*isImplicitlyDeclared=*/false, isConstexpr); 7947 7948 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7949 // This is a C++ destructor declaration. 7950 if (DC->isRecord()) { 7951 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7952 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7953 CXXDestructorDecl *NewDD = 7954 CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(), 7955 NameInfo, R, TInfo, isInline, 7956 /*isImplicitlyDeclared=*/false); 7957 7958 // If the destructor needs an implicit exception specification, set it 7959 // now. FIXME: It'd be nice to be able to create the right type to start 7960 // with, but the type needs to reference the destructor declaration. 7961 if (SemaRef.getLangOpts().CPlusPlus11) 7962 SemaRef.AdjustDestructorExceptionSpec(NewDD); 7963 7964 IsVirtualOkay = true; 7965 return NewDD; 7966 7967 } else { 7968 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7969 D.setInvalidType(); 7970 7971 // Create a FunctionDecl to satisfy the function definition parsing 7972 // code path. 7973 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 7974 D.getIdentifierLoc(), Name, R, TInfo, SC, 7975 isInline, 7976 /*hasPrototype=*/true, isConstexpr); 7977 } 7978 7979 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7980 if (!DC->isRecord()) { 7981 SemaRef.Diag(D.getIdentifierLoc(), 7982 diag::err_conv_function_not_member); 7983 return nullptr; 7984 } 7985 7986 SemaRef.CheckConversionDeclarator(D, R, SC); 7987 IsVirtualOkay = true; 7988 return CXXConversionDecl::Create( 7989 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 7990 TInfo, isInline, isExplicit, isConstexpr, SourceLocation()); 7991 7992 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7993 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7994 7995 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 7996 isExplicit, NameInfo, R, TInfo, 7997 D.getEndLoc()); 7998 } else if (DC->isRecord()) { 7999 // If the name of the function is the same as the name of the record, 8000 // then this must be an invalid constructor that has a return type. 8001 // (The parser checks for a return type and makes the declarator a 8002 // constructor if it has no return type). 8003 if (Name.getAsIdentifierInfo() && 8004 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8005 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8006 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8007 << SourceRange(D.getIdentifierLoc()); 8008 return nullptr; 8009 } 8010 8011 // This is a C++ method declaration. 8012 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8013 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8014 TInfo, SC, isInline, isConstexpr, SourceLocation()); 8015 IsVirtualOkay = !Ret->isStatic(); 8016 return Ret; 8017 } else { 8018 bool isFriend = 8019 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8020 if (!isFriend && SemaRef.CurContext->isRecord()) 8021 return nullptr; 8022 8023 // Determine whether the function was written with a 8024 // prototype. This true when: 8025 // - we're in C++ (where every function has a prototype), 8026 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8027 R, TInfo, SC, isInline, true /*HasPrototype*/, 8028 isConstexpr); 8029 } 8030 } 8031 8032 enum OpenCLParamType { 8033 ValidKernelParam, 8034 PtrPtrKernelParam, 8035 PtrKernelParam, 8036 InvalidAddrSpacePtrKernelParam, 8037 InvalidKernelParam, 8038 RecordKernelParam 8039 }; 8040 8041 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8042 // Size dependent types are just typedefs to normal integer types 8043 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8044 // integers other than by their names. 8045 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8046 8047 // Remove typedefs one by one until we reach a typedef 8048 // for a size dependent type. 8049 QualType DesugaredTy = Ty; 8050 do { 8051 ArrayRef<StringRef> Names(SizeTypeNames); 8052 auto Match = 8053 std::find(Names.begin(), Names.end(), DesugaredTy.getAsString()); 8054 if (Names.end() != Match) 8055 return true; 8056 8057 Ty = DesugaredTy; 8058 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8059 } while (DesugaredTy != Ty); 8060 8061 return false; 8062 } 8063 8064 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8065 if (PT->isPointerType()) { 8066 QualType PointeeType = PT->getPointeeType(); 8067 if (PointeeType->isPointerType()) 8068 return PtrPtrKernelParam; 8069 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8070 PointeeType.getAddressSpace() == LangAS::opencl_private || 8071 PointeeType.getAddressSpace() == LangAS::Default) 8072 return InvalidAddrSpacePtrKernelParam; 8073 return PtrKernelParam; 8074 } 8075 8076 // OpenCL v1.2 s6.9.k: 8077 // Arguments to kernel functions in a program cannot be declared with the 8078 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8079 // uintptr_t or a struct and/or union that contain fields declared to be one 8080 // of these built-in scalar types. 8081 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8082 return InvalidKernelParam; 8083 8084 if (PT->isImageType()) 8085 return PtrKernelParam; 8086 8087 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8088 return InvalidKernelParam; 8089 8090 // OpenCL extension spec v1.2 s9.5: 8091 // This extension adds support for half scalar and vector types as built-in 8092 // types that can be used for arithmetic operations, conversions etc. 8093 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8094 return InvalidKernelParam; 8095 8096 if (PT->isRecordType()) 8097 return RecordKernelParam; 8098 8099 // Look into an array argument to check if it has a forbidden type. 8100 if (PT->isArrayType()) { 8101 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8102 // Call ourself to check an underlying type of an array. Since the 8103 // getPointeeOrArrayElementType returns an innermost type which is not an 8104 // array, this recursive call only happens once. 8105 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8106 } 8107 8108 return ValidKernelParam; 8109 } 8110 8111 static void checkIsValidOpenCLKernelParameter( 8112 Sema &S, 8113 Declarator &D, 8114 ParmVarDecl *Param, 8115 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8116 QualType PT = Param->getType(); 8117 8118 // Cache the valid types we encounter to avoid rechecking structs that are 8119 // used again 8120 if (ValidTypes.count(PT.getTypePtr())) 8121 return; 8122 8123 switch (getOpenCLKernelParameterType(S, PT)) { 8124 case PtrPtrKernelParam: 8125 // OpenCL v1.2 s6.9.a: 8126 // A kernel function argument cannot be declared as a 8127 // pointer to a pointer type. 8128 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8129 D.setInvalidType(); 8130 return; 8131 8132 case InvalidAddrSpacePtrKernelParam: 8133 // OpenCL v1.0 s6.5: 8134 // __kernel function arguments declared to be a pointer of a type can point 8135 // to one of the following address spaces only : __global, __local or 8136 // __constant. 8137 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8138 D.setInvalidType(); 8139 return; 8140 8141 // OpenCL v1.2 s6.9.k: 8142 // Arguments to kernel functions in a program cannot be declared with the 8143 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8144 // uintptr_t or a struct and/or union that contain fields declared to be 8145 // one of these built-in scalar types. 8146 8147 case InvalidKernelParam: 8148 // OpenCL v1.2 s6.8 n: 8149 // A kernel function argument cannot be declared 8150 // of event_t type. 8151 // Do not diagnose half type since it is diagnosed as invalid argument 8152 // type for any function elsewhere. 8153 if (!PT->isHalfType()) { 8154 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8155 8156 // Explain what typedefs are involved. 8157 const TypedefType *Typedef = nullptr; 8158 while ((Typedef = PT->getAs<TypedefType>())) { 8159 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8160 // SourceLocation may be invalid for a built-in type. 8161 if (Loc.isValid()) 8162 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8163 PT = Typedef->desugar(); 8164 } 8165 } 8166 8167 D.setInvalidType(); 8168 return; 8169 8170 case PtrKernelParam: 8171 case ValidKernelParam: 8172 ValidTypes.insert(PT.getTypePtr()); 8173 return; 8174 8175 case RecordKernelParam: 8176 break; 8177 } 8178 8179 // Track nested structs we will inspect 8180 SmallVector<const Decl *, 4> VisitStack; 8181 8182 // Track where we are in the nested structs. Items will migrate from 8183 // VisitStack to HistoryStack as we do the DFS for bad field. 8184 SmallVector<const FieldDecl *, 4> HistoryStack; 8185 HistoryStack.push_back(nullptr); 8186 8187 // At this point we already handled everything except of a RecordType or 8188 // an ArrayType of a RecordType. 8189 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8190 const RecordType *RecTy = 8191 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8192 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8193 8194 VisitStack.push_back(RecTy->getDecl()); 8195 assert(VisitStack.back() && "First decl null?"); 8196 8197 do { 8198 const Decl *Next = VisitStack.pop_back_val(); 8199 if (!Next) { 8200 assert(!HistoryStack.empty()); 8201 // Found a marker, we have gone up a level 8202 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8203 ValidTypes.insert(Hist->getType().getTypePtr()); 8204 8205 continue; 8206 } 8207 8208 // Adds everything except the original parameter declaration (which is not a 8209 // field itself) to the history stack. 8210 const RecordDecl *RD; 8211 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8212 HistoryStack.push_back(Field); 8213 8214 QualType FieldTy = Field->getType(); 8215 // Other field types (known to be valid or invalid) are handled while we 8216 // walk around RecordDecl::fields(). 8217 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8218 "Unexpected type."); 8219 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8220 8221 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8222 } else { 8223 RD = cast<RecordDecl>(Next); 8224 } 8225 8226 // Add a null marker so we know when we've gone back up a level 8227 VisitStack.push_back(nullptr); 8228 8229 for (const auto *FD : RD->fields()) { 8230 QualType QT = FD->getType(); 8231 8232 if (ValidTypes.count(QT.getTypePtr())) 8233 continue; 8234 8235 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8236 if (ParamType == ValidKernelParam) 8237 continue; 8238 8239 if (ParamType == RecordKernelParam) { 8240 VisitStack.push_back(FD); 8241 continue; 8242 } 8243 8244 // OpenCL v1.2 s6.9.p: 8245 // Arguments to kernel functions that are declared to be a struct or union 8246 // do not allow OpenCL objects to be passed as elements of the struct or 8247 // union. 8248 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8249 ParamType == InvalidAddrSpacePtrKernelParam) { 8250 S.Diag(Param->getLocation(), 8251 diag::err_record_with_pointers_kernel_param) 8252 << PT->isUnionType() 8253 << PT; 8254 } else { 8255 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8256 } 8257 8258 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8259 << OrigRecDecl->getDeclName(); 8260 8261 // We have an error, now let's go back up through history and show where 8262 // the offending field came from 8263 for (ArrayRef<const FieldDecl *>::const_iterator 8264 I = HistoryStack.begin() + 1, 8265 E = HistoryStack.end(); 8266 I != E; ++I) { 8267 const FieldDecl *OuterField = *I; 8268 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8269 << OuterField->getType(); 8270 } 8271 8272 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8273 << QT->isPointerType() 8274 << QT; 8275 D.setInvalidType(); 8276 return; 8277 } 8278 } while (!VisitStack.empty()); 8279 } 8280 8281 /// Find the DeclContext in which a tag is implicitly declared if we see an 8282 /// elaborated type specifier in the specified context, and lookup finds 8283 /// nothing. 8284 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8285 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8286 DC = DC->getParent(); 8287 return DC; 8288 } 8289 8290 /// Find the Scope in which a tag is implicitly declared if we see an 8291 /// elaborated type specifier in the specified context, and lookup finds 8292 /// nothing. 8293 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8294 while (S->isClassScope() || 8295 (LangOpts.CPlusPlus && 8296 S->isFunctionPrototypeScope()) || 8297 ((S->getFlags() & Scope::DeclScope) == 0) || 8298 (S->getEntity() && S->getEntity()->isTransparentContext())) 8299 S = S->getParent(); 8300 return S; 8301 } 8302 8303 NamedDecl* 8304 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8305 TypeSourceInfo *TInfo, LookupResult &Previous, 8306 MultiTemplateParamsArg TemplateParamLists, 8307 bool &AddToScope) { 8308 QualType R = TInfo->getType(); 8309 8310 assert(R->isFunctionType()); 8311 8312 // TODO: consider using NameInfo for diagnostic. 8313 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8314 DeclarationName Name = NameInfo.getName(); 8315 StorageClass SC = getFunctionStorageClass(*this, D); 8316 8317 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8318 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8319 diag::err_invalid_thread) 8320 << DeclSpec::getSpecifierName(TSCS); 8321 8322 if (D.isFirstDeclarationOfMember()) 8323 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8324 D.getIdentifierLoc()); 8325 8326 bool isFriend = false; 8327 FunctionTemplateDecl *FunctionTemplate = nullptr; 8328 bool isMemberSpecialization = false; 8329 bool isFunctionTemplateSpecialization = false; 8330 8331 bool isDependentClassScopeExplicitSpecialization = false; 8332 bool HasExplicitTemplateArgs = false; 8333 TemplateArgumentListInfo TemplateArgs; 8334 8335 bool isVirtualOkay = false; 8336 8337 DeclContext *OriginalDC = DC; 8338 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8339 8340 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8341 isVirtualOkay); 8342 if (!NewFD) return nullptr; 8343 8344 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8345 NewFD->setTopLevelDeclInObjCContainer(); 8346 8347 // Set the lexical context. If this is a function-scope declaration, or has a 8348 // C++ scope specifier, or is the object of a friend declaration, the lexical 8349 // context will be different from the semantic context. 8350 NewFD->setLexicalDeclContext(CurContext); 8351 8352 if (IsLocalExternDecl) 8353 NewFD->setLocalExternDecl(); 8354 8355 if (getLangOpts().CPlusPlus) { 8356 bool isInline = D.getDeclSpec().isInlineSpecified(); 8357 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8358 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8359 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8360 isFriend = D.getDeclSpec().isFriendSpecified(); 8361 if (isFriend && !isInline && D.isFunctionDefinition()) { 8362 // C++ [class.friend]p5 8363 // A function can be defined in a friend declaration of a 8364 // class . . . . Such a function is implicitly inline. 8365 NewFD->setImplicitlyInline(); 8366 } 8367 8368 // If this is a method defined in an __interface, and is not a constructor 8369 // or an overloaded operator, then set the pure flag (isVirtual will already 8370 // return true). 8371 if (const CXXRecordDecl *Parent = 8372 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8373 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8374 NewFD->setPure(true); 8375 8376 // C++ [class.union]p2 8377 // A union can have member functions, but not virtual functions. 8378 if (isVirtual && Parent->isUnion()) 8379 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8380 } 8381 8382 SetNestedNameSpecifier(*this, NewFD, D); 8383 isMemberSpecialization = false; 8384 isFunctionTemplateSpecialization = false; 8385 if (D.isInvalidType()) 8386 NewFD->setInvalidDecl(); 8387 8388 // Match up the template parameter lists with the scope specifier, then 8389 // determine whether we have a template or a template specialization. 8390 bool Invalid = false; 8391 if (TemplateParameterList *TemplateParams = 8392 MatchTemplateParametersToScopeSpecifier( 8393 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8394 D.getCXXScopeSpec(), 8395 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8396 ? D.getName().TemplateId 8397 : nullptr, 8398 TemplateParamLists, isFriend, isMemberSpecialization, 8399 Invalid)) { 8400 if (TemplateParams->size() > 0) { 8401 // This is a function template 8402 8403 // Check that we can declare a template here. 8404 if (CheckTemplateDeclScope(S, TemplateParams)) 8405 NewFD->setInvalidDecl(); 8406 8407 // A destructor cannot be a template. 8408 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8409 Diag(NewFD->getLocation(), diag::err_destructor_template); 8410 NewFD->setInvalidDecl(); 8411 } 8412 8413 // If we're adding a template to a dependent context, we may need to 8414 // rebuilding some of the types used within the template parameter list, 8415 // now that we know what the current instantiation is. 8416 if (DC->isDependentContext()) { 8417 ContextRAII SavedContext(*this, DC); 8418 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8419 Invalid = true; 8420 } 8421 8422 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8423 NewFD->getLocation(), 8424 Name, TemplateParams, 8425 NewFD); 8426 FunctionTemplate->setLexicalDeclContext(CurContext); 8427 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8428 8429 // For source fidelity, store the other template param lists. 8430 if (TemplateParamLists.size() > 1) { 8431 NewFD->setTemplateParameterListsInfo(Context, 8432 TemplateParamLists.drop_back(1)); 8433 } 8434 } else { 8435 // This is a function template specialization. 8436 isFunctionTemplateSpecialization = true; 8437 // For source fidelity, store all the template param lists. 8438 if (TemplateParamLists.size() > 0) 8439 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8440 8441 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8442 if (isFriend) { 8443 // We want to remove the "template<>", found here. 8444 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8445 8446 // If we remove the template<> and the name is not a 8447 // template-id, we're actually silently creating a problem: 8448 // the friend declaration will refer to an untemplated decl, 8449 // and clearly the user wants a template specialization. So 8450 // we need to insert '<>' after the name. 8451 SourceLocation InsertLoc; 8452 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8453 InsertLoc = D.getName().getSourceRange().getEnd(); 8454 InsertLoc = getLocForEndOfToken(InsertLoc); 8455 } 8456 8457 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8458 << Name << RemoveRange 8459 << FixItHint::CreateRemoval(RemoveRange) 8460 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8461 } 8462 } 8463 } else { 8464 // All template param lists were matched against the scope specifier: 8465 // this is NOT (an explicit specialization of) a template. 8466 if (TemplateParamLists.size() > 0) 8467 // For source fidelity, store all the template param lists. 8468 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8469 } 8470 8471 if (Invalid) { 8472 NewFD->setInvalidDecl(); 8473 if (FunctionTemplate) 8474 FunctionTemplate->setInvalidDecl(); 8475 } 8476 8477 // C++ [dcl.fct.spec]p5: 8478 // The virtual specifier shall only be used in declarations of 8479 // nonstatic class member functions that appear within a 8480 // member-specification of a class declaration; see 10.3. 8481 // 8482 if (isVirtual && !NewFD->isInvalidDecl()) { 8483 if (!isVirtualOkay) { 8484 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8485 diag::err_virtual_non_function); 8486 } else if (!CurContext->isRecord()) { 8487 // 'virtual' was specified outside of the class. 8488 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8489 diag::err_virtual_out_of_class) 8490 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8491 } else if (NewFD->getDescribedFunctionTemplate()) { 8492 // C++ [temp.mem]p3: 8493 // A member function template shall not be virtual. 8494 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8495 diag::err_virtual_member_function_template) 8496 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8497 } else { 8498 // Okay: Add virtual to the method. 8499 NewFD->setVirtualAsWritten(true); 8500 } 8501 8502 if (getLangOpts().CPlusPlus14 && 8503 NewFD->getReturnType()->isUndeducedType()) 8504 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8505 } 8506 8507 if (getLangOpts().CPlusPlus14 && 8508 (NewFD->isDependentContext() || 8509 (isFriend && CurContext->isDependentContext())) && 8510 NewFD->getReturnType()->isUndeducedType()) { 8511 // If the function template is referenced directly (for instance, as a 8512 // member of the current instantiation), pretend it has a dependent type. 8513 // This is not really justified by the standard, but is the only sane 8514 // thing to do. 8515 // FIXME: For a friend function, we have not marked the function as being 8516 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8517 const FunctionProtoType *FPT = 8518 NewFD->getType()->castAs<FunctionProtoType>(); 8519 QualType Result = 8520 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8521 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8522 FPT->getExtProtoInfo())); 8523 } 8524 8525 // C++ [dcl.fct.spec]p3: 8526 // The inline specifier shall not appear on a block scope function 8527 // declaration. 8528 if (isInline && !NewFD->isInvalidDecl()) { 8529 if (CurContext->isFunctionOrMethod()) { 8530 // 'inline' is not allowed on block scope function declaration. 8531 Diag(D.getDeclSpec().getInlineSpecLoc(), 8532 diag::err_inline_declaration_block_scope) << Name 8533 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8534 } 8535 } 8536 8537 // C++ [dcl.fct.spec]p6: 8538 // The explicit specifier shall be used only in the declaration of a 8539 // constructor or conversion function within its class definition; 8540 // see 12.3.1 and 12.3.2. 8541 if (isExplicit && !NewFD->isInvalidDecl() && 8542 !isa<CXXDeductionGuideDecl>(NewFD)) { 8543 if (!CurContext->isRecord()) { 8544 // 'explicit' was specified outside of the class. 8545 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8546 diag::err_explicit_out_of_class) 8547 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8548 } else if (!isa<CXXConstructorDecl>(NewFD) && 8549 !isa<CXXConversionDecl>(NewFD)) { 8550 // 'explicit' was specified on a function that wasn't a constructor 8551 // or conversion function. 8552 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8553 diag::err_explicit_non_ctor_or_conv_function) 8554 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8555 } 8556 } 8557 8558 if (isConstexpr) { 8559 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8560 // are implicitly inline. 8561 NewFD->setImplicitlyInline(); 8562 8563 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8564 // be either constructors or to return a literal type. Therefore, 8565 // destructors cannot be declared constexpr. 8566 if (isa<CXXDestructorDecl>(NewFD)) 8567 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8568 } 8569 8570 // If __module_private__ was specified, mark the function accordingly. 8571 if (D.getDeclSpec().isModulePrivateSpecified()) { 8572 if (isFunctionTemplateSpecialization) { 8573 SourceLocation ModulePrivateLoc 8574 = D.getDeclSpec().getModulePrivateSpecLoc(); 8575 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8576 << 0 8577 << FixItHint::CreateRemoval(ModulePrivateLoc); 8578 } else { 8579 NewFD->setModulePrivate(); 8580 if (FunctionTemplate) 8581 FunctionTemplate->setModulePrivate(); 8582 } 8583 } 8584 8585 if (isFriend) { 8586 if (FunctionTemplate) { 8587 FunctionTemplate->setObjectOfFriendDecl(); 8588 FunctionTemplate->setAccess(AS_public); 8589 } 8590 NewFD->setObjectOfFriendDecl(); 8591 NewFD->setAccess(AS_public); 8592 } 8593 8594 // If a function is defined as defaulted or deleted, mark it as such now. 8595 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8596 // definition kind to FDK_Definition. 8597 switch (D.getFunctionDefinitionKind()) { 8598 case FDK_Declaration: 8599 case FDK_Definition: 8600 break; 8601 8602 case FDK_Defaulted: 8603 NewFD->setDefaulted(); 8604 break; 8605 8606 case FDK_Deleted: 8607 NewFD->setDeletedAsWritten(); 8608 break; 8609 } 8610 8611 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8612 D.isFunctionDefinition()) { 8613 // C++ [class.mfct]p2: 8614 // A member function may be defined (8.4) in its class definition, in 8615 // which case it is an inline member function (7.1.2) 8616 NewFD->setImplicitlyInline(); 8617 } 8618 8619 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8620 !CurContext->isRecord()) { 8621 // C++ [class.static]p1: 8622 // A data or function member of a class may be declared static 8623 // in a class definition, in which case it is a static member of 8624 // the class. 8625 8626 // Complain about the 'static' specifier if it's on an out-of-line 8627 // member function definition. 8628 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8629 diag::err_static_out_of_line) 8630 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8631 } 8632 8633 // C++11 [except.spec]p15: 8634 // A deallocation function with no exception-specification is treated 8635 // as if it were specified with noexcept(true). 8636 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8637 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8638 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8639 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8640 NewFD->setType(Context.getFunctionType( 8641 FPT->getReturnType(), FPT->getParamTypes(), 8642 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8643 } 8644 8645 // Filter out previous declarations that don't match the scope. 8646 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8647 D.getCXXScopeSpec().isNotEmpty() || 8648 isMemberSpecialization || 8649 isFunctionTemplateSpecialization); 8650 8651 // Handle GNU asm-label extension (encoded as an attribute). 8652 if (Expr *E = (Expr*) D.getAsmLabel()) { 8653 // The parser guarantees this is a string. 8654 StringLiteral *SE = cast<StringLiteral>(E); 8655 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8656 SE->getString(), 0)); 8657 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8658 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8659 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8660 if (I != ExtnameUndeclaredIdentifiers.end()) { 8661 if (isDeclExternC(NewFD)) { 8662 NewFD->addAttr(I->second); 8663 ExtnameUndeclaredIdentifiers.erase(I); 8664 } else 8665 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8666 << /*Variable*/0 << NewFD; 8667 } 8668 } 8669 8670 // Copy the parameter declarations from the declarator D to the function 8671 // declaration NewFD, if they are available. First scavenge them into Params. 8672 SmallVector<ParmVarDecl*, 16> Params; 8673 unsigned FTIIdx; 8674 if (D.isFunctionDeclarator(FTIIdx)) { 8675 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8676 8677 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8678 // function that takes no arguments, not a function that takes a 8679 // single void argument. 8680 // We let through "const void" here because Sema::GetTypeForDeclarator 8681 // already checks for that case. 8682 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8683 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8684 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8685 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8686 Param->setDeclContext(NewFD); 8687 Params.push_back(Param); 8688 8689 if (Param->isInvalidDecl()) 8690 NewFD->setInvalidDecl(); 8691 } 8692 } 8693 8694 if (!getLangOpts().CPlusPlus) { 8695 // In C, find all the tag declarations from the prototype and move them 8696 // into the function DeclContext. Remove them from the surrounding tag 8697 // injection context of the function, which is typically but not always 8698 // the TU. 8699 DeclContext *PrototypeTagContext = 8700 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8701 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8702 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8703 8704 // We don't want to reparent enumerators. Look at their parent enum 8705 // instead. 8706 if (!TD) { 8707 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8708 TD = cast<EnumDecl>(ECD->getDeclContext()); 8709 } 8710 if (!TD) 8711 continue; 8712 DeclContext *TagDC = TD->getLexicalDeclContext(); 8713 if (!TagDC->containsDecl(TD)) 8714 continue; 8715 TagDC->removeDecl(TD); 8716 TD->setDeclContext(NewFD); 8717 NewFD->addDecl(TD); 8718 8719 // Preserve the lexical DeclContext if it is not the surrounding tag 8720 // injection context of the FD. In this example, the semantic context of 8721 // E will be f and the lexical context will be S, while both the 8722 // semantic and lexical contexts of S will be f: 8723 // void f(struct S { enum E { a } f; } s); 8724 if (TagDC != PrototypeTagContext) 8725 TD->setLexicalDeclContext(TagDC); 8726 } 8727 } 8728 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8729 // When we're declaring a function with a typedef, typeof, etc as in the 8730 // following example, we'll need to synthesize (unnamed) 8731 // parameters for use in the declaration. 8732 // 8733 // @code 8734 // typedef void fn(int); 8735 // fn f; 8736 // @endcode 8737 8738 // Synthesize a parameter for each argument type. 8739 for (const auto &AI : FT->param_types()) { 8740 ParmVarDecl *Param = 8741 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8742 Param->setScopeInfo(0, Params.size()); 8743 Params.push_back(Param); 8744 } 8745 } else { 8746 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8747 "Should not need args for typedef of non-prototype fn"); 8748 } 8749 8750 // Finally, we know we have the right number of parameters, install them. 8751 NewFD->setParams(Params); 8752 8753 if (D.getDeclSpec().isNoreturnSpecified()) 8754 NewFD->addAttr( 8755 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8756 Context, 0)); 8757 8758 // Functions returning a variably modified type violate C99 6.7.5.2p2 8759 // because all functions have linkage. 8760 if (!NewFD->isInvalidDecl() && 8761 NewFD->getReturnType()->isVariablyModifiedType()) { 8762 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8763 NewFD->setInvalidDecl(); 8764 } 8765 8766 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8767 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8768 !NewFD->hasAttr<SectionAttr>()) { 8769 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8770 PragmaClangTextSection.SectionName, 8771 PragmaClangTextSection.PragmaLocation)); 8772 } 8773 8774 // Apply an implicit SectionAttr if #pragma code_seg is active. 8775 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8776 !NewFD->hasAttr<SectionAttr>()) { 8777 NewFD->addAttr( 8778 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8779 CodeSegStack.CurrentValue->getString(), 8780 CodeSegStack.CurrentPragmaLocation)); 8781 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8782 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8783 ASTContext::PSF_Read, 8784 NewFD)) 8785 NewFD->dropAttr<SectionAttr>(); 8786 } 8787 8788 // Apply an implicit CodeSegAttr from class declspec or 8789 // apply an implicit SectionAttr from #pragma code_seg if active. 8790 if (!NewFD->hasAttr<CodeSegAttr>()) { 8791 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 8792 D.isFunctionDefinition())) { 8793 NewFD->addAttr(SAttr); 8794 } 8795 } 8796 8797 // Handle attributes. 8798 ProcessDeclAttributes(S, NewFD, D); 8799 8800 if (getLangOpts().OpenCL) { 8801 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8802 // type declaration will generate a compilation error. 8803 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8804 if (AddressSpace != LangAS::Default) { 8805 Diag(NewFD->getLocation(), 8806 diag::err_opencl_return_value_with_address_space); 8807 NewFD->setInvalidDecl(); 8808 } 8809 } 8810 8811 if (!getLangOpts().CPlusPlus) { 8812 // Perform semantic checking on the function declaration. 8813 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8814 CheckMain(NewFD, D.getDeclSpec()); 8815 8816 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8817 CheckMSVCRTEntryPoint(NewFD); 8818 8819 if (!NewFD->isInvalidDecl()) 8820 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8821 isMemberSpecialization)); 8822 else if (!Previous.empty()) 8823 // Recover gracefully from an invalid redeclaration. 8824 D.setRedeclaration(true); 8825 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8826 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8827 "previous declaration set still overloaded"); 8828 8829 // Diagnose no-prototype function declarations with calling conventions that 8830 // don't support variadic calls. Only do this in C and do it after merging 8831 // possibly prototyped redeclarations. 8832 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8833 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8834 CallingConv CC = FT->getExtInfo().getCC(); 8835 if (!supportsVariadicCall(CC)) { 8836 // Windows system headers sometimes accidentally use stdcall without 8837 // (void) parameters, so we relax this to a warning. 8838 int DiagID = 8839 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8840 Diag(NewFD->getLocation(), DiagID) 8841 << FunctionType::getNameForCallConv(CC); 8842 } 8843 } 8844 } else { 8845 // C++11 [replacement.functions]p3: 8846 // The program's definitions shall not be specified as inline. 8847 // 8848 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8849 // 8850 // Suppress the diagnostic if the function is __attribute__((used)), since 8851 // that forces an external definition to be emitted. 8852 if (D.getDeclSpec().isInlineSpecified() && 8853 NewFD->isReplaceableGlobalAllocationFunction() && 8854 !NewFD->hasAttr<UsedAttr>()) 8855 Diag(D.getDeclSpec().getInlineSpecLoc(), 8856 diag::ext_operator_new_delete_declared_inline) 8857 << NewFD->getDeclName(); 8858 8859 // If the declarator is a template-id, translate the parser's template 8860 // argument list into our AST format. 8861 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8862 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8863 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8864 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8865 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8866 TemplateId->NumArgs); 8867 translateTemplateArguments(TemplateArgsPtr, 8868 TemplateArgs); 8869 8870 HasExplicitTemplateArgs = true; 8871 8872 if (NewFD->isInvalidDecl()) { 8873 HasExplicitTemplateArgs = false; 8874 } else if (FunctionTemplate) { 8875 // Function template with explicit template arguments. 8876 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8877 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8878 8879 HasExplicitTemplateArgs = false; 8880 } else { 8881 assert((isFunctionTemplateSpecialization || 8882 D.getDeclSpec().isFriendSpecified()) && 8883 "should have a 'template<>' for this decl"); 8884 // "friend void foo<>(int);" is an implicit specialization decl. 8885 isFunctionTemplateSpecialization = true; 8886 } 8887 } else if (isFriend && isFunctionTemplateSpecialization) { 8888 // This combination is only possible in a recovery case; the user 8889 // wrote something like: 8890 // template <> friend void foo(int); 8891 // which we're recovering from as if the user had written: 8892 // friend void foo<>(int); 8893 // Go ahead and fake up a template id. 8894 HasExplicitTemplateArgs = true; 8895 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8896 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8897 } 8898 8899 // We do not add HD attributes to specializations here because 8900 // they may have different constexpr-ness compared to their 8901 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8902 // may end up with different effective targets. Instead, a 8903 // specialization inherits its target attributes from its template 8904 // in the CheckFunctionTemplateSpecialization() call below. 8905 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8906 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8907 8908 // If it's a friend (and only if it's a friend), it's possible 8909 // that either the specialized function type or the specialized 8910 // template is dependent, and therefore matching will fail. In 8911 // this case, don't check the specialization yet. 8912 bool InstantiationDependent = false; 8913 if (isFunctionTemplateSpecialization && isFriend && 8914 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8915 TemplateSpecializationType::anyDependentTemplateArguments( 8916 TemplateArgs, 8917 InstantiationDependent))) { 8918 assert(HasExplicitTemplateArgs && 8919 "friend function specialization without template args"); 8920 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8921 Previous)) 8922 NewFD->setInvalidDecl(); 8923 } else if (isFunctionTemplateSpecialization) { 8924 if (CurContext->isDependentContext() && CurContext->isRecord() 8925 && !isFriend) { 8926 isDependentClassScopeExplicitSpecialization = true; 8927 } else if (!NewFD->isInvalidDecl() && 8928 CheckFunctionTemplateSpecialization( 8929 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8930 Previous)) 8931 NewFD->setInvalidDecl(); 8932 8933 // C++ [dcl.stc]p1: 8934 // A storage-class-specifier shall not be specified in an explicit 8935 // specialization (14.7.3) 8936 FunctionTemplateSpecializationInfo *Info = 8937 NewFD->getTemplateSpecializationInfo(); 8938 if (Info && SC != SC_None) { 8939 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8940 Diag(NewFD->getLocation(), 8941 diag::err_explicit_specialization_inconsistent_storage_class) 8942 << SC 8943 << FixItHint::CreateRemoval( 8944 D.getDeclSpec().getStorageClassSpecLoc()); 8945 8946 else 8947 Diag(NewFD->getLocation(), 8948 diag::ext_explicit_specialization_storage_class) 8949 << FixItHint::CreateRemoval( 8950 D.getDeclSpec().getStorageClassSpecLoc()); 8951 } 8952 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8953 if (CheckMemberSpecialization(NewFD, Previous)) 8954 NewFD->setInvalidDecl(); 8955 } 8956 8957 // Perform semantic checking on the function declaration. 8958 if (!isDependentClassScopeExplicitSpecialization) { 8959 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8960 CheckMain(NewFD, D.getDeclSpec()); 8961 8962 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8963 CheckMSVCRTEntryPoint(NewFD); 8964 8965 if (!NewFD->isInvalidDecl()) 8966 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8967 isMemberSpecialization)); 8968 else if (!Previous.empty()) 8969 // Recover gracefully from an invalid redeclaration. 8970 D.setRedeclaration(true); 8971 } 8972 8973 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8974 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8975 "previous declaration set still overloaded"); 8976 8977 NamedDecl *PrincipalDecl = (FunctionTemplate 8978 ? cast<NamedDecl>(FunctionTemplate) 8979 : NewFD); 8980 8981 if (isFriend && NewFD->getPreviousDecl()) { 8982 AccessSpecifier Access = AS_public; 8983 if (!NewFD->isInvalidDecl()) 8984 Access = NewFD->getPreviousDecl()->getAccess(); 8985 8986 NewFD->setAccess(Access); 8987 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8988 } 8989 8990 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8991 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8992 PrincipalDecl->setNonMemberOperator(); 8993 8994 // If we have a function template, check the template parameter 8995 // list. This will check and merge default template arguments. 8996 if (FunctionTemplate) { 8997 FunctionTemplateDecl *PrevTemplate = 8998 FunctionTemplate->getPreviousDecl(); 8999 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9000 PrevTemplate ? PrevTemplate->getTemplateParameters() 9001 : nullptr, 9002 D.getDeclSpec().isFriendSpecified() 9003 ? (D.isFunctionDefinition() 9004 ? TPC_FriendFunctionTemplateDefinition 9005 : TPC_FriendFunctionTemplate) 9006 : (D.getCXXScopeSpec().isSet() && 9007 DC && DC->isRecord() && 9008 DC->isDependentContext()) 9009 ? TPC_ClassTemplateMember 9010 : TPC_FunctionTemplate); 9011 } 9012 9013 if (NewFD->isInvalidDecl()) { 9014 // Ignore all the rest of this. 9015 } else if (!D.isRedeclaration()) { 9016 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9017 AddToScope }; 9018 // Fake up an access specifier if it's supposed to be a class member. 9019 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9020 NewFD->setAccess(AS_public); 9021 9022 // Qualified decls generally require a previous declaration. 9023 if (D.getCXXScopeSpec().isSet()) { 9024 // ...with the major exception of templated-scope or 9025 // dependent-scope friend declarations. 9026 9027 // TODO: we currently also suppress this check in dependent 9028 // contexts because (1) the parameter depth will be off when 9029 // matching friend templates and (2) we might actually be 9030 // selecting a friend based on a dependent factor. But there 9031 // are situations where these conditions don't apply and we 9032 // can actually do this check immediately. 9033 if (isFriend && 9034 (TemplateParamLists.size() || 9035 D.getCXXScopeSpec().getScopeRep()->isDependent() || 9036 CurContext->isDependentContext())) { 9037 // ignore these 9038 } else { 9039 // The user tried to provide an out-of-line definition for a 9040 // function that is a member of a class or namespace, but there 9041 // was no such member function declared (C++ [class.mfct]p2, 9042 // C++ [namespace.memdef]p2). For example: 9043 // 9044 // class X { 9045 // void f() const; 9046 // }; 9047 // 9048 // void X::f() { } // ill-formed 9049 // 9050 // Complain about this problem, and attempt to suggest close 9051 // matches (e.g., those that differ only in cv-qualifiers and 9052 // whether the parameter types are references). 9053 9054 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9055 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9056 AddToScope = ExtraArgs.AddToScope; 9057 return Result; 9058 } 9059 } 9060 9061 // Unqualified local friend declarations are required to resolve 9062 // to something. 9063 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9064 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9065 *this, Previous, NewFD, ExtraArgs, true, S)) { 9066 AddToScope = ExtraArgs.AddToScope; 9067 return Result; 9068 } 9069 } 9070 } else if (!D.isFunctionDefinition() && 9071 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9072 !isFriend && !isFunctionTemplateSpecialization && 9073 !isMemberSpecialization) { 9074 // An out-of-line member function declaration must also be a 9075 // definition (C++ [class.mfct]p2). 9076 // Note that this is not the case for explicit specializations of 9077 // function templates or member functions of class templates, per 9078 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9079 // extension for compatibility with old SWIG code which likes to 9080 // generate them. 9081 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9082 << D.getCXXScopeSpec().getRange(); 9083 } 9084 } 9085 9086 ProcessPragmaWeak(S, NewFD); 9087 checkAttributesAfterMerging(*this, *NewFD); 9088 9089 AddKnownFunctionAttributes(NewFD); 9090 9091 if (NewFD->hasAttr<OverloadableAttr>() && 9092 !NewFD->getType()->getAs<FunctionProtoType>()) { 9093 Diag(NewFD->getLocation(), 9094 diag::err_attribute_overloadable_no_prototype) 9095 << NewFD; 9096 9097 // Turn this into a variadic function with no parameters. 9098 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9099 FunctionProtoType::ExtProtoInfo EPI( 9100 Context.getDefaultCallingConvention(true, false)); 9101 EPI.Variadic = true; 9102 EPI.ExtInfo = FT->getExtInfo(); 9103 9104 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9105 NewFD->setType(R); 9106 } 9107 9108 // If there's a #pragma GCC visibility in scope, and this isn't a class 9109 // member, set the visibility of this function. 9110 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9111 AddPushedVisibilityAttribute(NewFD); 9112 9113 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9114 // marking the function. 9115 AddCFAuditedAttribute(NewFD); 9116 9117 // If this is a function definition, check if we have to apply optnone due to 9118 // a pragma. 9119 if(D.isFunctionDefinition()) 9120 AddRangeBasedOptnone(NewFD); 9121 9122 // If this is the first declaration of an extern C variable, update 9123 // the map of such variables. 9124 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9125 isIncompleteDeclExternC(*this, NewFD)) 9126 RegisterLocallyScopedExternCDecl(NewFD, S); 9127 9128 // Set this FunctionDecl's range up to the right paren. 9129 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9130 9131 if (D.isRedeclaration() && !Previous.empty()) { 9132 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9133 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9134 isMemberSpecialization || 9135 isFunctionTemplateSpecialization, 9136 D.isFunctionDefinition()); 9137 } 9138 9139 if (getLangOpts().CUDA) { 9140 IdentifierInfo *II = NewFD->getIdentifier(); 9141 if (II && 9142 II->isStr(getLangOpts().HIP ? "hipConfigureCall" 9143 : "cudaConfigureCall") && 9144 !NewFD->isInvalidDecl() && 9145 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9146 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9147 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9148 Context.setcudaConfigureCallDecl(NewFD); 9149 } 9150 9151 // Variadic functions, other than a *declaration* of printf, are not allowed 9152 // in device-side CUDA code, unless someone passed 9153 // -fcuda-allow-variadic-functions. 9154 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9155 (NewFD->hasAttr<CUDADeviceAttr>() || 9156 NewFD->hasAttr<CUDAGlobalAttr>()) && 9157 !(II && II->isStr("printf") && NewFD->isExternC() && 9158 !D.isFunctionDefinition())) { 9159 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9160 } 9161 } 9162 9163 MarkUnusedFileScopedDecl(NewFD); 9164 9165 if (getLangOpts().CPlusPlus) { 9166 if (FunctionTemplate) { 9167 if (NewFD->isInvalidDecl()) 9168 FunctionTemplate->setInvalidDecl(); 9169 return FunctionTemplate; 9170 } 9171 9172 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9173 CompleteMemberSpecialization(NewFD, Previous); 9174 } 9175 9176 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9177 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9178 if ((getLangOpts().OpenCLVersion >= 120) 9179 && (SC == SC_Static)) { 9180 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9181 D.setInvalidType(); 9182 } 9183 9184 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9185 if (!NewFD->getReturnType()->isVoidType()) { 9186 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9187 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9188 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9189 : FixItHint()); 9190 D.setInvalidType(); 9191 } 9192 9193 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9194 for (auto Param : NewFD->parameters()) 9195 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9196 } 9197 for (const ParmVarDecl *Param : NewFD->parameters()) { 9198 QualType PT = Param->getType(); 9199 9200 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9201 // types. 9202 if (getLangOpts().OpenCLVersion >= 200) { 9203 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9204 QualType ElemTy = PipeTy->getElementType(); 9205 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9206 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9207 D.setInvalidType(); 9208 } 9209 } 9210 } 9211 } 9212 9213 // Here we have an function template explicit specialization at class scope. 9214 // The actual specialization will be postponed to template instatiation 9215 // time via the ClassScopeFunctionSpecializationDecl node. 9216 if (isDependentClassScopeExplicitSpecialization) { 9217 ClassScopeFunctionSpecializationDecl *NewSpec = 9218 ClassScopeFunctionSpecializationDecl::Create( 9219 Context, CurContext, NewFD->getLocation(), 9220 cast<CXXMethodDecl>(NewFD), 9221 HasExplicitTemplateArgs, TemplateArgs); 9222 CurContext->addDecl(NewSpec); 9223 AddToScope = false; 9224 } 9225 9226 // Diagnose availability attributes. Availability cannot be used on functions 9227 // that are run during load/unload. 9228 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9229 if (NewFD->hasAttr<ConstructorAttr>()) { 9230 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9231 << 1; 9232 NewFD->dropAttr<AvailabilityAttr>(); 9233 } 9234 if (NewFD->hasAttr<DestructorAttr>()) { 9235 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9236 << 2; 9237 NewFD->dropAttr<AvailabilityAttr>(); 9238 } 9239 } 9240 9241 return NewFD; 9242 } 9243 9244 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9245 /// when __declspec(code_seg) "is applied to a class, all member functions of 9246 /// the class and nested classes -- this includes compiler-generated special 9247 /// member functions -- are put in the specified segment." 9248 /// The actual behavior is a little more complicated. The Microsoft compiler 9249 /// won't check outer classes if there is an active value from #pragma code_seg. 9250 /// The CodeSeg is always applied from the direct parent but only from outer 9251 /// classes when the #pragma code_seg stack is empty. See: 9252 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9253 /// available since MS has removed the page. 9254 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9255 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9256 if (!Method) 9257 return nullptr; 9258 const CXXRecordDecl *Parent = Method->getParent(); 9259 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9260 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9261 NewAttr->setImplicit(true); 9262 return NewAttr; 9263 } 9264 9265 // The Microsoft compiler won't check outer classes for the CodeSeg 9266 // when the #pragma code_seg stack is active. 9267 if (S.CodeSegStack.CurrentValue) 9268 return nullptr; 9269 9270 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9271 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9272 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9273 NewAttr->setImplicit(true); 9274 return NewAttr; 9275 } 9276 } 9277 return nullptr; 9278 } 9279 9280 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9281 /// containing class. Otherwise it will return implicit SectionAttr if the 9282 /// function is a definition and there is an active value on CodeSegStack 9283 /// (from the current #pragma code-seg value). 9284 /// 9285 /// \param FD Function being declared. 9286 /// \param IsDefinition Whether it is a definition or just a declarartion. 9287 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9288 /// nullptr if no attribute should be added. 9289 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9290 bool IsDefinition) { 9291 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9292 return A; 9293 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9294 CodeSegStack.CurrentValue) { 9295 return SectionAttr::CreateImplicit(getASTContext(), 9296 SectionAttr::Declspec_allocate, 9297 CodeSegStack.CurrentValue->getString(), 9298 CodeSegStack.CurrentPragmaLocation); 9299 } 9300 return nullptr; 9301 } 9302 9303 /// Determines if we can perform a correct type check for \p D as a 9304 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9305 /// best-effort check. 9306 /// 9307 /// \param NewD The new declaration. 9308 /// \param OldD The old declaration. 9309 /// \param NewT The portion of the type of the new declaration to check. 9310 /// \param OldT The portion of the type of the old declaration to check. 9311 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9312 QualType NewT, QualType OldT) { 9313 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9314 return true; 9315 9316 // For dependently-typed local extern declarations and friends, we can't 9317 // perform a correct type check in general until instantiation: 9318 // 9319 // int f(); 9320 // template<typename T> void g() { T f(); } 9321 // 9322 // (valid if g() is only instantiated with T = int). 9323 if (NewT->isDependentType() && 9324 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9325 return false; 9326 9327 // Similarly, if the previous declaration was a dependent local extern 9328 // declaration, we don't really know its type yet. 9329 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9330 return false; 9331 9332 return true; 9333 } 9334 9335 /// Checks if the new declaration declared in dependent context must be 9336 /// put in the same redeclaration chain as the specified declaration. 9337 /// 9338 /// \param D Declaration that is checked. 9339 /// \param PrevDecl Previous declaration found with proper lookup method for the 9340 /// same declaration name. 9341 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9342 /// belongs to. 9343 /// 9344 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9345 if (!D->getLexicalDeclContext()->isDependentContext()) 9346 return true; 9347 9348 // Don't chain dependent friend function definitions until instantiation, to 9349 // permit cases like 9350 // 9351 // void func(); 9352 // template<typename T> class C1 { friend void func() {} }; 9353 // template<typename T> class C2 { friend void func() {} }; 9354 // 9355 // ... which is valid if only one of C1 and C2 is ever instantiated. 9356 // 9357 // FIXME: This need only apply to function definitions. For now, we proxy 9358 // this by checking for a file-scope function. We do not want this to apply 9359 // to friend declarations nominating member functions, because that gets in 9360 // the way of access checks. 9361 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9362 return false; 9363 9364 auto *VD = dyn_cast<ValueDecl>(D); 9365 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9366 return !VD || !PrevVD || 9367 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9368 PrevVD->getType()); 9369 } 9370 9371 /// Check the target attribute of the function for MultiVersion 9372 /// validity. 9373 /// 9374 /// Returns true if there was an error, false otherwise. 9375 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9376 const auto *TA = FD->getAttr<TargetAttr>(); 9377 assert(TA && "MultiVersion Candidate requires a target attribute"); 9378 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9379 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9380 enum ErrType { Feature = 0, Architecture = 1 }; 9381 9382 if (!ParseInfo.Architecture.empty() && 9383 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9384 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9385 << Architecture << ParseInfo.Architecture; 9386 return true; 9387 } 9388 9389 for (const auto &Feat : ParseInfo.Features) { 9390 auto BareFeat = StringRef{Feat}.substr(1); 9391 if (Feat[0] == '-') { 9392 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9393 << Feature << ("no-" + BareFeat).str(); 9394 return true; 9395 } 9396 9397 if (!TargetInfo.validateCpuSupports(BareFeat) || 9398 !TargetInfo.isValidFeatureName(BareFeat)) { 9399 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9400 << Feature << BareFeat; 9401 return true; 9402 } 9403 } 9404 return false; 9405 } 9406 9407 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9408 MultiVersionKind MVType) { 9409 for (const Attr *A : FD->attrs()) { 9410 switch (A->getKind()) { 9411 case attr::CPUDispatch: 9412 case attr::CPUSpecific: 9413 if (MVType != MultiVersionKind::CPUDispatch && 9414 MVType != MultiVersionKind::CPUSpecific) 9415 return true; 9416 break; 9417 case attr::Target: 9418 if (MVType != MultiVersionKind::Target) 9419 return true; 9420 break; 9421 default: 9422 return true; 9423 } 9424 } 9425 return false; 9426 } 9427 9428 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9429 const FunctionDecl *NewFD, 9430 bool CausesMV, 9431 MultiVersionKind MVType) { 9432 enum DoesntSupport { 9433 FuncTemplates = 0, 9434 VirtFuncs = 1, 9435 DeducedReturn = 2, 9436 Constructors = 3, 9437 Destructors = 4, 9438 DeletedFuncs = 5, 9439 DefaultedFuncs = 6, 9440 ConstexprFuncs = 7, 9441 }; 9442 enum Different { 9443 CallingConv = 0, 9444 ReturnType = 1, 9445 ConstexprSpec = 2, 9446 InlineSpec = 3, 9447 StorageClass = 4, 9448 Linkage = 5 9449 }; 9450 9451 bool IsCPUSpecificCPUDispatchMVType = 9452 MVType == MultiVersionKind::CPUDispatch || 9453 MVType == MultiVersionKind::CPUSpecific; 9454 9455 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { 9456 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9457 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9458 return true; 9459 } 9460 9461 if (!NewFD->getType()->getAs<FunctionProtoType>()) 9462 return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9463 9464 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9465 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9466 if (OldFD) 9467 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9468 return true; 9469 } 9470 9471 // For now, disallow all other attributes. These should be opt-in, but 9472 // an analysis of all of them is a future FIXME. 9473 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 9474 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 9475 << IsCPUSpecificCPUDispatchMVType; 9476 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9477 return true; 9478 } 9479 9480 if (HasNonMultiVersionAttributes(NewFD, MVType)) 9481 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 9482 << IsCPUSpecificCPUDispatchMVType; 9483 9484 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9485 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9486 << IsCPUSpecificCPUDispatchMVType << FuncTemplates; 9487 9488 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9489 if (NewCXXFD->isVirtual()) 9490 return S.Diag(NewCXXFD->getLocation(), 9491 diag::err_multiversion_doesnt_support) 9492 << IsCPUSpecificCPUDispatchMVType << VirtFuncs; 9493 9494 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9495 return S.Diag(NewCXXCtor->getLocation(), 9496 diag::err_multiversion_doesnt_support) 9497 << IsCPUSpecificCPUDispatchMVType << Constructors; 9498 9499 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9500 return S.Diag(NewCXXDtor->getLocation(), 9501 diag::err_multiversion_doesnt_support) 9502 << IsCPUSpecificCPUDispatchMVType << Destructors; 9503 } 9504 9505 if (NewFD->isDeleted()) 9506 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9507 << IsCPUSpecificCPUDispatchMVType << DeletedFuncs; 9508 9509 if (NewFD->isDefaulted()) 9510 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9511 << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs; 9512 9513 if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch || 9514 MVType == MultiVersionKind::CPUSpecific)) 9515 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9516 << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs; 9517 9518 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9519 const auto *NewType = cast<FunctionType>(NewQType); 9520 QualType NewReturnType = NewType->getReturnType(); 9521 9522 if (NewReturnType->isUndeducedType()) 9523 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9524 << IsCPUSpecificCPUDispatchMVType << DeducedReturn; 9525 9526 // Only allow transition to MultiVersion if it hasn't been used. 9527 if (OldFD && CausesMV && OldFD->isUsed(false)) 9528 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9529 9530 // Ensure the return type is identical. 9531 if (OldFD) { 9532 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9533 const auto *OldType = cast<FunctionType>(OldQType); 9534 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9535 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9536 9537 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9538 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9539 << CallingConv; 9540 9541 QualType OldReturnType = OldType->getReturnType(); 9542 9543 if (OldReturnType != NewReturnType) 9544 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9545 << ReturnType; 9546 9547 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9548 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9549 << ConstexprSpec; 9550 9551 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9552 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9553 << InlineSpec; 9554 9555 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9556 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9557 << StorageClass; 9558 9559 if (OldFD->isExternC() != NewFD->isExternC()) 9560 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9561 << Linkage; 9562 9563 if (S.CheckEquivalentExceptionSpec( 9564 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9565 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9566 return true; 9567 } 9568 return false; 9569 } 9570 9571 /// Check the validity of a multiversion function declaration that is the 9572 /// first of its kind. Also sets the multiversion'ness' of the function itself. 9573 /// 9574 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9575 /// 9576 /// Returns true if there was an error, false otherwise. 9577 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 9578 MultiVersionKind MVType, 9579 const TargetAttr *TA, 9580 const CPUDispatchAttr *CPUDisp, 9581 const CPUSpecificAttr *CPUSpec) { 9582 assert(MVType != MultiVersionKind::None && 9583 "Function lacks multiversion attribute"); 9584 9585 // Target only causes MV if it is default, otherwise this is a normal 9586 // function. 9587 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 9588 return false; 9589 9590 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 9591 FD->setInvalidDecl(); 9592 return true; 9593 } 9594 9595 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 9596 FD->setInvalidDecl(); 9597 return true; 9598 } 9599 9600 FD->setIsMultiVersion(); 9601 return false; 9602 } 9603 9604 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 9605 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 9606 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 9607 return true; 9608 } 9609 9610 return false; 9611 } 9612 9613 static bool CheckTargetCausesMultiVersioning( 9614 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 9615 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9616 LookupResult &Previous) { 9617 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9618 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9619 // Sort order doesn't matter, it just needs to be consistent. 9620 llvm::sort(NewParsed.Features); 9621 9622 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9623 // to change, this is a simple redeclaration. 9624 if (!NewTA->isDefaultVersion() && 9625 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 9626 return false; 9627 9628 // Otherwise, this decl causes MultiVersioning. 9629 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9630 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9631 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9632 NewFD->setInvalidDecl(); 9633 return true; 9634 } 9635 9636 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 9637 MultiVersionKind::Target)) { 9638 NewFD->setInvalidDecl(); 9639 return true; 9640 } 9641 9642 if (CheckMultiVersionValue(S, NewFD)) { 9643 NewFD->setInvalidDecl(); 9644 return true; 9645 } 9646 9647 // If this is 'default', permit the forward declaration. 9648 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 9649 Redeclaration = true; 9650 OldDecl = OldFD; 9651 OldFD->setIsMultiVersion(); 9652 NewFD->setIsMultiVersion(); 9653 return false; 9654 } 9655 9656 if (CheckMultiVersionValue(S, OldFD)) { 9657 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9658 NewFD->setInvalidDecl(); 9659 return true; 9660 } 9661 9662 TargetAttr::ParsedTargetAttr OldParsed = 9663 OldTA->parse(std::less<std::string>()); 9664 9665 if (OldParsed == NewParsed) { 9666 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9667 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9668 NewFD->setInvalidDecl(); 9669 return true; 9670 } 9671 9672 for (const auto *FD : OldFD->redecls()) { 9673 const auto *CurTA = FD->getAttr<TargetAttr>(); 9674 // We allow forward declarations before ANY multiversioning attributes, but 9675 // nothing after the fact. 9676 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 9677 (!CurTA || CurTA->isInherited())) { 9678 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 9679 << 0; 9680 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9681 NewFD->setInvalidDecl(); 9682 return true; 9683 } 9684 } 9685 9686 OldFD->setIsMultiVersion(); 9687 NewFD->setIsMultiVersion(); 9688 Redeclaration = false; 9689 MergeTypeWithPrevious = false; 9690 OldDecl = nullptr; 9691 Previous.clear(); 9692 return false; 9693 } 9694 9695 /// Check the validity of a new function declaration being added to an existing 9696 /// multiversioned declaration collection. 9697 static bool CheckMultiVersionAdditionalDecl( 9698 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 9699 MultiVersionKind NewMVType, const TargetAttr *NewTA, 9700 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 9701 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9702 LookupResult &Previous) { 9703 9704 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 9705 // Disallow mixing of multiversioning types. 9706 if ((OldMVType == MultiVersionKind::Target && 9707 NewMVType != MultiVersionKind::Target) || 9708 (NewMVType == MultiVersionKind::Target && 9709 OldMVType != MultiVersionKind::Target)) { 9710 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9711 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9712 NewFD->setInvalidDecl(); 9713 return true; 9714 } 9715 9716 TargetAttr::ParsedTargetAttr NewParsed; 9717 if (NewTA) { 9718 NewParsed = NewTA->parse(); 9719 llvm::sort(NewParsed.Features); 9720 } 9721 9722 bool UseMemberUsingDeclRules = 9723 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9724 9725 // Next, check ALL non-overloads to see if this is a redeclaration of a 9726 // previous member of the MultiVersion set. 9727 for (NamedDecl *ND : Previous) { 9728 FunctionDecl *CurFD = ND->getAsFunction(); 9729 if (!CurFD) 9730 continue; 9731 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9732 continue; 9733 9734 if (NewMVType == MultiVersionKind::Target) { 9735 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9736 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9737 NewFD->setIsMultiVersion(); 9738 Redeclaration = true; 9739 OldDecl = ND; 9740 return false; 9741 } 9742 9743 TargetAttr::ParsedTargetAttr CurParsed = 9744 CurTA->parse(std::less<std::string>()); 9745 if (CurParsed == NewParsed) { 9746 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9747 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9748 NewFD->setInvalidDecl(); 9749 return true; 9750 } 9751 } else { 9752 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 9753 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 9754 // Handle CPUDispatch/CPUSpecific versions. 9755 // Only 1 CPUDispatch function is allowed, this will make it go through 9756 // the redeclaration errors. 9757 if (NewMVType == MultiVersionKind::CPUDispatch && 9758 CurFD->hasAttr<CPUDispatchAttr>()) { 9759 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 9760 std::equal( 9761 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 9762 NewCPUDisp->cpus_begin(), 9763 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9764 return Cur->getName() == New->getName(); 9765 })) { 9766 NewFD->setIsMultiVersion(); 9767 Redeclaration = true; 9768 OldDecl = ND; 9769 return false; 9770 } 9771 9772 // If the declarations don't match, this is an error condition. 9773 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 9774 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9775 NewFD->setInvalidDecl(); 9776 return true; 9777 } 9778 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 9779 9780 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 9781 std::equal( 9782 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 9783 NewCPUSpec->cpus_begin(), 9784 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9785 return Cur->getName() == New->getName(); 9786 })) { 9787 NewFD->setIsMultiVersion(); 9788 Redeclaration = true; 9789 OldDecl = ND; 9790 return false; 9791 } 9792 9793 // Only 1 version of CPUSpecific is allowed for each CPU. 9794 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 9795 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 9796 if (CurII == NewII) { 9797 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 9798 << NewII; 9799 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9800 NewFD->setInvalidDecl(); 9801 return true; 9802 } 9803 } 9804 } 9805 } 9806 // If the two decls aren't the same MVType, there is no possible error 9807 // condition. 9808 } 9809 } 9810 9811 // Else, this is simply a non-redecl case. Checking the 'value' is only 9812 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 9813 // handled in the attribute adding step. 9814 if (NewMVType == MultiVersionKind::Target && 9815 CheckMultiVersionValue(S, NewFD)) { 9816 NewFD->setInvalidDecl(); 9817 return true; 9818 } 9819 9820 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false, NewMVType)) { 9821 NewFD->setInvalidDecl(); 9822 return true; 9823 } 9824 9825 // Permit forward declarations in the case where these two are compatible. 9826 if (!OldFD->isMultiVersion()) { 9827 OldFD->setIsMultiVersion(); 9828 NewFD->setIsMultiVersion(); 9829 Redeclaration = true; 9830 OldDecl = OldFD; 9831 return false; 9832 } 9833 9834 NewFD->setIsMultiVersion(); 9835 Redeclaration = false; 9836 MergeTypeWithPrevious = false; 9837 OldDecl = nullptr; 9838 Previous.clear(); 9839 return false; 9840 } 9841 9842 9843 /// Check the validity of a mulitversion function declaration. 9844 /// Also sets the multiversion'ness' of the function itself. 9845 /// 9846 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9847 /// 9848 /// Returns true if there was an error, false otherwise. 9849 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9850 bool &Redeclaration, NamedDecl *&OldDecl, 9851 bool &MergeTypeWithPrevious, 9852 LookupResult &Previous) { 9853 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9854 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 9855 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 9856 9857 // Mixing Multiversioning types is prohibited. 9858 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 9859 (NewCPUDisp && NewCPUSpec)) { 9860 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9861 NewFD->setInvalidDecl(); 9862 return true; 9863 } 9864 9865 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 9866 9867 // Main isn't allowed to become a multiversion function, however it IS 9868 // permitted to have 'main' be marked with the 'target' optimization hint. 9869 if (NewFD->isMain()) { 9870 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 9871 MVType == MultiVersionKind::CPUDispatch || 9872 MVType == MultiVersionKind::CPUSpecific) { 9873 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9874 NewFD->setInvalidDecl(); 9875 return true; 9876 } 9877 return false; 9878 } 9879 9880 if (!OldDecl || !OldDecl->getAsFunction() || 9881 OldDecl->getDeclContext()->getRedeclContext() != 9882 NewFD->getDeclContext()->getRedeclContext()) { 9883 // If there's no previous declaration, AND this isn't attempting to cause 9884 // multiversioning, this isn't an error condition. 9885 if (MVType == MultiVersionKind::None) 9886 return false; 9887 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp, 9888 NewCPUSpec); 9889 } 9890 9891 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9892 9893 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 9894 return false; 9895 9896 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 9897 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 9898 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 9899 NewFD->setInvalidDecl(); 9900 return true; 9901 } 9902 9903 // Handle the target potentially causes multiversioning case. 9904 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 9905 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 9906 Redeclaration, OldDecl, 9907 MergeTypeWithPrevious, Previous); 9908 9909 // At this point, we have a multiversion function decl (in OldFD) AND an 9910 // appropriate attribute in the current function decl. Resolve that these are 9911 // still compatible with previous declarations. 9912 return CheckMultiVersionAdditionalDecl( 9913 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 9914 OldDecl, MergeTypeWithPrevious, Previous); 9915 } 9916 9917 /// Perform semantic checking of a new function declaration. 9918 /// 9919 /// Performs semantic analysis of the new function declaration 9920 /// NewFD. This routine performs all semantic checking that does not 9921 /// require the actual declarator involved in the declaration, and is 9922 /// used both for the declaration of functions as they are parsed 9923 /// (called via ActOnDeclarator) and for the declaration of functions 9924 /// that have been instantiated via C++ template instantiation (called 9925 /// via InstantiateDecl). 9926 /// 9927 /// \param IsMemberSpecialization whether this new function declaration is 9928 /// a member specialization (that replaces any definition provided by the 9929 /// previous declaration). 9930 /// 9931 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9932 /// 9933 /// \returns true if the function declaration is a redeclaration. 9934 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9935 LookupResult &Previous, 9936 bool IsMemberSpecialization) { 9937 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9938 "Variably modified return types are not handled here"); 9939 9940 // Determine whether the type of this function should be merged with 9941 // a previous visible declaration. This never happens for functions in C++, 9942 // and always happens in C if the previous declaration was visible. 9943 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9944 !Previous.isShadowed(); 9945 9946 bool Redeclaration = false; 9947 NamedDecl *OldDecl = nullptr; 9948 bool MayNeedOverloadableChecks = false; 9949 9950 // Merge or overload the declaration with an existing declaration of 9951 // the same name, if appropriate. 9952 if (!Previous.empty()) { 9953 // Determine whether NewFD is an overload of PrevDecl or 9954 // a declaration that requires merging. If it's an overload, 9955 // there's no more work to do here; we'll just add the new 9956 // function to the scope. 9957 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9958 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9959 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9960 Redeclaration = true; 9961 OldDecl = Candidate; 9962 } 9963 } else { 9964 MayNeedOverloadableChecks = true; 9965 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9966 /*NewIsUsingDecl*/ false)) { 9967 case Ovl_Match: 9968 Redeclaration = true; 9969 break; 9970 9971 case Ovl_NonFunction: 9972 Redeclaration = true; 9973 break; 9974 9975 case Ovl_Overload: 9976 Redeclaration = false; 9977 break; 9978 } 9979 } 9980 } 9981 9982 // Check for a previous extern "C" declaration with this name. 9983 if (!Redeclaration && 9984 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9985 if (!Previous.empty()) { 9986 // This is an extern "C" declaration with the same name as a previous 9987 // declaration, and thus redeclares that entity... 9988 Redeclaration = true; 9989 OldDecl = Previous.getFoundDecl(); 9990 MergeTypeWithPrevious = false; 9991 9992 // ... except in the presence of __attribute__((overloadable)). 9993 if (OldDecl->hasAttr<OverloadableAttr>() || 9994 NewFD->hasAttr<OverloadableAttr>()) { 9995 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9996 MayNeedOverloadableChecks = true; 9997 Redeclaration = false; 9998 OldDecl = nullptr; 9999 } 10000 } 10001 } 10002 } 10003 10004 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10005 MergeTypeWithPrevious, Previous)) 10006 return Redeclaration; 10007 10008 // C++11 [dcl.constexpr]p8: 10009 // A constexpr specifier for a non-static member function that is not 10010 // a constructor declares that member function to be const. 10011 // 10012 // This needs to be delayed until we know whether this is an out-of-line 10013 // definition of a static member function. 10014 // 10015 // This rule is not present in C++1y, so we produce a backwards 10016 // compatibility warning whenever it happens in C++11. 10017 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10018 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10019 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10020 !MD->getTypeQualifiers().hasConst()) { 10021 CXXMethodDecl *OldMD = nullptr; 10022 if (OldDecl) 10023 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10024 if (!OldMD || !OldMD->isStatic()) { 10025 const FunctionProtoType *FPT = 10026 MD->getType()->castAs<FunctionProtoType>(); 10027 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10028 EPI.TypeQuals.addConst(); 10029 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10030 FPT->getParamTypes(), EPI)); 10031 10032 // Warn that we did this, if we're not performing template instantiation. 10033 // In that case, we'll have warned already when the template was defined. 10034 if (!inTemplateInstantiation()) { 10035 SourceLocation AddConstLoc; 10036 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10037 .IgnoreParens().getAs<FunctionTypeLoc>()) 10038 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10039 10040 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10041 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10042 } 10043 } 10044 } 10045 10046 if (Redeclaration) { 10047 // NewFD and OldDecl represent declarations that need to be 10048 // merged. 10049 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10050 NewFD->setInvalidDecl(); 10051 return Redeclaration; 10052 } 10053 10054 Previous.clear(); 10055 Previous.addDecl(OldDecl); 10056 10057 if (FunctionTemplateDecl *OldTemplateDecl = 10058 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10059 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10060 FunctionTemplateDecl *NewTemplateDecl 10061 = NewFD->getDescribedFunctionTemplate(); 10062 assert(NewTemplateDecl && "Template/non-template mismatch"); 10063 10064 // The call to MergeFunctionDecl above may have created some state in 10065 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10066 // can add it as a redeclaration. 10067 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10068 10069 NewFD->setPreviousDeclaration(OldFD); 10070 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10071 if (NewFD->isCXXClassMember()) { 10072 NewFD->setAccess(OldTemplateDecl->getAccess()); 10073 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10074 } 10075 10076 // If this is an explicit specialization of a member that is a function 10077 // template, mark it as a member specialization. 10078 if (IsMemberSpecialization && 10079 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10080 NewTemplateDecl->setMemberSpecialization(); 10081 assert(OldTemplateDecl->isMemberSpecialization()); 10082 // Explicit specializations of a member template do not inherit deleted 10083 // status from the parent member template that they are specializing. 10084 if (OldFD->isDeleted()) { 10085 // FIXME: This assert will not hold in the presence of modules. 10086 assert(OldFD->getCanonicalDecl() == OldFD); 10087 // FIXME: We need an update record for this AST mutation. 10088 OldFD->setDeletedAsWritten(false); 10089 } 10090 } 10091 10092 } else { 10093 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10094 auto *OldFD = cast<FunctionDecl>(OldDecl); 10095 // This needs to happen first so that 'inline' propagates. 10096 NewFD->setPreviousDeclaration(OldFD); 10097 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10098 if (NewFD->isCXXClassMember()) 10099 NewFD->setAccess(OldFD->getAccess()); 10100 } 10101 } 10102 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10103 !NewFD->getAttr<OverloadableAttr>()) { 10104 assert((Previous.empty() || 10105 llvm::any_of(Previous, 10106 [](const NamedDecl *ND) { 10107 return ND->hasAttr<OverloadableAttr>(); 10108 })) && 10109 "Non-redecls shouldn't happen without overloadable present"); 10110 10111 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10112 const auto *FD = dyn_cast<FunctionDecl>(ND); 10113 return FD && !FD->hasAttr<OverloadableAttr>(); 10114 }); 10115 10116 if (OtherUnmarkedIter != Previous.end()) { 10117 Diag(NewFD->getLocation(), 10118 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10119 Diag((*OtherUnmarkedIter)->getLocation(), 10120 diag::note_attribute_overloadable_prev_overload) 10121 << false; 10122 10123 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10124 } 10125 } 10126 10127 // Semantic checking for this function declaration (in isolation). 10128 10129 if (getLangOpts().CPlusPlus) { 10130 // C++-specific checks. 10131 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10132 CheckConstructor(Constructor); 10133 } else if (CXXDestructorDecl *Destructor = 10134 dyn_cast<CXXDestructorDecl>(NewFD)) { 10135 CXXRecordDecl *Record = Destructor->getParent(); 10136 QualType ClassType = Context.getTypeDeclType(Record); 10137 10138 // FIXME: Shouldn't we be able to perform this check even when the class 10139 // type is dependent? Both gcc and edg can handle that. 10140 if (!ClassType->isDependentType()) { 10141 DeclarationName Name 10142 = Context.DeclarationNames.getCXXDestructorName( 10143 Context.getCanonicalType(ClassType)); 10144 if (NewFD->getDeclName() != Name) { 10145 Diag(NewFD->getLocation(), diag::err_destructor_name); 10146 NewFD->setInvalidDecl(); 10147 return Redeclaration; 10148 } 10149 } 10150 } else if (CXXConversionDecl *Conversion 10151 = dyn_cast<CXXConversionDecl>(NewFD)) { 10152 ActOnConversionDeclarator(Conversion); 10153 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10154 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10155 CheckDeductionGuideTemplate(TD); 10156 10157 // A deduction guide is not on the list of entities that can be 10158 // explicitly specialized. 10159 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10160 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10161 << /*explicit specialization*/ 1; 10162 } 10163 10164 // Find any virtual functions that this function overrides. 10165 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10166 if (!Method->isFunctionTemplateSpecialization() && 10167 !Method->getDescribedFunctionTemplate() && 10168 Method->isCanonicalDecl()) { 10169 if (AddOverriddenMethods(Method->getParent(), Method)) { 10170 // If the function was marked as "static", we have a problem. 10171 if (NewFD->getStorageClass() == SC_Static) { 10172 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10173 } 10174 } 10175 } 10176 10177 if (Method->isStatic()) 10178 checkThisInStaticMemberFunctionType(Method); 10179 } 10180 10181 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10182 if (NewFD->isOverloadedOperator() && 10183 CheckOverloadedOperatorDeclaration(NewFD)) { 10184 NewFD->setInvalidDecl(); 10185 return Redeclaration; 10186 } 10187 10188 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10189 if (NewFD->getLiteralIdentifier() && 10190 CheckLiteralOperatorDeclaration(NewFD)) { 10191 NewFD->setInvalidDecl(); 10192 return Redeclaration; 10193 } 10194 10195 // In C++, check default arguments now that we have merged decls. Unless 10196 // the lexical context is the class, because in this case this is done 10197 // during delayed parsing anyway. 10198 if (!CurContext->isRecord()) 10199 CheckCXXDefaultArguments(NewFD); 10200 10201 // If this function declares a builtin function, check the type of this 10202 // declaration against the expected type for the builtin. 10203 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10204 ASTContext::GetBuiltinTypeError Error; 10205 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10206 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10207 // If the type of the builtin differs only in its exception 10208 // specification, that's OK. 10209 // FIXME: If the types do differ in this way, it would be better to 10210 // retain the 'noexcept' form of the type. 10211 if (!T.isNull() && 10212 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10213 NewFD->getType())) 10214 // The type of this function differs from the type of the builtin, 10215 // so forget about the builtin entirely. 10216 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10217 } 10218 10219 // If this function is declared as being extern "C", then check to see if 10220 // the function returns a UDT (class, struct, or union type) that is not C 10221 // compatible, and if it does, warn the user. 10222 // But, issue any diagnostic on the first declaration only. 10223 if (Previous.empty() && NewFD->isExternC()) { 10224 QualType R = NewFD->getReturnType(); 10225 if (R->isIncompleteType() && !R->isVoidType()) 10226 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10227 << NewFD << R; 10228 else if (!R.isPODType(Context) && !R->isVoidType() && 10229 !R->isObjCObjectPointerType()) 10230 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10231 } 10232 10233 // C++1z [dcl.fct]p6: 10234 // [...] whether the function has a non-throwing exception-specification 10235 // [is] part of the function type 10236 // 10237 // This results in an ABI break between C++14 and C++17 for functions whose 10238 // declared type includes an exception-specification in a parameter or 10239 // return type. (Exception specifications on the function itself are OK in 10240 // most cases, and exception specifications are not permitted in most other 10241 // contexts where they could make it into a mangling.) 10242 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10243 auto HasNoexcept = [&](QualType T) -> bool { 10244 // Strip off declarator chunks that could be between us and a function 10245 // type. We don't need to look far, exception specifications are very 10246 // restricted prior to C++17. 10247 if (auto *RT = T->getAs<ReferenceType>()) 10248 T = RT->getPointeeType(); 10249 else if (T->isAnyPointerType()) 10250 T = T->getPointeeType(); 10251 else if (auto *MPT = T->getAs<MemberPointerType>()) 10252 T = MPT->getPointeeType(); 10253 if (auto *FPT = T->getAs<FunctionProtoType>()) 10254 if (FPT->isNothrow()) 10255 return true; 10256 return false; 10257 }; 10258 10259 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10260 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10261 for (QualType T : FPT->param_types()) 10262 AnyNoexcept |= HasNoexcept(T); 10263 if (AnyNoexcept) 10264 Diag(NewFD->getLocation(), 10265 diag::warn_cxx17_compat_exception_spec_in_signature) 10266 << NewFD; 10267 } 10268 10269 if (!Redeclaration && LangOpts.CUDA) 10270 checkCUDATargetOverload(NewFD, Previous); 10271 } 10272 return Redeclaration; 10273 } 10274 10275 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10276 // C++11 [basic.start.main]p3: 10277 // A program that [...] declares main to be inline, static or 10278 // constexpr is ill-formed. 10279 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10280 // appear in a declaration of main. 10281 // static main is not an error under C99, but we should warn about it. 10282 // We accept _Noreturn main as an extension. 10283 if (FD->getStorageClass() == SC_Static) 10284 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10285 ? diag::err_static_main : diag::warn_static_main) 10286 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10287 if (FD->isInlineSpecified()) 10288 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10289 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10290 if (DS.isNoreturnSpecified()) { 10291 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10292 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10293 Diag(NoreturnLoc, diag::ext_noreturn_main); 10294 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10295 << FixItHint::CreateRemoval(NoreturnRange); 10296 } 10297 if (FD->isConstexpr()) { 10298 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10299 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10300 FD->setConstexpr(false); 10301 } 10302 10303 if (getLangOpts().OpenCL) { 10304 Diag(FD->getLocation(), diag::err_opencl_no_main) 10305 << FD->hasAttr<OpenCLKernelAttr>(); 10306 FD->setInvalidDecl(); 10307 return; 10308 } 10309 10310 QualType T = FD->getType(); 10311 assert(T->isFunctionType() && "function decl is not of function type"); 10312 const FunctionType* FT = T->castAs<FunctionType>(); 10313 10314 // Set default calling convention for main() 10315 if (FT->getCallConv() != CC_C) { 10316 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10317 FD->setType(QualType(FT, 0)); 10318 T = Context.getCanonicalType(FD->getType()); 10319 } 10320 10321 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10322 // In C with GNU extensions we allow main() to have non-integer return 10323 // type, but we should warn about the extension, and we disable the 10324 // implicit-return-zero rule. 10325 10326 // GCC in C mode accepts qualified 'int'. 10327 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10328 FD->setHasImplicitReturnZero(true); 10329 else { 10330 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10331 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10332 if (RTRange.isValid()) 10333 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10334 << FixItHint::CreateReplacement(RTRange, "int"); 10335 } 10336 } else { 10337 // In C and C++, main magically returns 0 if you fall off the end; 10338 // set the flag which tells us that. 10339 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10340 10341 // All the standards say that main() should return 'int'. 10342 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10343 FD->setHasImplicitReturnZero(true); 10344 else { 10345 // Otherwise, this is just a flat-out error. 10346 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10347 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10348 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10349 : FixItHint()); 10350 FD->setInvalidDecl(true); 10351 } 10352 } 10353 10354 // Treat protoless main() as nullary. 10355 if (isa<FunctionNoProtoType>(FT)) return; 10356 10357 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10358 unsigned nparams = FTP->getNumParams(); 10359 assert(FD->getNumParams() == nparams); 10360 10361 bool HasExtraParameters = (nparams > 3); 10362 10363 if (FTP->isVariadic()) { 10364 Diag(FD->getLocation(), diag::ext_variadic_main); 10365 // FIXME: if we had information about the location of the ellipsis, we 10366 // could add a FixIt hint to remove it as a parameter. 10367 } 10368 10369 // Darwin passes an undocumented fourth argument of type char**. If 10370 // other platforms start sprouting these, the logic below will start 10371 // getting shifty. 10372 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10373 HasExtraParameters = false; 10374 10375 if (HasExtraParameters) { 10376 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10377 FD->setInvalidDecl(true); 10378 nparams = 3; 10379 } 10380 10381 // FIXME: a lot of the following diagnostics would be improved 10382 // if we had some location information about types. 10383 10384 QualType CharPP = 10385 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10386 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10387 10388 for (unsigned i = 0; i < nparams; ++i) { 10389 QualType AT = FTP->getParamType(i); 10390 10391 bool mismatch = true; 10392 10393 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10394 mismatch = false; 10395 else if (Expected[i] == CharPP) { 10396 // As an extension, the following forms are okay: 10397 // char const ** 10398 // char const * const * 10399 // char * const * 10400 10401 QualifierCollector qs; 10402 const PointerType* PT; 10403 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10404 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10405 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10406 Context.CharTy)) { 10407 qs.removeConst(); 10408 mismatch = !qs.empty(); 10409 } 10410 } 10411 10412 if (mismatch) { 10413 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10414 // TODO: suggest replacing given type with expected type 10415 FD->setInvalidDecl(true); 10416 } 10417 } 10418 10419 if (nparams == 1 && !FD->isInvalidDecl()) { 10420 Diag(FD->getLocation(), diag::warn_main_one_arg); 10421 } 10422 10423 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10424 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10425 FD->setInvalidDecl(); 10426 } 10427 } 10428 10429 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10430 QualType T = FD->getType(); 10431 assert(T->isFunctionType() && "function decl is not of function type"); 10432 const FunctionType *FT = T->castAs<FunctionType>(); 10433 10434 // Set an implicit return of 'zero' if the function can return some integral, 10435 // enumeration, pointer or nullptr type. 10436 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10437 FT->getReturnType()->isAnyPointerType() || 10438 FT->getReturnType()->isNullPtrType()) 10439 // DllMain is exempt because a return value of zero means it failed. 10440 if (FD->getName() != "DllMain") 10441 FD->setHasImplicitReturnZero(true); 10442 10443 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10444 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10445 FD->setInvalidDecl(); 10446 } 10447 } 10448 10449 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10450 // FIXME: Need strict checking. In C89, we need to check for 10451 // any assignment, increment, decrement, function-calls, or 10452 // commas outside of a sizeof. In C99, it's the same list, 10453 // except that the aforementioned are allowed in unevaluated 10454 // expressions. Everything else falls under the 10455 // "may accept other forms of constant expressions" exception. 10456 // (We never end up here for C++, so the constant expression 10457 // rules there don't matter.) 10458 const Expr *Culprit; 10459 if (Init->isConstantInitializer(Context, false, &Culprit)) 10460 return false; 10461 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10462 << Culprit->getSourceRange(); 10463 return true; 10464 } 10465 10466 namespace { 10467 // Visits an initialization expression to see if OrigDecl is evaluated in 10468 // its own initialization and throws a warning if it does. 10469 class SelfReferenceChecker 10470 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10471 Sema &S; 10472 Decl *OrigDecl; 10473 bool isRecordType; 10474 bool isPODType; 10475 bool isReferenceType; 10476 10477 bool isInitList; 10478 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10479 10480 public: 10481 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10482 10483 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10484 S(S), OrigDecl(OrigDecl) { 10485 isPODType = false; 10486 isRecordType = false; 10487 isReferenceType = false; 10488 isInitList = false; 10489 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10490 isPODType = VD->getType().isPODType(S.Context); 10491 isRecordType = VD->getType()->isRecordType(); 10492 isReferenceType = VD->getType()->isReferenceType(); 10493 } 10494 } 10495 10496 // For most expressions, just call the visitor. For initializer lists, 10497 // track the index of the field being initialized since fields are 10498 // initialized in order allowing use of previously initialized fields. 10499 void CheckExpr(Expr *E) { 10500 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10501 if (!InitList) { 10502 Visit(E); 10503 return; 10504 } 10505 10506 // Track and increment the index here. 10507 isInitList = true; 10508 InitFieldIndex.push_back(0); 10509 for (auto Child : InitList->children()) { 10510 CheckExpr(cast<Expr>(Child)); 10511 ++InitFieldIndex.back(); 10512 } 10513 InitFieldIndex.pop_back(); 10514 } 10515 10516 // Returns true if MemberExpr is checked and no further checking is needed. 10517 // Returns false if additional checking is required. 10518 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10519 llvm::SmallVector<FieldDecl*, 4> Fields; 10520 Expr *Base = E; 10521 bool ReferenceField = false; 10522 10523 // Get the field members used. 10524 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10525 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10526 if (!FD) 10527 return false; 10528 Fields.push_back(FD); 10529 if (FD->getType()->isReferenceType()) 10530 ReferenceField = true; 10531 Base = ME->getBase()->IgnoreParenImpCasts(); 10532 } 10533 10534 // Keep checking only if the base Decl is the same. 10535 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10536 if (!DRE || DRE->getDecl() != OrigDecl) 10537 return false; 10538 10539 // A reference field can be bound to an unininitialized field. 10540 if (CheckReference && !ReferenceField) 10541 return true; 10542 10543 // Convert FieldDecls to their index number. 10544 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10545 for (const FieldDecl *I : llvm::reverse(Fields)) 10546 UsedFieldIndex.push_back(I->getFieldIndex()); 10547 10548 // See if a warning is needed by checking the first difference in index 10549 // numbers. If field being used has index less than the field being 10550 // initialized, then the use is safe. 10551 for (auto UsedIter = UsedFieldIndex.begin(), 10552 UsedEnd = UsedFieldIndex.end(), 10553 OrigIter = InitFieldIndex.begin(), 10554 OrigEnd = InitFieldIndex.end(); 10555 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10556 if (*UsedIter < *OrigIter) 10557 return true; 10558 if (*UsedIter > *OrigIter) 10559 break; 10560 } 10561 10562 // TODO: Add a different warning which will print the field names. 10563 HandleDeclRefExpr(DRE); 10564 return true; 10565 } 10566 10567 // For most expressions, the cast is directly above the DeclRefExpr. 10568 // For conditional operators, the cast can be outside the conditional 10569 // operator if both expressions are DeclRefExpr's. 10570 void HandleValue(Expr *E) { 10571 E = E->IgnoreParens(); 10572 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10573 HandleDeclRefExpr(DRE); 10574 return; 10575 } 10576 10577 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10578 Visit(CO->getCond()); 10579 HandleValue(CO->getTrueExpr()); 10580 HandleValue(CO->getFalseExpr()); 10581 return; 10582 } 10583 10584 if (BinaryConditionalOperator *BCO = 10585 dyn_cast<BinaryConditionalOperator>(E)) { 10586 Visit(BCO->getCond()); 10587 HandleValue(BCO->getFalseExpr()); 10588 return; 10589 } 10590 10591 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10592 HandleValue(OVE->getSourceExpr()); 10593 return; 10594 } 10595 10596 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10597 if (BO->getOpcode() == BO_Comma) { 10598 Visit(BO->getLHS()); 10599 HandleValue(BO->getRHS()); 10600 return; 10601 } 10602 } 10603 10604 if (isa<MemberExpr>(E)) { 10605 if (isInitList) { 10606 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10607 false /*CheckReference*/)) 10608 return; 10609 } 10610 10611 Expr *Base = E->IgnoreParenImpCasts(); 10612 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10613 // Check for static member variables and don't warn on them. 10614 if (!isa<FieldDecl>(ME->getMemberDecl())) 10615 return; 10616 Base = ME->getBase()->IgnoreParenImpCasts(); 10617 } 10618 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10619 HandleDeclRefExpr(DRE); 10620 return; 10621 } 10622 10623 Visit(E); 10624 } 10625 10626 // Reference types not handled in HandleValue are handled here since all 10627 // uses of references are bad, not just r-value uses. 10628 void VisitDeclRefExpr(DeclRefExpr *E) { 10629 if (isReferenceType) 10630 HandleDeclRefExpr(E); 10631 } 10632 10633 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10634 if (E->getCastKind() == CK_LValueToRValue) { 10635 HandleValue(E->getSubExpr()); 10636 return; 10637 } 10638 10639 Inherited::VisitImplicitCastExpr(E); 10640 } 10641 10642 void VisitMemberExpr(MemberExpr *E) { 10643 if (isInitList) { 10644 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10645 return; 10646 } 10647 10648 // Don't warn on arrays since they can be treated as pointers. 10649 if (E->getType()->canDecayToPointerType()) return; 10650 10651 // Warn when a non-static method call is followed by non-static member 10652 // field accesses, which is followed by a DeclRefExpr. 10653 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10654 bool Warn = (MD && !MD->isStatic()); 10655 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10656 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10657 if (!isa<FieldDecl>(ME->getMemberDecl())) 10658 Warn = false; 10659 Base = ME->getBase()->IgnoreParenImpCasts(); 10660 } 10661 10662 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10663 if (Warn) 10664 HandleDeclRefExpr(DRE); 10665 return; 10666 } 10667 10668 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10669 // Visit that expression. 10670 Visit(Base); 10671 } 10672 10673 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10674 Expr *Callee = E->getCallee(); 10675 10676 if (isa<UnresolvedLookupExpr>(Callee)) 10677 return Inherited::VisitCXXOperatorCallExpr(E); 10678 10679 Visit(Callee); 10680 for (auto Arg: E->arguments()) 10681 HandleValue(Arg->IgnoreParenImpCasts()); 10682 } 10683 10684 void VisitUnaryOperator(UnaryOperator *E) { 10685 // For POD record types, addresses of its own members are well-defined. 10686 if (E->getOpcode() == UO_AddrOf && isRecordType && 10687 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10688 if (!isPODType) 10689 HandleValue(E->getSubExpr()); 10690 return; 10691 } 10692 10693 if (E->isIncrementDecrementOp()) { 10694 HandleValue(E->getSubExpr()); 10695 return; 10696 } 10697 10698 Inherited::VisitUnaryOperator(E); 10699 } 10700 10701 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10702 10703 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10704 if (E->getConstructor()->isCopyConstructor()) { 10705 Expr *ArgExpr = E->getArg(0); 10706 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10707 if (ILE->getNumInits() == 1) 10708 ArgExpr = ILE->getInit(0); 10709 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10710 if (ICE->getCastKind() == CK_NoOp) 10711 ArgExpr = ICE->getSubExpr(); 10712 HandleValue(ArgExpr); 10713 return; 10714 } 10715 Inherited::VisitCXXConstructExpr(E); 10716 } 10717 10718 void VisitCallExpr(CallExpr *E) { 10719 // Treat std::move as a use. 10720 if (E->isCallToStdMove()) { 10721 HandleValue(E->getArg(0)); 10722 return; 10723 } 10724 10725 Inherited::VisitCallExpr(E); 10726 } 10727 10728 void VisitBinaryOperator(BinaryOperator *E) { 10729 if (E->isCompoundAssignmentOp()) { 10730 HandleValue(E->getLHS()); 10731 Visit(E->getRHS()); 10732 return; 10733 } 10734 10735 Inherited::VisitBinaryOperator(E); 10736 } 10737 10738 // A custom visitor for BinaryConditionalOperator is needed because the 10739 // regular visitor would check the condition and true expression separately 10740 // but both point to the same place giving duplicate diagnostics. 10741 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10742 Visit(E->getCond()); 10743 Visit(E->getFalseExpr()); 10744 } 10745 10746 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10747 Decl* ReferenceDecl = DRE->getDecl(); 10748 if (OrigDecl != ReferenceDecl) return; 10749 unsigned diag; 10750 if (isReferenceType) { 10751 diag = diag::warn_uninit_self_reference_in_reference_init; 10752 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10753 diag = diag::warn_static_self_reference_in_init; 10754 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10755 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10756 DRE->getDecl()->getType()->isRecordType()) { 10757 diag = diag::warn_uninit_self_reference_in_init; 10758 } else { 10759 // Local variables will be handled by the CFG analysis. 10760 return; 10761 } 10762 10763 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 10764 S.PDiag(diag) 10765 << DRE->getDecl() << OrigDecl->getLocation() 10766 << DRE->getSourceRange()); 10767 } 10768 }; 10769 10770 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10771 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10772 bool DirectInit) { 10773 // Parameters arguments are occassionially constructed with itself, 10774 // for instance, in recursive functions. Skip them. 10775 if (isa<ParmVarDecl>(OrigDecl)) 10776 return; 10777 10778 E = E->IgnoreParens(); 10779 10780 // Skip checking T a = a where T is not a record or reference type. 10781 // Doing so is a way to silence uninitialized warnings. 10782 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10783 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10784 if (ICE->getCastKind() == CK_LValueToRValue) 10785 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10786 if (DRE->getDecl() == OrigDecl) 10787 return; 10788 10789 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10790 } 10791 } // end anonymous namespace 10792 10793 namespace { 10794 // Simple wrapper to add the name of a variable or (if no variable is 10795 // available) a DeclarationName into a diagnostic. 10796 struct VarDeclOrName { 10797 VarDecl *VDecl; 10798 DeclarationName Name; 10799 10800 friend const Sema::SemaDiagnosticBuilder & 10801 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10802 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10803 } 10804 }; 10805 } // end anonymous namespace 10806 10807 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10808 DeclarationName Name, QualType Type, 10809 TypeSourceInfo *TSI, 10810 SourceRange Range, bool DirectInit, 10811 Expr *Init) { 10812 bool IsInitCapture = !VDecl; 10813 assert((!VDecl || !VDecl->isInitCapture()) && 10814 "init captures are expected to be deduced prior to initialization"); 10815 10816 VarDeclOrName VN{VDecl, Name}; 10817 10818 DeducedType *Deduced = Type->getContainedDeducedType(); 10819 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10820 10821 // C++11 [dcl.spec.auto]p3 10822 if (!Init) { 10823 assert(VDecl && "no init for init capture deduction?"); 10824 10825 // Except for class argument deduction, and then for an initializing 10826 // declaration only, i.e. no static at class scope or extern. 10827 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10828 VDecl->hasExternalStorage() || 10829 VDecl->isStaticDataMember()) { 10830 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10831 << VDecl->getDeclName() << Type; 10832 return QualType(); 10833 } 10834 } 10835 10836 ArrayRef<Expr*> DeduceInits; 10837 if (Init) 10838 DeduceInits = Init; 10839 10840 if (DirectInit) { 10841 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10842 DeduceInits = PL->exprs(); 10843 } 10844 10845 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10846 assert(VDecl && "non-auto type for init capture deduction?"); 10847 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10848 InitializationKind Kind = InitializationKind::CreateForInit( 10849 VDecl->getLocation(), DirectInit, Init); 10850 // FIXME: Initialization should not be taking a mutable list of inits. 10851 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10852 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10853 InitsCopy); 10854 } 10855 10856 if (DirectInit) { 10857 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10858 DeduceInits = IL->inits(); 10859 } 10860 10861 // Deduction only works if we have exactly one source expression. 10862 if (DeduceInits.empty()) { 10863 // It isn't possible to write this directly, but it is possible to 10864 // end up in this situation with "auto x(some_pack...);" 10865 Diag(Init->getBeginLoc(), IsInitCapture 10866 ? diag::err_init_capture_no_expression 10867 : diag::err_auto_var_init_no_expression) 10868 << VN << Type << Range; 10869 return QualType(); 10870 } 10871 10872 if (DeduceInits.size() > 1) { 10873 Diag(DeduceInits[1]->getBeginLoc(), 10874 IsInitCapture ? diag::err_init_capture_multiple_expressions 10875 : diag::err_auto_var_init_multiple_expressions) 10876 << VN << Type << Range; 10877 return QualType(); 10878 } 10879 10880 Expr *DeduceInit = DeduceInits[0]; 10881 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10882 Diag(Init->getBeginLoc(), IsInitCapture 10883 ? diag::err_init_capture_paren_braces 10884 : diag::err_auto_var_init_paren_braces) 10885 << isa<InitListExpr>(Init) << VN << Type << Range; 10886 return QualType(); 10887 } 10888 10889 // Expressions default to 'id' when we're in a debugger. 10890 bool DefaultedAnyToId = false; 10891 if (getLangOpts().DebuggerCastResultToId && 10892 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10893 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10894 if (Result.isInvalid()) { 10895 return QualType(); 10896 } 10897 Init = Result.get(); 10898 DefaultedAnyToId = true; 10899 } 10900 10901 // C++ [dcl.decomp]p1: 10902 // If the assignment-expression [...] has array type A and no ref-qualifier 10903 // is present, e has type cv A 10904 if (VDecl && isa<DecompositionDecl>(VDecl) && 10905 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10906 DeduceInit->getType()->isConstantArrayType()) 10907 return Context.getQualifiedType(DeduceInit->getType(), 10908 Type.getQualifiers()); 10909 10910 QualType DeducedType; 10911 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10912 if (!IsInitCapture) 10913 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10914 else if (isa<InitListExpr>(Init)) 10915 Diag(Range.getBegin(), 10916 diag::err_init_capture_deduction_failure_from_init_list) 10917 << VN 10918 << (DeduceInit->getType().isNull() ? TSI->getType() 10919 : DeduceInit->getType()) 10920 << DeduceInit->getSourceRange(); 10921 else 10922 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10923 << VN << TSI->getType() 10924 << (DeduceInit->getType().isNull() ? TSI->getType() 10925 : DeduceInit->getType()) 10926 << DeduceInit->getSourceRange(); 10927 } 10928 10929 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10930 // 'id' instead of a specific object type prevents most of our usual 10931 // checks. 10932 // We only want to warn outside of template instantiations, though: 10933 // inside a template, the 'id' could have come from a parameter. 10934 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10935 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10936 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10937 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10938 } 10939 10940 return DeducedType; 10941 } 10942 10943 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10944 Expr *Init) { 10945 QualType DeducedType = deduceVarTypeFromInitializer( 10946 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10947 VDecl->getSourceRange(), DirectInit, Init); 10948 if (DeducedType.isNull()) { 10949 VDecl->setInvalidDecl(); 10950 return true; 10951 } 10952 10953 VDecl->setType(DeducedType); 10954 assert(VDecl->isLinkageValid()); 10955 10956 // In ARC, infer lifetime. 10957 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10958 VDecl->setInvalidDecl(); 10959 10960 // If this is a redeclaration, check that the type we just deduced matches 10961 // the previously declared type. 10962 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10963 // We never need to merge the type, because we cannot form an incomplete 10964 // array of auto, nor deduce such a type. 10965 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10966 } 10967 10968 // Check the deduced type is valid for a variable declaration. 10969 CheckVariableDeclarationType(VDecl); 10970 return VDecl->isInvalidDecl(); 10971 } 10972 10973 /// AddInitializerToDecl - Adds the initializer Init to the 10974 /// declaration dcl. If DirectInit is true, this is C++ direct 10975 /// initialization rather than copy initialization. 10976 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10977 // If there is no declaration, there was an error parsing it. Just ignore 10978 // the initializer. 10979 if (!RealDecl || RealDecl->isInvalidDecl()) { 10980 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10981 return; 10982 } 10983 10984 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10985 // Pure-specifiers are handled in ActOnPureSpecifier. 10986 Diag(Method->getLocation(), diag::err_member_function_initialization) 10987 << Method->getDeclName() << Init->getSourceRange(); 10988 Method->setInvalidDecl(); 10989 return; 10990 } 10991 10992 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10993 if (!VDecl) { 10994 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10995 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10996 RealDecl->setInvalidDecl(); 10997 return; 10998 } 10999 11000 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11001 if (VDecl->getType()->isUndeducedType()) { 11002 // Attempt typo correction early so that the type of the init expression can 11003 // be deduced based on the chosen correction if the original init contains a 11004 // TypoExpr. 11005 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11006 if (!Res.isUsable()) { 11007 RealDecl->setInvalidDecl(); 11008 return; 11009 } 11010 Init = Res.get(); 11011 11012 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11013 return; 11014 } 11015 11016 // dllimport cannot be used on variable definitions. 11017 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11018 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11019 VDecl->setInvalidDecl(); 11020 return; 11021 } 11022 11023 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11024 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11025 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11026 VDecl->setInvalidDecl(); 11027 return; 11028 } 11029 11030 if (!VDecl->getType()->isDependentType()) { 11031 // A definition must end up with a complete type, which means it must be 11032 // complete with the restriction that an array type might be completed by 11033 // the initializer; note that later code assumes this restriction. 11034 QualType BaseDeclType = VDecl->getType(); 11035 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11036 BaseDeclType = Array->getElementType(); 11037 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11038 diag::err_typecheck_decl_incomplete_type)) { 11039 RealDecl->setInvalidDecl(); 11040 return; 11041 } 11042 11043 // The variable can not have an abstract class type. 11044 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11045 diag::err_abstract_type_in_decl, 11046 AbstractVariableType)) 11047 VDecl->setInvalidDecl(); 11048 } 11049 11050 // If adding the initializer will turn this declaration into a definition, 11051 // and we already have a definition for this variable, diagnose or otherwise 11052 // handle the situation. 11053 VarDecl *Def; 11054 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11055 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11056 !VDecl->isThisDeclarationADemotedDefinition() && 11057 checkVarDeclRedefinition(Def, VDecl)) 11058 return; 11059 11060 if (getLangOpts().CPlusPlus) { 11061 // C++ [class.static.data]p4 11062 // If a static data member is of const integral or const 11063 // enumeration type, its declaration in the class definition can 11064 // specify a constant-initializer which shall be an integral 11065 // constant expression (5.19). In that case, the member can appear 11066 // in integral constant expressions. The member shall still be 11067 // defined in a namespace scope if it is used in the program and the 11068 // namespace scope definition shall not contain an initializer. 11069 // 11070 // We already performed a redefinition check above, but for static 11071 // data members we also need to check whether there was an in-class 11072 // declaration with an initializer. 11073 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11074 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11075 << VDecl->getDeclName(); 11076 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11077 diag::note_previous_initializer) 11078 << 0; 11079 return; 11080 } 11081 11082 if (VDecl->hasLocalStorage()) 11083 setFunctionHasBranchProtectedScope(); 11084 11085 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11086 VDecl->setInvalidDecl(); 11087 return; 11088 } 11089 } 11090 11091 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11092 // a kernel function cannot be initialized." 11093 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11094 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11095 VDecl->setInvalidDecl(); 11096 return; 11097 } 11098 11099 // Get the decls type and save a reference for later, since 11100 // CheckInitializerTypes may change it. 11101 QualType DclT = VDecl->getType(), SavT = DclT; 11102 11103 // Expressions default to 'id' when we're in a debugger 11104 // and we are assigning it to a variable of Objective-C pointer type. 11105 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11106 Init->getType() == Context.UnknownAnyTy) { 11107 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11108 if (Result.isInvalid()) { 11109 VDecl->setInvalidDecl(); 11110 return; 11111 } 11112 Init = Result.get(); 11113 } 11114 11115 // Perform the initialization. 11116 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11117 if (!VDecl->isInvalidDecl()) { 11118 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11119 InitializationKind Kind = InitializationKind::CreateForInit( 11120 VDecl->getLocation(), DirectInit, Init); 11121 11122 MultiExprArg Args = Init; 11123 if (CXXDirectInit) 11124 Args = MultiExprArg(CXXDirectInit->getExprs(), 11125 CXXDirectInit->getNumExprs()); 11126 11127 // Try to correct any TypoExprs in the initialization arguments. 11128 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11129 ExprResult Res = CorrectDelayedTyposInExpr( 11130 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11131 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11132 return Init.Failed() ? ExprError() : E; 11133 }); 11134 if (Res.isInvalid()) { 11135 VDecl->setInvalidDecl(); 11136 } else if (Res.get() != Args[Idx]) { 11137 Args[Idx] = Res.get(); 11138 } 11139 } 11140 if (VDecl->isInvalidDecl()) 11141 return; 11142 11143 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11144 /*TopLevelOfInitList=*/false, 11145 /*TreatUnavailableAsInvalid=*/false); 11146 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11147 if (Result.isInvalid()) { 11148 VDecl->setInvalidDecl(); 11149 return; 11150 } 11151 11152 Init = Result.getAs<Expr>(); 11153 } 11154 11155 // Check for self-references within variable initializers. 11156 // Variables declared within a function/method body (except for references) 11157 // are handled by a dataflow analysis. 11158 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11159 VDecl->getType()->isReferenceType()) { 11160 CheckSelfReference(*this, RealDecl, Init, DirectInit); 11161 } 11162 11163 // If the type changed, it means we had an incomplete type that was 11164 // completed by the initializer. For example: 11165 // int ary[] = { 1, 3, 5 }; 11166 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 11167 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 11168 VDecl->setType(DclT); 11169 11170 if (!VDecl->isInvalidDecl()) { 11171 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 11172 11173 if (VDecl->hasAttr<BlocksAttr>()) 11174 checkRetainCycles(VDecl, Init); 11175 11176 // It is safe to assign a weak reference into a strong variable. 11177 // Although this code can still have problems: 11178 // id x = self.weakProp; 11179 // id y = self.weakProp; 11180 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11181 // paths through the function. This should be revisited if 11182 // -Wrepeated-use-of-weak is made flow-sensitive. 11183 if (FunctionScopeInfo *FSI = getCurFunction()) 11184 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 11185 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 11186 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11187 Init->getBeginLoc())) 11188 FSI->markSafeWeakUse(Init); 11189 } 11190 11191 // The initialization is usually a full-expression. 11192 // 11193 // FIXME: If this is a braced initialization of an aggregate, it is not 11194 // an expression, and each individual field initializer is a separate 11195 // full-expression. For instance, in: 11196 // 11197 // struct Temp { ~Temp(); }; 11198 // struct S { S(Temp); }; 11199 // struct T { S a, b; } t = { Temp(), Temp() } 11200 // 11201 // we should destroy the first Temp before constructing the second. 11202 ExprResult Result = 11203 ActOnFinishFullExpr(Init, VDecl->getLocation(), 11204 /*DiscardedValue*/ false, VDecl->isConstexpr()); 11205 if (Result.isInvalid()) { 11206 VDecl->setInvalidDecl(); 11207 return; 11208 } 11209 Init = Result.get(); 11210 11211 // Attach the initializer to the decl. 11212 VDecl->setInit(Init); 11213 11214 if (VDecl->isLocalVarDecl()) { 11215 // Don't check the initializer if the declaration is malformed. 11216 if (VDecl->isInvalidDecl()) { 11217 // do nothing 11218 11219 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 11220 // This is true even in OpenCL C++. 11221 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 11222 CheckForConstantInitializer(Init, DclT); 11223 11224 // Otherwise, C++ does not restrict the initializer. 11225 } else if (getLangOpts().CPlusPlus) { 11226 // do nothing 11227 11228 // C99 6.7.8p4: All the expressions in an initializer for an object that has 11229 // static storage duration shall be constant expressions or string literals. 11230 } else if (VDecl->getStorageClass() == SC_Static) { 11231 CheckForConstantInitializer(Init, DclT); 11232 11233 // C89 is stricter than C99 for aggregate initializers. 11234 // C89 6.5.7p3: All the expressions [...] in an initializer list 11235 // for an object that has aggregate or union type shall be 11236 // constant expressions. 11237 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 11238 isa<InitListExpr>(Init)) { 11239 const Expr *Culprit; 11240 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 11241 Diag(Culprit->getExprLoc(), 11242 diag::ext_aggregate_init_not_constant) 11243 << Culprit->getSourceRange(); 11244 } 11245 } 11246 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 11247 VDecl->getLexicalDeclContext()->isRecord()) { 11248 // This is an in-class initialization for a static data member, e.g., 11249 // 11250 // struct S { 11251 // static const int value = 17; 11252 // }; 11253 11254 // C++ [class.mem]p4: 11255 // A member-declarator can contain a constant-initializer only 11256 // if it declares a static member (9.4) of const integral or 11257 // const enumeration type, see 9.4.2. 11258 // 11259 // C++11 [class.static.data]p3: 11260 // If a non-volatile non-inline const static data member is of integral 11261 // or enumeration type, its declaration in the class definition can 11262 // specify a brace-or-equal-initializer in which every initializer-clause 11263 // that is an assignment-expression is a constant expression. A static 11264 // data member of literal type can be declared in the class definition 11265 // with the constexpr specifier; if so, its declaration shall specify a 11266 // brace-or-equal-initializer in which every initializer-clause that is 11267 // an assignment-expression is a constant expression. 11268 11269 // Do nothing on dependent types. 11270 if (DclT->isDependentType()) { 11271 11272 // Allow any 'static constexpr' members, whether or not they are of literal 11273 // type. We separately check that every constexpr variable is of literal 11274 // type. 11275 } else if (VDecl->isConstexpr()) { 11276 11277 // Require constness. 11278 } else if (!DclT.isConstQualified()) { 11279 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 11280 << Init->getSourceRange(); 11281 VDecl->setInvalidDecl(); 11282 11283 // We allow integer constant expressions in all cases. 11284 } else if (DclT->isIntegralOrEnumerationType()) { 11285 // Check whether the expression is a constant expression. 11286 SourceLocation Loc; 11287 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 11288 // In C++11, a non-constexpr const static data member with an 11289 // in-class initializer cannot be volatile. 11290 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 11291 else if (Init->isValueDependent()) 11292 ; // Nothing to check. 11293 else if (Init->isIntegerConstantExpr(Context, &Loc)) 11294 ; // Ok, it's an ICE! 11295 else if (Init->getType()->isScopedEnumeralType() && 11296 Init->isCXX11ConstantExpr(Context)) 11297 ; // Ok, it is a scoped-enum constant expression. 11298 else if (Init->isEvaluatable(Context)) { 11299 // If we can constant fold the initializer through heroics, accept it, 11300 // but report this as a use of an extension for -pedantic. 11301 Diag(Loc, diag::ext_in_class_initializer_non_constant) 11302 << Init->getSourceRange(); 11303 } else { 11304 // Otherwise, this is some crazy unknown case. Report the issue at the 11305 // location provided by the isIntegerConstantExpr failed check. 11306 Diag(Loc, diag::err_in_class_initializer_non_constant) 11307 << Init->getSourceRange(); 11308 VDecl->setInvalidDecl(); 11309 } 11310 11311 // We allow foldable floating-point constants as an extension. 11312 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 11313 // In C++98, this is a GNU extension. In C++11, it is not, but we support 11314 // it anyway and provide a fixit to add the 'constexpr'. 11315 if (getLangOpts().CPlusPlus11) { 11316 Diag(VDecl->getLocation(), 11317 diag::ext_in_class_initializer_float_type_cxx11) 11318 << DclT << Init->getSourceRange(); 11319 Diag(VDecl->getBeginLoc(), 11320 diag::note_in_class_initializer_float_type_cxx11) 11321 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11322 } else { 11323 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 11324 << DclT << Init->getSourceRange(); 11325 11326 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 11327 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 11328 << Init->getSourceRange(); 11329 VDecl->setInvalidDecl(); 11330 } 11331 } 11332 11333 // Suggest adding 'constexpr' in C++11 for literal types. 11334 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 11335 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 11336 << DclT << Init->getSourceRange() 11337 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11338 VDecl->setConstexpr(true); 11339 11340 } else { 11341 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 11342 << DclT << Init->getSourceRange(); 11343 VDecl->setInvalidDecl(); 11344 } 11345 } else if (VDecl->isFileVarDecl()) { 11346 // In C, extern is typically used to avoid tentative definitions when 11347 // declaring variables in headers, but adding an intializer makes it a 11348 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 11349 // In C++, extern is often used to give implictly static const variables 11350 // external linkage, so don't warn in that case. If selectany is present, 11351 // this might be header code intended for C and C++ inclusion, so apply the 11352 // C++ rules. 11353 if (VDecl->getStorageClass() == SC_Extern && 11354 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 11355 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 11356 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 11357 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 11358 Diag(VDecl->getLocation(), diag::warn_extern_init); 11359 11360 // C99 6.7.8p4. All file scoped initializers need to be constant. 11361 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 11362 CheckForConstantInitializer(Init, DclT); 11363 } 11364 11365 // We will represent direct-initialization similarly to copy-initialization: 11366 // int x(1); -as-> int x = 1; 11367 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 11368 // 11369 // Clients that want to distinguish between the two forms, can check for 11370 // direct initializer using VarDecl::getInitStyle(). 11371 // A major benefit is that clients that don't particularly care about which 11372 // exactly form was it (like the CodeGen) can handle both cases without 11373 // special case code. 11374 11375 // C++ 8.5p11: 11376 // The form of initialization (using parentheses or '=') is generally 11377 // insignificant, but does matter when the entity being initialized has a 11378 // class type. 11379 if (CXXDirectInit) { 11380 assert(DirectInit && "Call-style initializer must be direct init."); 11381 VDecl->setInitStyle(VarDecl::CallInit); 11382 } else if (DirectInit) { 11383 // This must be list-initialization. No other way is direct-initialization. 11384 VDecl->setInitStyle(VarDecl::ListInit); 11385 } 11386 11387 CheckCompleteVariableDeclaration(VDecl); 11388 } 11389 11390 /// ActOnInitializerError - Given that there was an error parsing an 11391 /// initializer for the given declaration, try to return to some form 11392 /// of sanity. 11393 void Sema::ActOnInitializerError(Decl *D) { 11394 // Our main concern here is re-establishing invariants like "a 11395 // variable's type is either dependent or complete". 11396 if (!D || D->isInvalidDecl()) return; 11397 11398 VarDecl *VD = dyn_cast<VarDecl>(D); 11399 if (!VD) return; 11400 11401 // Bindings are not usable if we can't make sense of the initializer. 11402 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11403 for (auto *BD : DD->bindings()) 11404 BD->setInvalidDecl(); 11405 11406 // Auto types are meaningless if we can't make sense of the initializer. 11407 if (ParsingInitForAutoVars.count(D)) { 11408 D->setInvalidDecl(); 11409 return; 11410 } 11411 11412 QualType Ty = VD->getType(); 11413 if (Ty->isDependentType()) return; 11414 11415 // Require a complete type. 11416 if (RequireCompleteType(VD->getLocation(), 11417 Context.getBaseElementType(Ty), 11418 diag::err_typecheck_decl_incomplete_type)) { 11419 VD->setInvalidDecl(); 11420 return; 11421 } 11422 11423 // Require a non-abstract type. 11424 if (RequireNonAbstractType(VD->getLocation(), Ty, 11425 diag::err_abstract_type_in_decl, 11426 AbstractVariableType)) { 11427 VD->setInvalidDecl(); 11428 return; 11429 } 11430 11431 // Don't bother complaining about constructors or destructors, 11432 // though. 11433 } 11434 11435 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11436 // If there is no declaration, there was an error parsing it. Just ignore it. 11437 if (!RealDecl) 11438 return; 11439 11440 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11441 QualType Type = Var->getType(); 11442 11443 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11444 if (isa<DecompositionDecl>(RealDecl)) { 11445 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11446 Var->setInvalidDecl(); 11447 return; 11448 } 11449 11450 if (Type->isUndeducedType() && 11451 DeduceVariableDeclarationType(Var, false, nullptr)) 11452 return; 11453 11454 // C++11 [class.static.data]p3: A static data member can be declared with 11455 // the constexpr specifier; if so, its declaration shall specify 11456 // a brace-or-equal-initializer. 11457 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11458 // the definition of a variable [...] or the declaration of a static data 11459 // member. 11460 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11461 !Var->isThisDeclarationADemotedDefinition()) { 11462 if (Var->isStaticDataMember()) { 11463 // C++1z removes the relevant rule; the in-class declaration is always 11464 // a definition there. 11465 if (!getLangOpts().CPlusPlus17) { 11466 Diag(Var->getLocation(), 11467 diag::err_constexpr_static_mem_var_requires_init) 11468 << Var->getDeclName(); 11469 Var->setInvalidDecl(); 11470 return; 11471 } 11472 } else { 11473 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11474 Var->setInvalidDecl(); 11475 return; 11476 } 11477 } 11478 11479 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11480 // be initialized. 11481 if (!Var->isInvalidDecl() && 11482 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11483 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11484 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11485 Var->setInvalidDecl(); 11486 return; 11487 } 11488 11489 switch (Var->isThisDeclarationADefinition()) { 11490 case VarDecl::Definition: 11491 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11492 break; 11493 11494 // We have an out-of-line definition of a static data member 11495 // that has an in-class initializer, so we type-check this like 11496 // a declaration. 11497 // 11498 LLVM_FALLTHROUGH; 11499 11500 case VarDecl::DeclarationOnly: 11501 // It's only a declaration. 11502 11503 // Block scope. C99 6.7p7: If an identifier for an object is 11504 // declared with no linkage (C99 6.2.2p6), the type for the 11505 // object shall be complete. 11506 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11507 !Var->hasLinkage() && !Var->isInvalidDecl() && 11508 RequireCompleteType(Var->getLocation(), Type, 11509 diag::err_typecheck_decl_incomplete_type)) 11510 Var->setInvalidDecl(); 11511 11512 // Make sure that the type is not abstract. 11513 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11514 RequireNonAbstractType(Var->getLocation(), Type, 11515 diag::err_abstract_type_in_decl, 11516 AbstractVariableType)) 11517 Var->setInvalidDecl(); 11518 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11519 Var->getStorageClass() == SC_PrivateExtern) { 11520 Diag(Var->getLocation(), diag::warn_private_extern); 11521 Diag(Var->getLocation(), diag::note_private_extern); 11522 } 11523 11524 return; 11525 11526 case VarDecl::TentativeDefinition: 11527 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11528 // object that has file scope without an initializer, and without a 11529 // storage-class specifier or with the storage-class specifier "static", 11530 // constitutes a tentative definition. Note: A tentative definition with 11531 // external linkage is valid (C99 6.2.2p5). 11532 if (!Var->isInvalidDecl()) { 11533 if (const IncompleteArrayType *ArrayT 11534 = Context.getAsIncompleteArrayType(Type)) { 11535 if (RequireCompleteType(Var->getLocation(), 11536 ArrayT->getElementType(), 11537 diag::err_illegal_decl_array_incomplete_type)) 11538 Var->setInvalidDecl(); 11539 } else if (Var->getStorageClass() == SC_Static) { 11540 // C99 6.9.2p3: If the declaration of an identifier for an object is 11541 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11542 // declared type shall not be an incomplete type. 11543 // NOTE: code such as the following 11544 // static struct s; 11545 // struct s { int a; }; 11546 // is accepted by gcc. Hence here we issue a warning instead of 11547 // an error and we do not invalidate the static declaration. 11548 // NOTE: to avoid multiple warnings, only check the first declaration. 11549 if (Var->isFirstDecl()) 11550 RequireCompleteType(Var->getLocation(), Type, 11551 diag::ext_typecheck_decl_incomplete_type); 11552 } 11553 } 11554 11555 // Record the tentative definition; we're done. 11556 if (!Var->isInvalidDecl()) 11557 TentativeDefinitions.push_back(Var); 11558 return; 11559 } 11560 11561 // Provide a specific diagnostic for uninitialized variable 11562 // definitions with incomplete array type. 11563 if (Type->isIncompleteArrayType()) { 11564 Diag(Var->getLocation(), 11565 diag::err_typecheck_incomplete_array_needs_initializer); 11566 Var->setInvalidDecl(); 11567 return; 11568 } 11569 11570 // Provide a specific diagnostic for uninitialized variable 11571 // definitions with reference type. 11572 if (Type->isReferenceType()) { 11573 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11574 << Var->getDeclName() 11575 << SourceRange(Var->getLocation(), Var->getLocation()); 11576 Var->setInvalidDecl(); 11577 return; 11578 } 11579 11580 // Do not attempt to type-check the default initializer for a 11581 // variable with dependent type. 11582 if (Type->isDependentType()) 11583 return; 11584 11585 if (Var->isInvalidDecl()) 11586 return; 11587 11588 if (!Var->hasAttr<AliasAttr>()) { 11589 if (RequireCompleteType(Var->getLocation(), 11590 Context.getBaseElementType(Type), 11591 diag::err_typecheck_decl_incomplete_type)) { 11592 Var->setInvalidDecl(); 11593 return; 11594 } 11595 } else { 11596 return; 11597 } 11598 11599 // The variable can not have an abstract class type. 11600 if (RequireNonAbstractType(Var->getLocation(), Type, 11601 diag::err_abstract_type_in_decl, 11602 AbstractVariableType)) { 11603 Var->setInvalidDecl(); 11604 return; 11605 } 11606 11607 // Check for jumps past the implicit initializer. C++0x 11608 // clarifies that this applies to a "variable with automatic 11609 // storage duration", not a "local variable". 11610 // C++11 [stmt.dcl]p3 11611 // A program that jumps from a point where a variable with automatic 11612 // storage duration is not in scope to a point where it is in scope is 11613 // ill-formed unless the variable has scalar type, class type with a 11614 // trivial default constructor and a trivial destructor, a cv-qualified 11615 // version of one of these types, or an array of one of the preceding 11616 // types and is declared without an initializer. 11617 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11618 if (const RecordType *Record 11619 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11620 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11621 // Mark the function (if we're in one) for further checking even if the 11622 // looser rules of C++11 do not require such checks, so that we can 11623 // diagnose incompatibilities with C++98. 11624 if (!CXXRecord->isPOD()) 11625 setFunctionHasBranchProtectedScope(); 11626 } 11627 } 11628 11629 // C++03 [dcl.init]p9: 11630 // If no initializer is specified for an object, and the 11631 // object is of (possibly cv-qualified) non-POD class type (or 11632 // array thereof), the object shall be default-initialized; if 11633 // the object is of const-qualified type, the underlying class 11634 // type shall have a user-declared default 11635 // constructor. Otherwise, if no initializer is specified for 11636 // a non- static object, the object and its subobjects, if 11637 // any, have an indeterminate initial value); if the object 11638 // or any of its subobjects are of const-qualified type, the 11639 // program is ill-formed. 11640 // C++0x [dcl.init]p11: 11641 // If no initializer is specified for an object, the object is 11642 // default-initialized; [...]. 11643 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11644 InitializationKind Kind 11645 = InitializationKind::CreateDefault(Var->getLocation()); 11646 11647 InitializationSequence InitSeq(*this, Entity, Kind, None); 11648 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11649 if (Init.isInvalid()) 11650 Var->setInvalidDecl(); 11651 else if (Init.get()) { 11652 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11653 // This is important for template substitution. 11654 Var->setInitStyle(VarDecl::CallInit); 11655 } 11656 11657 CheckCompleteVariableDeclaration(Var); 11658 } 11659 } 11660 11661 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11662 // If there is no declaration, there was an error parsing it. Ignore it. 11663 if (!D) 11664 return; 11665 11666 VarDecl *VD = dyn_cast<VarDecl>(D); 11667 if (!VD) { 11668 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11669 D->setInvalidDecl(); 11670 return; 11671 } 11672 11673 VD->setCXXForRangeDecl(true); 11674 11675 // for-range-declaration cannot be given a storage class specifier. 11676 int Error = -1; 11677 switch (VD->getStorageClass()) { 11678 case SC_None: 11679 break; 11680 case SC_Extern: 11681 Error = 0; 11682 break; 11683 case SC_Static: 11684 Error = 1; 11685 break; 11686 case SC_PrivateExtern: 11687 Error = 2; 11688 break; 11689 case SC_Auto: 11690 Error = 3; 11691 break; 11692 case SC_Register: 11693 Error = 4; 11694 break; 11695 } 11696 if (Error != -1) { 11697 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11698 << VD->getDeclName() << Error; 11699 D->setInvalidDecl(); 11700 } 11701 } 11702 11703 StmtResult 11704 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11705 IdentifierInfo *Ident, 11706 ParsedAttributes &Attrs, 11707 SourceLocation AttrEnd) { 11708 // C++1y [stmt.iter]p1: 11709 // A range-based for statement of the form 11710 // for ( for-range-identifier : for-range-initializer ) statement 11711 // is equivalent to 11712 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11713 DeclSpec DS(Attrs.getPool().getFactory()); 11714 11715 const char *PrevSpec; 11716 unsigned DiagID; 11717 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11718 getPrintingPolicy()); 11719 11720 Declarator D(DS, DeclaratorContext::ForContext); 11721 D.SetIdentifier(Ident, IdentLoc); 11722 D.takeAttributes(Attrs, AttrEnd); 11723 11724 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11725 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 11726 IdentLoc); 11727 Decl *Var = ActOnDeclarator(S, D); 11728 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11729 FinalizeDeclaration(Var); 11730 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11731 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11732 } 11733 11734 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11735 if (var->isInvalidDecl()) return; 11736 11737 if (getLangOpts().OpenCL) { 11738 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11739 // initialiser 11740 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11741 !var->hasInit()) { 11742 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11743 << 1 /*Init*/; 11744 var->setInvalidDecl(); 11745 return; 11746 } 11747 } 11748 11749 // In Objective-C, don't allow jumps past the implicit initialization of a 11750 // local retaining variable. 11751 if (getLangOpts().ObjC && 11752 var->hasLocalStorage()) { 11753 switch (var->getType().getObjCLifetime()) { 11754 case Qualifiers::OCL_None: 11755 case Qualifiers::OCL_ExplicitNone: 11756 case Qualifiers::OCL_Autoreleasing: 11757 break; 11758 11759 case Qualifiers::OCL_Weak: 11760 case Qualifiers::OCL_Strong: 11761 setFunctionHasBranchProtectedScope(); 11762 break; 11763 } 11764 } 11765 11766 if (var->hasLocalStorage() && 11767 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11768 setFunctionHasBranchProtectedScope(); 11769 11770 // Warn about externally-visible variables being defined without a 11771 // prior declaration. We only want to do this for global 11772 // declarations, but we also specifically need to avoid doing it for 11773 // class members because the linkage of an anonymous class can 11774 // change if it's later given a typedef name. 11775 if (var->isThisDeclarationADefinition() && 11776 var->getDeclContext()->getRedeclContext()->isFileContext() && 11777 var->isExternallyVisible() && var->hasLinkage() && 11778 !var->isInline() && !var->getDescribedVarTemplate() && 11779 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11780 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11781 var->getLocation())) { 11782 // Find a previous declaration that's not a definition. 11783 VarDecl *prev = var->getPreviousDecl(); 11784 while (prev && prev->isThisDeclarationADefinition()) 11785 prev = prev->getPreviousDecl(); 11786 11787 if (!prev) 11788 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11789 } 11790 11791 // Cache the result of checking for constant initialization. 11792 Optional<bool> CacheHasConstInit; 11793 const Expr *CacheCulprit; 11794 auto checkConstInit = [&]() mutable { 11795 if (!CacheHasConstInit) 11796 CacheHasConstInit = var->getInit()->isConstantInitializer( 11797 Context, var->getType()->isReferenceType(), &CacheCulprit); 11798 return *CacheHasConstInit; 11799 }; 11800 11801 if (var->getTLSKind() == VarDecl::TLS_Static) { 11802 if (var->getType().isDestructedType()) { 11803 // GNU C++98 edits for __thread, [basic.start.term]p3: 11804 // The type of an object with thread storage duration shall not 11805 // have a non-trivial destructor. 11806 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11807 if (getLangOpts().CPlusPlus11) 11808 Diag(var->getLocation(), diag::note_use_thread_local); 11809 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11810 if (!checkConstInit()) { 11811 // GNU C++98 edits for __thread, [basic.start.init]p4: 11812 // An object of thread storage duration shall not require dynamic 11813 // initialization. 11814 // FIXME: Need strict checking here. 11815 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11816 << CacheCulprit->getSourceRange(); 11817 if (getLangOpts().CPlusPlus11) 11818 Diag(var->getLocation(), diag::note_use_thread_local); 11819 } 11820 } 11821 } 11822 11823 // Apply section attributes and pragmas to global variables. 11824 bool GlobalStorage = var->hasGlobalStorage(); 11825 if (GlobalStorage && var->isThisDeclarationADefinition() && 11826 !inTemplateInstantiation()) { 11827 PragmaStack<StringLiteral *> *Stack = nullptr; 11828 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11829 if (var->getType().isConstQualified()) 11830 Stack = &ConstSegStack; 11831 else if (!var->getInit()) { 11832 Stack = &BSSSegStack; 11833 SectionFlags |= ASTContext::PSF_Write; 11834 } else { 11835 Stack = &DataSegStack; 11836 SectionFlags |= ASTContext::PSF_Write; 11837 } 11838 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11839 var->addAttr(SectionAttr::CreateImplicit( 11840 Context, SectionAttr::Declspec_allocate, 11841 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11842 } 11843 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11844 if (UnifySection(SA->getName(), SectionFlags, var)) 11845 var->dropAttr<SectionAttr>(); 11846 11847 // Apply the init_seg attribute if this has an initializer. If the 11848 // initializer turns out to not be dynamic, we'll end up ignoring this 11849 // attribute. 11850 if (CurInitSeg && var->getInit()) 11851 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11852 CurInitSegLoc)); 11853 } 11854 11855 // All the following checks are C++ only. 11856 if (!getLangOpts().CPlusPlus) { 11857 // If this variable must be emitted, add it as an initializer for the 11858 // current module. 11859 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11860 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11861 return; 11862 } 11863 11864 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11865 CheckCompleteDecompositionDeclaration(DD); 11866 11867 QualType type = var->getType(); 11868 if (type->isDependentType()) return; 11869 11870 if (var->hasAttr<BlocksAttr>()) 11871 getCurFunction()->addByrefBlockVar(var); 11872 11873 Expr *Init = var->getInit(); 11874 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11875 QualType baseType = Context.getBaseElementType(type); 11876 11877 if (Init && !Init->isValueDependent()) { 11878 if (var->isConstexpr()) { 11879 SmallVector<PartialDiagnosticAt, 8> Notes; 11880 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11881 SourceLocation DiagLoc = var->getLocation(); 11882 // If the note doesn't add any useful information other than a source 11883 // location, fold it into the primary diagnostic. 11884 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11885 diag::note_invalid_subexpr_in_const_expr) { 11886 DiagLoc = Notes[0].first; 11887 Notes.clear(); 11888 } 11889 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11890 << var << Init->getSourceRange(); 11891 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11892 Diag(Notes[I].first, Notes[I].second); 11893 } 11894 } else if (var->isUsableInConstantExpressions(Context)) { 11895 // Check whether the initializer of a const variable of integral or 11896 // enumeration type is an ICE now, since we can't tell whether it was 11897 // initialized by a constant expression if we check later. 11898 var->checkInitIsICE(); 11899 } 11900 11901 // Don't emit further diagnostics about constexpr globals since they 11902 // were just diagnosed. 11903 if (!var->isConstexpr() && GlobalStorage && 11904 var->hasAttr<RequireConstantInitAttr>()) { 11905 // FIXME: Need strict checking in C++03 here. 11906 bool DiagErr = getLangOpts().CPlusPlus11 11907 ? !var->checkInitIsICE() : !checkConstInit(); 11908 if (DiagErr) { 11909 auto attr = var->getAttr<RequireConstantInitAttr>(); 11910 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11911 << Init->getSourceRange(); 11912 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11913 << attr->getRange(); 11914 if (getLangOpts().CPlusPlus11) { 11915 APValue Value; 11916 SmallVector<PartialDiagnosticAt, 8> Notes; 11917 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11918 for (auto &it : Notes) 11919 Diag(it.first, it.second); 11920 } else { 11921 Diag(CacheCulprit->getExprLoc(), 11922 diag::note_invalid_subexpr_in_const_expr) 11923 << CacheCulprit->getSourceRange(); 11924 } 11925 } 11926 } 11927 else if (!var->isConstexpr() && IsGlobal && 11928 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11929 var->getLocation())) { 11930 // Warn about globals which don't have a constant initializer. Don't 11931 // warn about globals with a non-trivial destructor because we already 11932 // warned about them. 11933 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11934 if (!(RD && !RD->hasTrivialDestructor())) { 11935 if (!checkConstInit()) 11936 Diag(var->getLocation(), diag::warn_global_constructor) 11937 << Init->getSourceRange(); 11938 } 11939 } 11940 } 11941 11942 // Require the destructor. 11943 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11944 FinalizeVarWithDestructor(var, recordType); 11945 11946 // If this variable must be emitted, add it as an initializer for the current 11947 // module. 11948 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11949 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11950 } 11951 11952 /// Determines if a variable's alignment is dependent. 11953 static bool hasDependentAlignment(VarDecl *VD) { 11954 if (VD->getType()->isDependentType()) 11955 return true; 11956 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11957 if (I->isAlignmentDependent()) 11958 return true; 11959 return false; 11960 } 11961 11962 /// Check if VD needs to be dllexport/dllimport due to being in a 11963 /// dllexport/import function. 11964 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 11965 assert(VD->isStaticLocal()); 11966 11967 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11968 11969 // Find outermost function when VD is in lambda function. 11970 while (FD && !getDLLAttr(FD) && 11971 !FD->hasAttr<DLLExportStaticLocalAttr>() && 11972 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 11973 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 11974 } 11975 11976 if (!FD) 11977 return; 11978 11979 // Static locals inherit dll attributes from their function. 11980 if (Attr *A = getDLLAttr(FD)) { 11981 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11982 NewAttr->setInherited(true); 11983 VD->addAttr(NewAttr); 11984 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 11985 auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(), 11986 getASTContext(), 11987 A->getSpellingListIndex()); 11988 NewAttr->setInherited(true); 11989 VD->addAttr(NewAttr); 11990 11991 // Export this function to enforce exporting this static variable even 11992 // if it is not used in this compilation unit. 11993 if (!FD->hasAttr<DLLExportAttr>()) 11994 FD->addAttr(NewAttr); 11995 11996 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 11997 auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(), 11998 getASTContext(), 11999 A->getSpellingListIndex()); 12000 NewAttr->setInherited(true); 12001 VD->addAttr(NewAttr); 12002 } 12003 } 12004 12005 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12006 /// any semantic actions necessary after any initializer has been attached. 12007 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12008 // Note that we are no longer parsing the initializer for this declaration. 12009 ParsingInitForAutoVars.erase(ThisDecl); 12010 12011 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12012 if (!VD) 12013 return; 12014 12015 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12016 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12017 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12018 if (PragmaClangBSSSection.Valid) 12019 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 12020 PragmaClangBSSSection.SectionName, 12021 PragmaClangBSSSection.PragmaLocation)); 12022 if (PragmaClangDataSection.Valid) 12023 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 12024 PragmaClangDataSection.SectionName, 12025 PragmaClangDataSection.PragmaLocation)); 12026 if (PragmaClangRodataSection.Valid) 12027 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 12028 PragmaClangRodataSection.SectionName, 12029 PragmaClangRodataSection.PragmaLocation)); 12030 } 12031 12032 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12033 for (auto *BD : DD->bindings()) { 12034 FinalizeDeclaration(BD); 12035 } 12036 } 12037 12038 checkAttributesAfterMerging(*this, *VD); 12039 12040 // Perform TLS alignment check here after attributes attached to the variable 12041 // which may affect the alignment have been processed. Only perform the check 12042 // if the target has a maximum TLS alignment (zero means no constraints). 12043 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12044 // Protect the check so that it's not performed on dependent types and 12045 // dependent alignments (we can't determine the alignment in that case). 12046 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12047 !VD->isInvalidDecl()) { 12048 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12049 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12050 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12051 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12052 << (unsigned)MaxAlignChars.getQuantity(); 12053 } 12054 } 12055 } 12056 12057 if (VD->isStaticLocal()) { 12058 CheckStaticLocalForDllExport(VD); 12059 12060 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12061 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12062 // function, only __shared__ variables or variables without any device 12063 // memory qualifiers may be declared with static storage class. 12064 // Note: It is unclear how a function-scope non-const static variable 12065 // without device memory qualifier is implemented, therefore only static 12066 // const variable without device memory qualifier is allowed. 12067 [&]() { 12068 if (!getLangOpts().CUDA) 12069 return; 12070 if (VD->hasAttr<CUDASharedAttr>()) 12071 return; 12072 if (VD->getType().isConstQualified() && 12073 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12074 return; 12075 if (CUDADiagIfDeviceCode(VD->getLocation(), 12076 diag::err_device_static_local_var) 12077 << CurrentCUDATarget()) 12078 VD->setInvalidDecl(); 12079 }(); 12080 } 12081 } 12082 12083 // Perform check for initializers of device-side global variables. 12084 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12085 // 7.5). We must also apply the same checks to all __shared__ 12086 // variables whether they are local or not. CUDA also allows 12087 // constant initializers for __constant__ and __device__ variables. 12088 if (getLangOpts().CUDA) 12089 checkAllowedCUDAInitializer(VD); 12090 12091 // Grab the dllimport or dllexport attribute off of the VarDecl. 12092 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12093 12094 // Imported static data members cannot be defined out-of-line. 12095 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12096 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12097 VD->isThisDeclarationADefinition()) { 12098 // We allow definitions of dllimport class template static data members 12099 // with a warning. 12100 CXXRecordDecl *Context = 12101 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12102 bool IsClassTemplateMember = 12103 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12104 Context->getDescribedClassTemplate(); 12105 12106 Diag(VD->getLocation(), 12107 IsClassTemplateMember 12108 ? diag::warn_attribute_dllimport_static_field_definition 12109 : diag::err_attribute_dllimport_static_field_definition); 12110 Diag(IA->getLocation(), diag::note_attribute); 12111 if (!IsClassTemplateMember) 12112 VD->setInvalidDecl(); 12113 } 12114 } 12115 12116 // dllimport/dllexport variables cannot be thread local, their TLS index 12117 // isn't exported with the variable. 12118 if (DLLAttr && VD->getTLSKind()) { 12119 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12120 if (F && getDLLAttr(F)) { 12121 assert(VD->isStaticLocal()); 12122 // But if this is a static local in a dlimport/dllexport function, the 12123 // function will never be inlined, which means the var would never be 12124 // imported, so having it marked import/export is safe. 12125 } else { 12126 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 12127 << DLLAttr; 12128 VD->setInvalidDecl(); 12129 } 12130 } 12131 12132 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 12133 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 12134 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 12135 VD->dropAttr<UsedAttr>(); 12136 } 12137 } 12138 12139 const DeclContext *DC = VD->getDeclContext(); 12140 // If there's a #pragma GCC visibility in scope, and this isn't a class 12141 // member, set the visibility of this variable. 12142 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 12143 AddPushedVisibilityAttribute(VD); 12144 12145 // FIXME: Warn on unused var template partial specializations. 12146 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 12147 MarkUnusedFileScopedDecl(VD); 12148 12149 // Now we have parsed the initializer and can update the table of magic 12150 // tag values. 12151 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 12152 !VD->getType()->isIntegralOrEnumerationType()) 12153 return; 12154 12155 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 12156 const Expr *MagicValueExpr = VD->getInit(); 12157 if (!MagicValueExpr) { 12158 continue; 12159 } 12160 llvm::APSInt MagicValueInt; 12161 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 12162 Diag(I->getRange().getBegin(), 12163 diag::err_type_tag_for_datatype_not_ice) 12164 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12165 continue; 12166 } 12167 if (MagicValueInt.getActiveBits() > 64) { 12168 Diag(I->getRange().getBegin(), 12169 diag::err_type_tag_for_datatype_too_large) 12170 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12171 continue; 12172 } 12173 uint64_t MagicValue = MagicValueInt.getZExtValue(); 12174 RegisterTypeTagForDatatype(I->getArgumentKind(), 12175 MagicValue, 12176 I->getMatchingCType(), 12177 I->getLayoutCompatible(), 12178 I->getMustBeNull()); 12179 } 12180 } 12181 12182 static bool hasDeducedAuto(DeclaratorDecl *DD) { 12183 auto *VD = dyn_cast<VarDecl>(DD); 12184 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 12185 } 12186 12187 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 12188 ArrayRef<Decl *> Group) { 12189 SmallVector<Decl*, 8> Decls; 12190 12191 if (DS.isTypeSpecOwned()) 12192 Decls.push_back(DS.getRepAsDecl()); 12193 12194 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 12195 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 12196 bool DiagnosedMultipleDecomps = false; 12197 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 12198 bool DiagnosedNonDeducedAuto = false; 12199 12200 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12201 if (Decl *D = Group[i]) { 12202 // For declarators, there are some additional syntactic-ish checks we need 12203 // to perform. 12204 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 12205 if (!FirstDeclaratorInGroup) 12206 FirstDeclaratorInGroup = DD; 12207 if (!FirstDecompDeclaratorInGroup) 12208 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 12209 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 12210 !hasDeducedAuto(DD)) 12211 FirstNonDeducedAutoInGroup = DD; 12212 12213 if (FirstDeclaratorInGroup != DD) { 12214 // A decomposition declaration cannot be combined with any other 12215 // declaration in the same group. 12216 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 12217 Diag(FirstDecompDeclaratorInGroup->getLocation(), 12218 diag::err_decomp_decl_not_alone) 12219 << FirstDeclaratorInGroup->getSourceRange() 12220 << DD->getSourceRange(); 12221 DiagnosedMultipleDecomps = true; 12222 } 12223 12224 // A declarator that uses 'auto' in any way other than to declare a 12225 // variable with a deduced type cannot be combined with any other 12226 // declarator in the same group. 12227 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 12228 Diag(FirstNonDeducedAutoInGroup->getLocation(), 12229 diag::err_auto_non_deduced_not_alone) 12230 << FirstNonDeducedAutoInGroup->getType() 12231 ->hasAutoForTrailingReturnType() 12232 << FirstDeclaratorInGroup->getSourceRange() 12233 << DD->getSourceRange(); 12234 DiagnosedNonDeducedAuto = true; 12235 } 12236 } 12237 } 12238 12239 Decls.push_back(D); 12240 } 12241 } 12242 12243 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 12244 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 12245 handleTagNumbering(Tag, S); 12246 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 12247 getLangOpts().CPlusPlus) 12248 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 12249 } 12250 } 12251 12252 return BuildDeclaratorGroup(Decls); 12253 } 12254 12255 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 12256 /// group, performing any necessary semantic checking. 12257 Sema::DeclGroupPtrTy 12258 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 12259 // C++14 [dcl.spec.auto]p7: (DR1347) 12260 // If the type that replaces the placeholder type is not the same in each 12261 // deduction, the program is ill-formed. 12262 if (Group.size() > 1) { 12263 QualType Deduced; 12264 VarDecl *DeducedDecl = nullptr; 12265 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12266 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 12267 if (!D || D->isInvalidDecl()) 12268 break; 12269 DeducedType *DT = D->getType()->getContainedDeducedType(); 12270 if (!DT || DT->getDeducedType().isNull()) 12271 continue; 12272 if (Deduced.isNull()) { 12273 Deduced = DT->getDeducedType(); 12274 DeducedDecl = D; 12275 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 12276 auto *AT = dyn_cast<AutoType>(DT); 12277 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 12278 diag::err_auto_different_deductions) 12279 << (AT ? (unsigned)AT->getKeyword() : 3) 12280 << Deduced << DeducedDecl->getDeclName() 12281 << DT->getDeducedType() << D->getDeclName() 12282 << DeducedDecl->getInit()->getSourceRange() 12283 << D->getInit()->getSourceRange(); 12284 D->setInvalidDecl(); 12285 break; 12286 } 12287 } 12288 } 12289 12290 ActOnDocumentableDecls(Group); 12291 12292 return DeclGroupPtrTy::make( 12293 DeclGroupRef::Create(Context, Group.data(), Group.size())); 12294 } 12295 12296 void Sema::ActOnDocumentableDecl(Decl *D) { 12297 ActOnDocumentableDecls(D); 12298 } 12299 12300 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 12301 // Don't parse the comment if Doxygen diagnostics are ignored. 12302 if (Group.empty() || !Group[0]) 12303 return; 12304 12305 if (Diags.isIgnored(diag::warn_doc_param_not_found, 12306 Group[0]->getLocation()) && 12307 Diags.isIgnored(diag::warn_unknown_comment_command_name, 12308 Group[0]->getLocation())) 12309 return; 12310 12311 if (Group.size() >= 2) { 12312 // This is a decl group. Normally it will contain only declarations 12313 // produced from declarator list. But in case we have any definitions or 12314 // additional declaration references: 12315 // 'typedef struct S {} S;' 12316 // 'typedef struct S *S;' 12317 // 'struct S *pS;' 12318 // FinalizeDeclaratorGroup adds these as separate declarations. 12319 Decl *MaybeTagDecl = Group[0]; 12320 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 12321 Group = Group.slice(1); 12322 } 12323 } 12324 12325 // See if there are any new comments that are not attached to a decl. 12326 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 12327 if (!Comments.empty() && 12328 !Comments.back()->isAttached()) { 12329 // There is at least one comment that not attached to a decl. 12330 // Maybe it should be attached to one of these decls? 12331 // 12332 // Note that this way we pick up not only comments that precede the 12333 // declaration, but also comments that *follow* the declaration -- thanks to 12334 // the lookahead in the lexer: we've consumed the semicolon and looked 12335 // ahead through comments. 12336 for (unsigned i = 0, e = Group.size(); i != e; ++i) 12337 Context.getCommentForDecl(Group[i], &PP); 12338 } 12339 } 12340 12341 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 12342 /// to introduce parameters into function prototype scope. 12343 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 12344 const DeclSpec &DS = D.getDeclSpec(); 12345 12346 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 12347 12348 // C++03 [dcl.stc]p2 also permits 'auto'. 12349 StorageClass SC = SC_None; 12350 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 12351 SC = SC_Register; 12352 // In C++11, the 'register' storage class specifier is deprecated. 12353 // In C++17, it is not allowed, but we tolerate it as an extension. 12354 if (getLangOpts().CPlusPlus11) { 12355 Diag(DS.getStorageClassSpecLoc(), 12356 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 12357 : diag::warn_deprecated_register) 12358 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12359 } 12360 } else if (getLangOpts().CPlusPlus && 12361 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 12362 SC = SC_Auto; 12363 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 12364 Diag(DS.getStorageClassSpecLoc(), 12365 diag::err_invalid_storage_class_in_func_decl); 12366 D.getMutableDeclSpec().ClearStorageClassSpecs(); 12367 } 12368 12369 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12370 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12371 << DeclSpec::getSpecifierName(TSCS); 12372 if (DS.isInlineSpecified()) 12373 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12374 << getLangOpts().CPlusPlus17; 12375 if (DS.isConstexprSpecified()) 12376 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12377 << 0; 12378 12379 DiagnoseFunctionSpecifiers(DS); 12380 12381 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12382 QualType parmDeclType = TInfo->getType(); 12383 12384 if (getLangOpts().CPlusPlus) { 12385 // Check that there are no default arguments inside the type of this 12386 // parameter. 12387 CheckExtraCXXDefaultArguments(D); 12388 12389 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12390 if (D.getCXXScopeSpec().isSet()) { 12391 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12392 << D.getCXXScopeSpec().getRange(); 12393 D.getCXXScopeSpec().clear(); 12394 } 12395 } 12396 12397 // Ensure we have a valid name 12398 IdentifierInfo *II = nullptr; 12399 if (D.hasName()) { 12400 II = D.getIdentifier(); 12401 if (!II) { 12402 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12403 << GetNameForDeclarator(D).getName(); 12404 D.setInvalidType(true); 12405 } 12406 } 12407 12408 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12409 if (II) { 12410 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12411 ForVisibleRedeclaration); 12412 LookupName(R, S); 12413 if (R.isSingleResult()) { 12414 NamedDecl *PrevDecl = R.getFoundDecl(); 12415 if (PrevDecl->isTemplateParameter()) { 12416 // Maybe we will complain about the shadowed template parameter. 12417 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12418 // Just pretend that we didn't see the previous declaration. 12419 PrevDecl = nullptr; 12420 } else if (S->isDeclScope(PrevDecl)) { 12421 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12422 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12423 12424 // Recover by removing the name 12425 II = nullptr; 12426 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12427 D.setInvalidType(true); 12428 } 12429 } 12430 } 12431 12432 // Temporarily put parameter variables in the translation unit, not 12433 // the enclosing context. This prevents them from accidentally 12434 // looking like class members in C++. 12435 ParmVarDecl *New = 12436 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 12437 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 12438 12439 if (D.isInvalidType()) 12440 New->setInvalidDecl(); 12441 12442 assert(S->isFunctionPrototypeScope()); 12443 assert(S->getFunctionPrototypeDepth() >= 1); 12444 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12445 S->getNextFunctionPrototypeIndex()); 12446 12447 // Add the parameter declaration into this scope. 12448 S->AddDecl(New); 12449 if (II) 12450 IdResolver.AddDecl(New); 12451 12452 ProcessDeclAttributes(S, New, D); 12453 12454 if (D.getDeclSpec().isModulePrivateSpecified()) 12455 Diag(New->getLocation(), diag::err_module_private_local) 12456 << 1 << New->getDeclName() 12457 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12458 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12459 12460 if (New->hasAttr<BlocksAttr>()) { 12461 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12462 } 12463 return New; 12464 } 12465 12466 /// Synthesizes a variable for a parameter arising from a 12467 /// typedef. 12468 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12469 SourceLocation Loc, 12470 QualType T) { 12471 /* FIXME: setting StartLoc == Loc. 12472 Would it be worth to modify callers so as to provide proper source 12473 location for the unnamed parameters, embedding the parameter's type? */ 12474 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12475 T, Context.getTrivialTypeSourceInfo(T, Loc), 12476 SC_None, nullptr); 12477 Param->setImplicit(); 12478 return Param; 12479 } 12480 12481 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12482 // Don't diagnose unused-parameter errors in template instantiations; we 12483 // will already have done so in the template itself. 12484 if (inTemplateInstantiation()) 12485 return; 12486 12487 for (const ParmVarDecl *Parameter : Parameters) { 12488 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12489 !Parameter->hasAttr<UnusedAttr>()) { 12490 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12491 << Parameter->getDeclName(); 12492 } 12493 } 12494 } 12495 12496 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12497 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12498 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12499 return; 12500 12501 // Warn if the return value is pass-by-value and larger than the specified 12502 // threshold. 12503 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12504 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12505 if (Size > LangOpts.NumLargeByValueCopy) 12506 Diag(D->getLocation(), diag::warn_return_value_size) 12507 << D->getDeclName() << Size; 12508 } 12509 12510 // Warn if any parameter is pass-by-value and larger than the specified 12511 // threshold. 12512 for (const ParmVarDecl *Parameter : Parameters) { 12513 QualType T = Parameter->getType(); 12514 if (T->isDependentType() || !T.isPODType(Context)) 12515 continue; 12516 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12517 if (Size > LangOpts.NumLargeByValueCopy) 12518 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12519 << Parameter->getDeclName() << Size; 12520 } 12521 } 12522 12523 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12524 SourceLocation NameLoc, IdentifierInfo *Name, 12525 QualType T, TypeSourceInfo *TSInfo, 12526 StorageClass SC) { 12527 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12528 if (getLangOpts().ObjCAutoRefCount && 12529 T.getObjCLifetime() == Qualifiers::OCL_None && 12530 T->isObjCLifetimeType()) { 12531 12532 Qualifiers::ObjCLifetime lifetime; 12533 12534 // Special cases for arrays: 12535 // - if it's const, use __unsafe_unretained 12536 // - otherwise, it's an error 12537 if (T->isArrayType()) { 12538 if (!T.isConstQualified()) { 12539 DelayedDiagnostics.add( 12540 sema::DelayedDiagnostic::makeForbiddenType( 12541 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12542 } 12543 lifetime = Qualifiers::OCL_ExplicitNone; 12544 } else { 12545 lifetime = T->getObjCARCImplicitLifetime(); 12546 } 12547 T = Context.getLifetimeQualifiedType(T, lifetime); 12548 } 12549 12550 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12551 Context.getAdjustedParameterType(T), 12552 TSInfo, SC, nullptr); 12553 12554 // Parameters can not be abstract class types. 12555 // For record types, this is done by the AbstractClassUsageDiagnoser once 12556 // the class has been completely parsed. 12557 if (!CurContext->isRecord() && 12558 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12559 AbstractParamType)) 12560 New->setInvalidDecl(); 12561 12562 // Parameter declarators cannot be interface types. All ObjC objects are 12563 // passed by reference. 12564 if (T->isObjCObjectType()) { 12565 SourceLocation TypeEndLoc = 12566 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 12567 Diag(NameLoc, 12568 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12569 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12570 T = Context.getObjCObjectPointerType(T); 12571 New->setType(T); 12572 } 12573 12574 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12575 // duration shall not be qualified by an address-space qualifier." 12576 // Since all parameters have automatic store duration, they can not have 12577 // an address space. 12578 if (T.getAddressSpace() != LangAS::Default && 12579 // OpenCL allows function arguments declared to be an array of a type 12580 // to be qualified with an address space. 12581 !(getLangOpts().OpenCL && 12582 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12583 Diag(NameLoc, diag::err_arg_with_address_space); 12584 New->setInvalidDecl(); 12585 } 12586 12587 return New; 12588 } 12589 12590 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12591 SourceLocation LocAfterDecls) { 12592 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12593 12594 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12595 // for a K&R function. 12596 if (!FTI.hasPrototype) { 12597 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12598 --i; 12599 if (FTI.Params[i].Param == nullptr) { 12600 SmallString<256> Code; 12601 llvm::raw_svector_ostream(Code) 12602 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12603 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12604 << FTI.Params[i].Ident 12605 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12606 12607 // Implicitly declare the argument as type 'int' for lack of a better 12608 // type. 12609 AttributeFactory attrs; 12610 DeclSpec DS(attrs); 12611 const char* PrevSpec; // unused 12612 unsigned DiagID; // unused 12613 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12614 DiagID, Context.getPrintingPolicy()); 12615 // Use the identifier location for the type source range. 12616 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12617 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12618 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12619 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12620 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12621 } 12622 } 12623 } 12624 } 12625 12626 Decl * 12627 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12628 MultiTemplateParamsArg TemplateParameterLists, 12629 SkipBodyInfo *SkipBody) { 12630 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12631 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12632 Scope *ParentScope = FnBodyScope->getParent(); 12633 12634 D.setFunctionDefinitionKind(FDK_Definition); 12635 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12636 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12637 } 12638 12639 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12640 Consumer.HandleInlineFunctionDefinition(D); 12641 } 12642 12643 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12644 const FunctionDecl*& PossibleZeroParamPrototype) { 12645 // Don't warn about invalid declarations. 12646 if (FD->isInvalidDecl()) 12647 return false; 12648 12649 // Or declarations that aren't global. 12650 if (!FD->isGlobal()) 12651 return false; 12652 12653 // Don't warn about C++ member functions. 12654 if (isa<CXXMethodDecl>(FD)) 12655 return false; 12656 12657 // Don't warn about 'main'. 12658 if (FD->isMain()) 12659 return false; 12660 12661 // Don't warn about inline functions. 12662 if (FD->isInlined()) 12663 return false; 12664 12665 // Don't warn about function templates. 12666 if (FD->getDescribedFunctionTemplate()) 12667 return false; 12668 12669 // Don't warn about function template specializations. 12670 if (FD->isFunctionTemplateSpecialization()) 12671 return false; 12672 12673 // Don't warn for OpenCL kernels. 12674 if (FD->hasAttr<OpenCLKernelAttr>()) 12675 return false; 12676 12677 // Don't warn on explicitly deleted functions. 12678 if (FD->isDeleted()) 12679 return false; 12680 12681 bool MissingPrototype = true; 12682 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12683 Prev; Prev = Prev->getPreviousDecl()) { 12684 // Ignore any declarations that occur in function or method 12685 // scope, because they aren't visible from the header. 12686 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12687 continue; 12688 12689 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12690 if (FD->getNumParams() == 0) 12691 PossibleZeroParamPrototype = Prev; 12692 break; 12693 } 12694 12695 return MissingPrototype; 12696 } 12697 12698 void 12699 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12700 const FunctionDecl *EffectiveDefinition, 12701 SkipBodyInfo *SkipBody) { 12702 const FunctionDecl *Definition = EffectiveDefinition; 12703 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12704 // If this is a friend function defined in a class template, it does not 12705 // have a body until it is used, nevertheless it is a definition, see 12706 // [temp.inst]p2: 12707 // 12708 // ... for the purpose of determining whether an instantiated redeclaration 12709 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12710 // corresponds to a definition in the template is considered to be a 12711 // definition. 12712 // 12713 // The following code must produce redefinition error: 12714 // 12715 // template<typename T> struct C20 { friend void func_20() {} }; 12716 // C20<int> c20i; 12717 // void func_20() {} 12718 // 12719 for (auto I : FD->redecls()) { 12720 if (I != FD && !I->isInvalidDecl() && 12721 I->getFriendObjectKind() != Decl::FOK_None) { 12722 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12723 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12724 // A merged copy of the same function, instantiated as a member of 12725 // the same class, is OK. 12726 if (declaresSameEntity(OrigFD, Original) && 12727 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12728 cast<Decl>(FD->getLexicalDeclContext()))) 12729 continue; 12730 } 12731 12732 if (Original->isThisDeclarationADefinition()) { 12733 Definition = I; 12734 break; 12735 } 12736 } 12737 } 12738 } 12739 } 12740 12741 if (!Definition) 12742 // Similar to friend functions a friend function template may be a 12743 // definition and do not have a body if it is instantiated in a class 12744 // template. 12745 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 12746 for (auto I : FTD->redecls()) { 12747 auto D = cast<FunctionTemplateDecl>(I); 12748 if (D != FTD) { 12749 assert(!D->isThisDeclarationADefinition() && 12750 "More than one definition in redeclaration chain"); 12751 if (D->getFriendObjectKind() != Decl::FOK_None) 12752 if (FunctionTemplateDecl *FT = 12753 D->getInstantiatedFromMemberTemplate()) { 12754 if (FT->isThisDeclarationADefinition()) { 12755 Definition = D->getTemplatedDecl(); 12756 break; 12757 } 12758 } 12759 } 12760 } 12761 } 12762 12763 if (!Definition) 12764 return; 12765 12766 if (canRedefineFunction(Definition, getLangOpts())) 12767 return; 12768 12769 // Don't emit an error when this is redefinition of a typo-corrected 12770 // definition. 12771 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12772 return; 12773 12774 // If we don't have a visible definition of the function, and it's inline or 12775 // a template, skip the new definition. 12776 if (SkipBody && !hasVisibleDefinition(Definition) && 12777 (Definition->getFormalLinkage() == InternalLinkage || 12778 Definition->isInlined() || 12779 Definition->getDescribedFunctionTemplate() || 12780 Definition->getNumTemplateParameterLists())) { 12781 SkipBody->ShouldSkip = true; 12782 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 12783 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12784 makeMergedDefinitionVisible(TD); 12785 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12786 return; 12787 } 12788 12789 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12790 Definition->getStorageClass() == SC_Extern) 12791 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12792 << FD->getDeclName() << getLangOpts().CPlusPlus; 12793 else 12794 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12795 12796 Diag(Definition->getLocation(), diag::note_previous_definition); 12797 FD->setInvalidDecl(); 12798 } 12799 12800 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12801 Sema &S) { 12802 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12803 12804 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12805 LSI->CallOperator = CallOperator; 12806 LSI->Lambda = LambdaClass; 12807 LSI->ReturnType = CallOperator->getReturnType(); 12808 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12809 12810 if (LCD == LCD_None) 12811 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12812 else if (LCD == LCD_ByCopy) 12813 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12814 else if (LCD == LCD_ByRef) 12815 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12816 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12817 12818 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12819 LSI->Mutable = !CallOperator->isConst(); 12820 12821 // Add the captures to the LSI so they can be noted as already 12822 // captured within tryCaptureVar. 12823 auto I = LambdaClass->field_begin(); 12824 for (const auto &C : LambdaClass->captures()) { 12825 if (C.capturesVariable()) { 12826 VarDecl *VD = C.getCapturedVar(); 12827 if (VD->isInitCapture()) 12828 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12829 QualType CaptureType = VD->getType(); 12830 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12831 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12832 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12833 /*EllipsisLoc*/C.isPackExpansion() 12834 ? C.getEllipsisLoc() : SourceLocation(), 12835 CaptureType, /*Expr*/ nullptr); 12836 12837 } else if (C.capturesThis()) { 12838 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12839 /*Expr*/ nullptr, 12840 C.getCaptureKind() == LCK_StarThis); 12841 } else { 12842 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12843 } 12844 ++I; 12845 } 12846 } 12847 12848 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12849 SkipBodyInfo *SkipBody) { 12850 if (!D) { 12851 // Parsing the function declaration failed in some way. Push on a fake scope 12852 // anyway so we can try to parse the function body. 12853 PushFunctionScope(); 12854 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12855 return D; 12856 } 12857 12858 FunctionDecl *FD = nullptr; 12859 12860 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12861 FD = FunTmpl->getTemplatedDecl(); 12862 else 12863 FD = cast<FunctionDecl>(D); 12864 12865 // Do not push if it is a lambda because one is already pushed when building 12866 // the lambda in ActOnStartOfLambdaDefinition(). 12867 if (!isLambdaCallOperator(FD)) 12868 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12869 12870 // Check for defining attributes before the check for redefinition. 12871 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12872 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12873 FD->dropAttr<AliasAttr>(); 12874 FD->setInvalidDecl(); 12875 } 12876 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12877 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12878 FD->dropAttr<IFuncAttr>(); 12879 FD->setInvalidDecl(); 12880 } 12881 12882 // See if this is a redefinition. If 'will have body' is already set, then 12883 // these checks were already performed when it was set. 12884 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12885 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12886 12887 // If we're skipping the body, we're done. Don't enter the scope. 12888 if (SkipBody && SkipBody->ShouldSkip) 12889 return D; 12890 } 12891 12892 // Mark this function as "will have a body eventually". This lets users to 12893 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12894 // this function. 12895 FD->setWillHaveBody(); 12896 12897 // If we are instantiating a generic lambda call operator, push 12898 // a LambdaScopeInfo onto the function stack. But use the information 12899 // that's already been calculated (ActOnLambdaExpr) to prime the current 12900 // LambdaScopeInfo. 12901 // When the template operator is being specialized, the LambdaScopeInfo, 12902 // has to be properly restored so that tryCaptureVariable doesn't try 12903 // and capture any new variables. In addition when calculating potential 12904 // captures during transformation of nested lambdas, it is necessary to 12905 // have the LSI properly restored. 12906 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12907 assert(inTemplateInstantiation() && 12908 "There should be an active template instantiation on the stack " 12909 "when instantiating a generic lambda!"); 12910 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12911 } else { 12912 // Enter a new function scope 12913 PushFunctionScope(); 12914 } 12915 12916 // Builtin functions cannot be defined. 12917 if (unsigned BuiltinID = FD->getBuiltinID()) { 12918 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12919 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12920 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12921 FD->setInvalidDecl(); 12922 } 12923 } 12924 12925 // The return type of a function definition must be complete 12926 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12927 QualType ResultType = FD->getReturnType(); 12928 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12929 !FD->isInvalidDecl() && 12930 RequireCompleteType(FD->getLocation(), ResultType, 12931 diag::err_func_def_incomplete_result)) 12932 FD->setInvalidDecl(); 12933 12934 if (FnBodyScope) 12935 PushDeclContext(FnBodyScope, FD); 12936 12937 // Check the validity of our function parameters 12938 CheckParmsForFunctionDef(FD->parameters(), 12939 /*CheckParameterNames=*/true); 12940 12941 // Add non-parameter declarations already in the function to the current 12942 // scope. 12943 if (FnBodyScope) { 12944 for (Decl *NPD : FD->decls()) { 12945 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12946 if (!NonParmDecl) 12947 continue; 12948 assert(!isa<ParmVarDecl>(NonParmDecl) && 12949 "parameters should not be in newly created FD yet"); 12950 12951 // If the decl has a name, make it accessible in the current scope. 12952 if (NonParmDecl->getDeclName()) 12953 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12954 12955 // Similarly, dive into enums and fish their constants out, making them 12956 // accessible in this scope. 12957 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12958 for (auto *EI : ED->enumerators()) 12959 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12960 } 12961 } 12962 } 12963 12964 // Introduce our parameters into the function scope 12965 for (auto Param : FD->parameters()) { 12966 Param->setOwningFunction(FD); 12967 12968 // If this has an identifier, add it to the scope stack. 12969 if (Param->getIdentifier() && FnBodyScope) { 12970 CheckShadow(FnBodyScope, Param); 12971 12972 PushOnScopeChains(Param, FnBodyScope); 12973 } 12974 } 12975 12976 // Ensure that the function's exception specification is instantiated. 12977 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12978 ResolveExceptionSpec(D->getLocation(), FPT); 12979 12980 // dllimport cannot be applied to non-inline function definitions. 12981 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12982 !FD->isTemplateInstantiation()) { 12983 assert(!FD->hasAttr<DLLExportAttr>()); 12984 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12985 FD->setInvalidDecl(); 12986 return D; 12987 } 12988 // We want to attach documentation to original Decl (which might be 12989 // a function template). 12990 ActOnDocumentableDecl(D); 12991 if (getCurLexicalContext()->isObjCContainer() && 12992 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12993 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12994 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12995 12996 return D; 12997 } 12998 12999 /// Given the set of return statements within a function body, 13000 /// compute the variables that are subject to the named return value 13001 /// optimization. 13002 /// 13003 /// Each of the variables that is subject to the named return value 13004 /// optimization will be marked as NRVO variables in the AST, and any 13005 /// return statement that has a marked NRVO variable as its NRVO candidate can 13006 /// use the named return value optimization. 13007 /// 13008 /// This function applies a very simplistic algorithm for NRVO: if every return 13009 /// statement in the scope of a variable has the same NRVO candidate, that 13010 /// candidate is an NRVO variable. 13011 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13012 ReturnStmt **Returns = Scope->Returns.data(); 13013 13014 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13015 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13016 if (!NRVOCandidate->isNRVOVariable()) 13017 Returns[I]->setNRVOCandidate(nullptr); 13018 } 13019 } 13020 } 13021 13022 bool Sema::canDelayFunctionBody(const Declarator &D) { 13023 // We can't delay parsing the body of a constexpr function template (yet). 13024 if (D.getDeclSpec().isConstexprSpecified()) 13025 return false; 13026 13027 // We can't delay parsing the body of a function template with a deduced 13028 // return type (yet). 13029 if (D.getDeclSpec().hasAutoTypeSpec()) { 13030 // If the placeholder introduces a non-deduced trailing return type, 13031 // we can still delay parsing it. 13032 if (D.getNumTypeObjects()) { 13033 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13034 if (Outer.Kind == DeclaratorChunk::Function && 13035 Outer.Fun.hasTrailingReturnType()) { 13036 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13037 return Ty.isNull() || !Ty->isUndeducedType(); 13038 } 13039 } 13040 return false; 13041 } 13042 13043 return true; 13044 } 13045 13046 bool Sema::canSkipFunctionBody(Decl *D) { 13047 // We cannot skip the body of a function (or function template) which is 13048 // constexpr, since we may need to evaluate its body in order to parse the 13049 // rest of the file. 13050 // We cannot skip the body of a function with an undeduced return type, 13051 // because any callers of that function need to know the type. 13052 if (const FunctionDecl *FD = D->getAsFunction()) { 13053 if (FD->isConstexpr()) 13054 return false; 13055 // We can't simply call Type::isUndeducedType here, because inside template 13056 // auto can be deduced to a dependent type, which is not considered 13057 // "undeduced". 13058 if (FD->getReturnType()->getContainedDeducedType()) 13059 return false; 13060 } 13061 return Consumer.shouldSkipFunctionBody(D); 13062 } 13063 13064 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13065 if (!Decl) 13066 return nullptr; 13067 if (FunctionDecl *FD = Decl->getAsFunction()) 13068 FD->setHasSkippedBody(); 13069 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13070 MD->setHasSkippedBody(); 13071 return Decl; 13072 } 13073 13074 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13075 return ActOnFinishFunctionBody(D, BodyArg, false); 13076 } 13077 13078 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13079 /// body. 13080 class ExitFunctionBodyRAII { 13081 public: 13082 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13083 ~ExitFunctionBodyRAII() { 13084 if (!IsLambda) 13085 S.PopExpressionEvaluationContext(); 13086 } 13087 13088 private: 13089 Sema &S; 13090 bool IsLambda = false; 13091 }; 13092 13093 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 13094 bool IsInstantiation) { 13095 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 13096 13097 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13098 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 13099 13100 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 13101 CheckCompletedCoroutineBody(FD, Body); 13102 13103 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 13104 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 13105 // meant to pop the context added in ActOnStartOfFunctionDef(). 13106 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 13107 13108 if (FD) { 13109 FD->setBody(Body); 13110 FD->setWillHaveBody(false); 13111 13112 if (getLangOpts().CPlusPlus14) { 13113 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 13114 FD->getReturnType()->isUndeducedType()) { 13115 // If the function has a deduced result type but contains no 'return' 13116 // statements, the result type as written must be exactly 'auto', and 13117 // the deduced result type is 'void'. 13118 if (!FD->getReturnType()->getAs<AutoType>()) { 13119 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 13120 << FD->getReturnType(); 13121 FD->setInvalidDecl(); 13122 } else { 13123 // Substitute 'void' for the 'auto' in the type. 13124 TypeLoc ResultType = getReturnTypeLoc(FD); 13125 Context.adjustDeducedFunctionResultType( 13126 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 13127 } 13128 } 13129 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 13130 // In C++11, we don't use 'auto' deduction rules for lambda call 13131 // operators because we don't support return type deduction. 13132 auto *LSI = getCurLambda(); 13133 if (LSI->HasImplicitReturnType) { 13134 deduceClosureReturnType(*LSI); 13135 13136 // C++11 [expr.prim.lambda]p4: 13137 // [...] if there are no return statements in the compound-statement 13138 // [the deduced type is] the type void 13139 QualType RetType = 13140 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 13141 13142 // Update the return type to the deduced type. 13143 const FunctionProtoType *Proto = 13144 FD->getType()->getAs<FunctionProtoType>(); 13145 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 13146 Proto->getExtProtoInfo())); 13147 } 13148 } 13149 13150 // If the function implicitly returns zero (like 'main') or is naked, 13151 // don't complain about missing return statements. 13152 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 13153 WP.disableCheckFallThrough(); 13154 13155 // MSVC permits the use of pure specifier (=0) on function definition, 13156 // defined at class scope, warn about this non-standard construct. 13157 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 13158 Diag(FD->getLocation(), diag::ext_pure_function_definition); 13159 13160 if (!FD->isInvalidDecl()) { 13161 // Don't diagnose unused parameters of defaulted or deleted functions. 13162 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 13163 DiagnoseUnusedParameters(FD->parameters()); 13164 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 13165 FD->getReturnType(), FD); 13166 13167 // If this is a structor, we need a vtable. 13168 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 13169 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 13170 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 13171 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 13172 13173 // Try to apply the named return value optimization. We have to check 13174 // if we can do this here because lambdas keep return statements around 13175 // to deduce an implicit return type. 13176 if (FD->getReturnType()->isRecordType() && 13177 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 13178 computeNRVO(Body, getCurFunction()); 13179 } 13180 13181 // GNU warning -Wmissing-prototypes: 13182 // Warn if a global function is defined without a previous 13183 // prototype declaration. This warning is issued even if the 13184 // definition itself provides a prototype. The aim is to detect 13185 // global functions that fail to be declared in header files. 13186 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 13187 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 13188 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 13189 13190 if (PossibleZeroParamPrototype) { 13191 // We found a declaration that is not a prototype, 13192 // but that could be a zero-parameter prototype 13193 if (TypeSourceInfo *TI = 13194 PossibleZeroParamPrototype->getTypeSourceInfo()) { 13195 TypeLoc TL = TI->getTypeLoc(); 13196 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 13197 Diag(PossibleZeroParamPrototype->getLocation(), 13198 diag::note_declaration_not_a_prototype) 13199 << PossibleZeroParamPrototype 13200 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 13201 } 13202 } 13203 13204 // GNU warning -Wstrict-prototypes 13205 // Warn if K&R function is defined without a previous declaration. 13206 // This warning is issued only if the definition itself does not provide 13207 // a prototype. Only K&R definitions do not provide a prototype. 13208 // An empty list in a function declarator that is part of a definition 13209 // of that function specifies that the function has no parameters 13210 // (C99 6.7.5.3p14) 13211 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 13212 !LangOpts.CPlusPlus) { 13213 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 13214 TypeLoc TL = TI->getTypeLoc(); 13215 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 13216 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 13217 } 13218 } 13219 13220 // Warn on CPUDispatch with an actual body. 13221 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 13222 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 13223 if (!CmpndBody->body_empty()) 13224 Diag(CmpndBody->body_front()->getBeginLoc(), 13225 diag::warn_dispatch_body_ignored); 13226 13227 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 13228 const CXXMethodDecl *KeyFunction; 13229 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 13230 MD->isVirtual() && 13231 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 13232 MD == KeyFunction->getCanonicalDecl()) { 13233 // Update the key-function state if necessary for this ABI. 13234 if (FD->isInlined() && 13235 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 13236 Context.setNonKeyFunction(MD); 13237 13238 // If the newly-chosen key function is already defined, then we 13239 // need to mark the vtable as used retroactively. 13240 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 13241 const FunctionDecl *Definition; 13242 if (KeyFunction && KeyFunction->isDefined(Definition)) 13243 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 13244 } else { 13245 // We just defined they key function; mark the vtable as used. 13246 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 13247 } 13248 } 13249 } 13250 13251 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 13252 "Function parsing confused"); 13253 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 13254 assert(MD == getCurMethodDecl() && "Method parsing confused"); 13255 MD->setBody(Body); 13256 if (!MD->isInvalidDecl()) { 13257 if (!MD->hasSkippedBody()) 13258 DiagnoseUnusedParameters(MD->parameters()); 13259 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 13260 MD->getReturnType(), MD); 13261 13262 if (Body) 13263 computeNRVO(Body, getCurFunction()); 13264 } 13265 if (getCurFunction()->ObjCShouldCallSuper) { 13266 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 13267 << MD->getSelector().getAsString(); 13268 getCurFunction()->ObjCShouldCallSuper = false; 13269 } 13270 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 13271 const ObjCMethodDecl *InitMethod = nullptr; 13272 bool isDesignated = 13273 MD->isDesignatedInitializerForTheInterface(&InitMethod); 13274 assert(isDesignated && InitMethod); 13275 (void)isDesignated; 13276 13277 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 13278 auto IFace = MD->getClassInterface(); 13279 if (!IFace) 13280 return false; 13281 auto SuperD = IFace->getSuperClass(); 13282 if (!SuperD) 13283 return false; 13284 return SuperD->getIdentifier() == 13285 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 13286 }; 13287 // Don't issue this warning for unavailable inits or direct subclasses 13288 // of NSObject. 13289 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 13290 Diag(MD->getLocation(), 13291 diag::warn_objc_designated_init_missing_super_call); 13292 Diag(InitMethod->getLocation(), 13293 diag::note_objc_designated_init_marked_here); 13294 } 13295 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 13296 } 13297 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 13298 // Don't issue this warning for unavaialable inits. 13299 if (!MD->isUnavailable()) 13300 Diag(MD->getLocation(), 13301 diag::warn_objc_secondary_init_missing_init_call); 13302 getCurFunction()->ObjCWarnForNoInitDelegation = false; 13303 } 13304 } else { 13305 // Parsing the function declaration failed in some way. Pop the fake scope 13306 // we pushed on. 13307 PopFunctionScopeInfo(ActivePolicy, dcl); 13308 return nullptr; 13309 } 13310 13311 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13312 DiagnoseUnguardedAvailabilityViolations(dcl); 13313 13314 assert(!getCurFunction()->ObjCShouldCallSuper && 13315 "This should only be set for ObjC methods, which should have been " 13316 "handled in the block above."); 13317 13318 // Verify and clean out per-function state. 13319 if (Body && (!FD || !FD->isDefaulted())) { 13320 // C++ constructors that have function-try-blocks can't have return 13321 // statements in the handlers of that block. (C++ [except.handle]p14) 13322 // Verify this. 13323 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 13324 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 13325 13326 // Verify that gotos and switch cases don't jump into scopes illegally. 13327 if (getCurFunction()->NeedsScopeChecking() && 13328 !PP.isCodeCompletionEnabled()) 13329 DiagnoseInvalidJumps(Body); 13330 13331 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 13332 if (!Destructor->getParent()->isDependentType()) 13333 CheckDestructor(Destructor); 13334 13335 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13336 Destructor->getParent()); 13337 } 13338 13339 // If any errors have occurred, clear out any temporaries that may have 13340 // been leftover. This ensures that these temporaries won't be picked up for 13341 // deletion in some later function. 13342 if (getDiagnostics().hasErrorOccurred() || 13343 getDiagnostics().getSuppressAllDiagnostics()) { 13344 DiscardCleanupsInEvaluationContext(); 13345 } 13346 if (!getDiagnostics().hasUncompilableErrorOccurred() && 13347 !isa<FunctionTemplateDecl>(dcl)) { 13348 // Since the body is valid, issue any analysis-based warnings that are 13349 // enabled. 13350 ActivePolicy = &WP; 13351 } 13352 13353 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 13354 (!CheckConstexprFunctionDecl(FD) || 13355 !CheckConstexprFunctionBody(FD, Body))) 13356 FD->setInvalidDecl(); 13357 13358 if (FD && FD->hasAttr<NakedAttr>()) { 13359 for (const Stmt *S : Body->children()) { 13360 // Allow local register variables without initializer as they don't 13361 // require prologue. 13362 bool RegisterVariables = false; 13363 if (auto *DS = dyn_cast<DeclStmt>(S)) { 13364 for (const auto *Decl : DS->decls()) { 13365 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 13366 RegisterVariables = 13367 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 13368 if (!RegisterVariables) 13369 break; 13370 } 13371 } 13372 } 13373 if (RegisterVariables) 13374 continue; 13375 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 13376 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 13377 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 13378 FD->setInvalidDecl(); 13379 break; 13380 } 13381 } 13382 } 13383 13384 assert(ExprCleanupObjects.size() == 13385 ExprEvalContexts.back().NumCleanupObjects && 13386 "Leftover temporaries in function"); 13387 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 13388 assert(MaybeODRUseExprs.empty() && 13389 "Leftover expressions for odr-use checking"); 13390 } 13391 13392 if (!IsInstantiation) 13393 PopDeclContext(); 13394 13395 PopFunctionScopeInfo(ActivePolicy, dcl); 13396 // If any errors have occurred, clear out any temporaries that may have 13397 // been leftover. This ensures that these temporaries won't be picked up for 13398 // deletion in some later function. 13399 if (getDiagnostics().hasErrorOccurred()) { 13400 DiscardCleanupsInEvaluationContext(); 13401 } 13402 13403 return dcl; 13404 } 13405 13406 /// When we finish delayed parsing of an attribute, we must attach it to the 13407 /// relevant Decl. 13408 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 13409 ParsedAttributes &Attrs) { 13410 // Always attach attributes to the underlying decl. 13411 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 13412 D = TD->getTemplatedDecl(); 13413 ProcessDeclAttributeList(S, D, Attrs); 13414 13415 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 13416 if (Method->isStatic()) 13417 checkThisInStaticMemberFunctionAttributes(Method); 13418 } 13419 13420 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 13421 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 13422 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 13423 IdentifierInfo &II, Scope *S) { 13424 // Find the scope in which the identifier is injected and the corresponding 13425 // DeclContext. 13426 // FIXME: C89 does not say what happens if there is no enclosing block scope. 13427 // In that case, we inject the declaration into the translation unit scope 13428 // instead. 13429 Scope *BlockScope = S; 13430 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 13431 BlockScope = BlockScope->getParent(); 13432 13433 Scope *ContextScope = BlockScope; 13434 while (!ContextScope->getEntity()) 13435 ContextScope = ContextScope->getParent(); 13436 ContextRAII SavedContext(*this, ContextScope->getEntity()); 13437 13438 // Before we produce a declaration for an implicitly defined 13439 // function, see whether there was a locally-scoped declaration of 13440 // this name as a function or variable. If so, use that 13441 // (non-visible) declaration, and complain about it. 13442 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 13443 if (ExternCPrev) { 13444 // We still need to inject the function into the enclosing block scope so 13445 // that later (non-call) uses can see it. 13446 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13447 13448 // C89 footnote 38: 13449 // If in fact it is not defined as having type "function returning int", 13450 // the behavior is undefined. 13451 if (!isa<FunctionDecl>(ExternCPrev) || 13452 !Context.typesAreCompatible( 13453 cast<FunctionDecl>(ExternCPrev)->getType(), 13454 Context.getFunctionNoProtoType(Context.IntTy))) { 13455 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13456 << ExternCPrev << !getLangOpts().C99; 13457 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13458 return ExternCPrev; 13459 } 13460 } 13461 13462 // Extension in C99. Legal in C90, but warn about it. 13463 unsigned diag_id; 13464 if (II.getName().startswith("__builtin_")) 13465 diag_id = diag::warn_builtin_unknown; 13466 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13467 else if (getLangOpts().OpenCL) 13468 diag_id = diag::err_opencl_implicit_function_decl; 13469 else if (getLangOpts().C99) 13470 diag_id = diag::ext_implicit_function_decl; 13471 else 13472 diag_id = diag::warn_implicit_function_decl; 13473 Diag(Loc, diag_id) << &II; 13474 13475 // If we found a prior declaration of this function, don't bother building 13476 // another one. We've already pushed that one into scope, so there's nothing 13477 // more to do. 13478 if (ExternCPrev) 13479 return ExternCPrev; 13480 13481 // Because typo correction is expensive, only do it if the implicit 13482 // function declaration is going to be treated as an error. 13483 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13484 TypoCorrection Corrected; 13485 if (S && 13486 (Corrected = CorrectTypo( 13487 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 13488 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 13489 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13490 /*ErrorRecovery*/false); 13491 } 13492 13493 // Set a Declarator for the implicit definition: int foo(); 13494 const char *Dummy; 13495 AttributeFactory attrFactory; 13496 DeclSpec DS(attrFactory); 13497 unsigned DiagID; 13498 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13499 Context.getPrintingPolicy()); 13500 (void)Error; // Silence warning. 13501 assert(!Error && "Error setting up implicit decl!"); 13502 SourceLocation NoLoc; 13503 Declarator D(DS, DeclaratorContext::BlockContext); 13504 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13505 /*IsAmbiguous=*/false, 13506 /*LParenLoc=*/NoLoc, 13507 /*Params=*/nullptr, 13508 /*NumParams=*/0, 13509 /*EllipsisLoc=*/NoLoc, 13510 /*RParenLoc=*/NoLoc, 13511 /*RefQualifierIsLvalueRef=*/true, 13512 /*RefQualifierLoc=*/NoLoc, 13513 /*MutableLoc=*/NoLoc, EST_None, 13514 /*ESpecRange=*/SourceRange(), 13515 /*Exceptions=*/nullptr, 13516 /*ExceptionRanges=*/nullptr, 13517 /*NumExceptions=*/0, 13518 /*NoexceptExpr=*/nullptr, 13519 /*ExceptionSpecTokens=*/nullptr, 13520 /*DeclsInPrototype=*/None, Loc, 13521 Loc, D), 13522 std::move(DS.getAttributes()), SourceLocation()); 13523 D.SetIdentifier(&II, Loc); 13524 13525 // Insert this function into the enclosing block scope. 13526 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13527 FD->setImplicit(); 13528 13529 AddKnownFunctionAttributes(FD); 13530 13531 return FD; 13532 } 13533 13534 /// Adds any function attributes that we know a priori based on 13535 /// the declaration of this function. 13536 /// 13537 /// These attributes can apply both to implicitly-declared builtins 13538 /// (like __builtin___printf_chk) or to library-declared functions 13539 /// like NSLog or printf. 13540 /// 13541 /// We need to check for duplicate attributes both here and where user-written 13542 /// attributes are applied to declarations. 13543 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13544 if (FD->isInvalidDecl()) 13545 return; 13546 13547 // If this is a built-in function, map its builtin attributes to 13548 // actual attributes. 13549 if (unsigned BuiltinID = FD->getBuiltinID()) { 13550 // Handle printf-formatting attributes. 13551 unsigned FormatIdx; 13552 bool HasVAListArg; 13553 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13554 if (!FD->hasAttr<FormatAttr>()) { 13555 const char *fmt = "printf"; 13556 unsigned int NumParams = FD->getNumParams(); 13557 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13558 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13559 fmt = "NSString"; 13560 FD->addAttr(FormatAttr::CreateImplicit(Context, 13561 &Context.Idents.get(fmt), 13562 FormatIdx+1, 13563 HasVAListArg ? 0 : FormatIdx+2, 13564 FD->getLocation())); 13565 } 13566 } 13567 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13568 HasVAListArg)) { 13569 if (!FD->hasAttr<FormatAttr>()) 13570 FD->addAttr(FormatAttr::CreateImplicit(Context, 13571 &Context.Idents.get("scanf"), 13572 FormatIdx+1, 13573 HasVAListArg ? 0 : FormatIdx+2, 13574 FD->getLocation())); 13575 } 13576 13577 // Mark const if we don't care about errno and that is the only thing 13578 // preventing the function from being const. This allows IRgen to use LLVM 13579 // intrinsics for such functions. 13580 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13581 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13582 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13583 13584 // We make "fma" on some platforms const because we know it does not set 13585 // errno in those environments even though it could set errno based on the 13586 // C standard. 13587 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13588 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13589 !FD->hasAttr<ConstAttr>()) { 13590 switch (BuiltinID) { 13591 case Builtin::BI__builtin_fma: 13592 case Builtin::BI__builtin_fmaf: 13593 case Builtin::BI__builtin_fmal: 13594 case Builtin::BIfma: 13595 case Builtin::BIfmaf: 13596 case Builtin::BIfmal: 13597 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13598 break; 13599 default: 13600 break; 13601 } 13602 } 13603 13604 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13605 !FD->hasAttr<ReturnsTwiceAttr>()) 13606 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13607 FD->getLocation())); 13608 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13609 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13610 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13611 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13612 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13613 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13614 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13615 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13616 // Add the appropriate attribute, depending on the CUDA compilation mode 13617 // and which target the builtin belongs to. For example, during host 13618 // compilation, aux builtins are __device__, while the rest are __host__. 13619 if (getLangOpts().CUDAIsDevice != 13620 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13621 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13622 else 13623 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13624 } 13625 } 13626 13627 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13628 // throw, add an implicit nothrow attribute to any extern "C" function we come 13629 // across. 13630 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13631 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13632 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13633 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13634 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13635 } 13636 13637 IdentifierInfo *Name = FD->getIdentifier(); 13638 if (!Name) 13639 return; 13640 if ((!getLangOpts().CPlusPlus && 13641 FD->getDeclContext()->isTranslationUnit()) || 13642 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13643 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13644 LinkageSpecDecl::lang_c)) { 13645 // Okay: this could be a libc/libm/Objective-C function we know 13646 // about. 13647 } else 13648 return; 13649 13650 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13651 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13652 // target-specific builtins, perhaps? 13653 if (!FD->hasAttr<FormatAttr>()) 13654 FD->addAttr(FormatAttr::CreateImplicit(Context, 13655 &Context.Idents.get("printf"), 2, 13656 Name->isStr("vasprintf") ? 0 : 3, 13657 FD->getLocation())); 13658 } 13659 13660 if (Name->isStr("__CFStringMakeConstantString")) { 13661 // We already have a __builtin___CFStringMakeConstantString, 13662 // but builds that use -fno-constant-cfstrings don't go through that. 13663 if (!FD->hasAttr<FormatArgAttr>()) 13664 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13665 FD->getLocation())); 13666 } 13667 } 13668 13669 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13670 TypeSourceInfo *TInfo) { 13671 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13672 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13673 13674 if (!TInfo) { 13675 assert(D.isInvalidType() && "no declarator info for valid type"); 13676 TInfo = Context.getTrivialTypeSourceInfo(T); 13677 } 13678 13679 // Scope manipulation handled by caller. 13680 TypedefDecl *NewTD = 13681 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 13682 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 13683 13684 // Bail out immediately if we have an invalid declaration. 13685 if (D.isInvalidType()) { 13686 NewTD->setInvalidDecl(); 13687 return NewTD; 13688 } 13689 13690 if (D.getDeclSpec().isModulePrivateSpecified()) { 13691 if (CurContext->isFunctionOrMethod()) 13692 Diag(NewTD->getLocation(), diag::err_module_private_local) 13693 << 2 << NewTD->getDeclName() 13694 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13695 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13696 else 13697 NewTD->setModulePrivate(); 13698 } 13699 13700 // C++ [dcl.typedef]p8: 13701 // If the typedef declaration defines an unnamed class (or 13702 // enum), the first typedef-name declared by the declaration 13703 // to be that class type (or enum type) is used to denote the 13704 // class type (or enum type) for linkage purposes only. 13705 // We need to check whether the type was declared in the declaration. 13706 switch (D.getDeclSpec().getTypeSpecType()) { 13707 case TST_enum: 13708 case TST_struct: 13709 case TST_interface: 13710 case TST_union: 13711 case TST_class: { 13712 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13713 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13714 break; 13715 } 13716 13717 default: 13718 break; 13719 } 13720 13721 return NewTD; 13722 } 13723 13724 /// Check that this is a valid underlying type for an enum declaration. 13725 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13726 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13727 QualType T = TI->getType(); 13728 13729 if (T->isDependentType()) 13730 return false; 13731 13732 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13733 if (BT->isInteger()) 13734 return false; 13735 13736 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13737 return true; 13738 } 13739 13740 /// Check whether this is a valid redeclaration of a previous enumeration. 13741 /// \return true if the redeclaration was invalid. 13742 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13743 QualType EnumUnderlyingTy, bool IsFixed, 13744 const EnumDecl *Prev) { 13745 if (IsScoped != Prev->isScoped()) { 13746 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13747 << Prev->isScoped(); 13748 Diag(Prev->getLocation(), diag::note_previous_declaration); 13749 return true; 13750 } 13751 13752 if (IsFixed && Prev->isFixed()) { 13753 if (!EnumUnderlyingTy->isDependentType() && 13754 !Prev->getIntegerType()->isDependentType() && 13755 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13756 Prev->getIntegerType())) { 13757 // TODO: Highlight the underlying type of the redeclaration. 13758 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13759 << EnumUnderlyingTy << Prev->getIntegerType(); 13760 Diag(Prev->getLocation(), diag::note_previous_declaration) 13761 << Prev->getIntegerTypeRange(); 13762 return true; 13763 } 13764 } else if (IsFixed != Prev->isFixed()) { 13765 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13766 << Prev->isFixed(); 13767 Diag(Prev->getLocation(), diag::note_previous_declaration); 13768 return true; 13769 } 13770 13771 return false; 13772 } 13773 13774 /// Get diagnostic %select index for tag kind for 13775 /// redeclaration diagnostic message. 13776 /// WARNING: Indexes apply to particular diagnostics only! 13777 /// 13778 /// \returns diagnostic %select index. 13779 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13780 switch (Tag) { 13781 case TTK_Struct: return 0; 13782 case TTK_Interface: return 1; 13783 case TTK_Class: return 2; 13784 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13785 } 13786 } 13787 13788 /// Determine if tag kind is a class-key compatible with 13789 /// class for redeclaration (class, struct, or __interface). 13790 /// 13791 /// \returns true iff the tag kind is compatible. 13792 static bool isClassCompatTagKind(TagTypeKind Tag) 13793 { 13794 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13795 } 13796 13797 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13798 TagTypeKind TTK) { 13799 if (isa<TypedefDecl>(PrevDecl)) 13800 return NTK_Typedef; 13801 else if (isa<TypeAliasDecl>(PrevDecl)) 13802 return NTK_TypeAlias; 13803 else if (isa<ClassTemplateDecl>(PrevDecl)) 13804 return NTK_Template; 13805 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13806 return NTK_TypeAliasTemplate; 13807 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13808 return NTK_TemplateTemplateArgument; 13809 switch (TTK) { 13810 case TTK_Struct: 13811 case TTK_Interface: 13812 case TTK_Class: 13813 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13814 case TTK_Union: 13815 return NTK_NonUnion; 13816 case TTK_Enum: 13817 return NTK_NonEnum; 13818 } 13819 llvm_unreachable("invalid TTK"); 13820 } 13821 13822 /// Determine whether a tag with a given kind is acceptable 13823 /// as a redeclaration of the given tag declaration. 13824 /// 13825 /// \returns true if the new tag kind is acceptable, false otherwise. 13826 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13827 TagTypeKind NewTag, bool isDefinition, 13828 SourceLocation NewTagLoc, 13829 const IdentifierInfo *Name) { 13830 // C++ [dcl.type.elab]p3: 13831 // The class-key or enum keyword present in the 13832 // elaborated-type-specifier shall agree in kind with the 13833 // declaration to which the name in the elaborated-type-specifier 13834 // refers. This rule also applies to the form of 13835 // elaborated-type-specifier that declares a class-name or 13836 // friend class since it can be construed as referring to the 13837 // definition of the class. Thus, in any 13838 // elaborated-type-specifier, the enum keyword shall be used to 13839 // refer to an enumeration (7.2), the union class-key shall be 13840 // used to refer to a union (clause 9), and either the class or 13841 // struct class-key shall be used to refer to a class (clause 9) 13842 // declared using the class or struct class-key. 13843 TagTypeKind OldTag = Previous->getTagKind(); 13844 if (OldTag != NewTag && 13845 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 13846 return false; 13847 13848 // Tags are compatible, but we might still want to warn on mismatched tags. 13849 // Non-class tags can't be mismatched at this point. 13850 if (!isClassCompatTagKind(NewTag)) 13851 return true; 13852 13853 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 13854 // by our warning analysis. We don't want to warn about mismatches with (eg) 13855 // declarations in system headers that are designed to be specialized, but if 13856 // a user asks us to warn, we should warn if their code contains mismatched 13857 // declarations. 13858 auto IsIgnoredLoc = [&](SourceLocation Loc) { 13859 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 13860 Loc); 13861 }; 13862 if (IsIgnoredLoc(NewTagLoc)) 13863 return true; 13864 13865 auto IsIgnored = [&](const TagDecl *Tag) { 13866 return IsIgnoredLoc(Tag->getLocation()); 13867 }; 13868 while (IsIgnored(Previous)) { 13869 Previous = Previous->getPreviousDecl(); 13870 if (!Previous) 13871 return true; 13872 OldTag = Previous->getTagKind(); 13873 } 13874 13875 bool isTemplate = false; 13876 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13877 isTemplate = Record->getDescribedClassTemplate(); 13878 13879 if (inTemplateInstantiation()) { 13880 if (OldTag != NewTag) { 13881 // In a template instantiation, do not offer fix-its for tag mismatches 13882 // since they usually mess up the template instead of fixing the problem. 13883 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13884 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13885 << getRedeclDiagFromTagKind(OldTag); 13886 // FIXME: Note previous location? 13887 } 13888 return true; 13889 } 13890 13891 if (isDefinition) { 13892 // On definitions, check all previous tags and issue a fix-it for each 13893 // one that doesn't match the current tag. 13894 if (Previous->getDefinition()) { 13895 // Don't suggest fix-its for redefinitions. 13896 return true; 13897 } 13898 13899 bool previousMismatch = false; 13900 for (const TagDecl *I : Previous->redecls()) { 13901 if (I->getTagKind() != NewTag) { 13902 // Ignore previous declarations for which the warning was disabled. 13903 if (IsIgnored(I)) 13904 continue; 13905 13906 if (!previousMismatch) { 13907 previousMismatch = true; 13908 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13909 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13910 << getRedeclDiagFromTagKind(I->getTagKind()); 13911 } 13912 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13913 << getRedeclDiagFromTagKind(NewTag) 13914 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13915 TypeWithKeyword::getTagTypeKindName(NewTag)); 13916 } 13917 } 13918 return true; 13919 } 13920 13921 // Identify the prevailing tag kind: this is the kind of the definition (if 13922 // there is a non-ignored definition), or otherwise the kind of the prior 13923 // (non-ignored) declaration. 13924 const TagDecl *PrevDef = Previous->getDefinition(); 13925 if (PrevDef && IsIgnored(PrevDef)) 13926 PrevDef = nullptr; 13927 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 13928 if (Redecl->getTagKind() != NewTag) { 13929 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13930 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13931 << getRedeclDiagFromTagKind(OldTag); 13932 Diag(Redecl->getLocation(), diag::note_previous_use); 13933 13934 // If there is a previous definition, suggest a fix-it. 13935 if (PrevDef) { 13936 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13937 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13938 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13939 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13940 } 13941 } 13942 13943 return true; 13944 } 13945 13946 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13947 /// from an outer enclosing namespace or file scope inside a friend declaration. 13948 /// This should provide the commented out code in the following snippet: 13949 /// namespace N { 13950 /// struct X; 13951 /// namespace M { 13952 /// struct Y { friend struct /*N::*/ X; }; 13953 /// } 13954 /// } 13955 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13956 SourceLocation NameLoc) { 13957 // While the decl is in a namespace, do repeated lookup of that name and see 13958 // if we get the same namespace back. If we do not, continue until 13959 // translation unit scope, at which point we have a fully qualified NNS. 13960 SmallVector<IdentifierInfo *, 4> Namespaces; 13961 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13962 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13963 // This tag should be declared in a namespace, which can only be enclosed by 13964 // other namespaces. Bail if there's an anonymous namespace in the chain. 13965 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13966 if (!Namespace || Namespace->isAnonymousNamespace()) 13967 return FixItHint(); 13968 IdentifierInfo *II = Namespace->getIdentifier(); 13969 Namespaces.push_back(II); 13970 NamedDecl *Lookup = SemaRef.LookupSingleName( 13971 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13972 if (Lookup == Namespace) 13973 break; 13974 } 13975 13976 // Once we have all the namespaces, reverse them to go outermost first, and 13977 // build an NNS. 13978 SmallString<64> Insertion; 13979 llvm::raw_svector_ostream OS(Insertion); 13980 if (DC->isTranslationUnit()) 13981 OS << "::"; 13982 std::reverse(Namespaces.begin(), Namespaces.end()); 13983 for (auto *II : Namespaces) 13984 OS << II->getName() << "::"; 13985 return FixItHint::CreateInsertion(NameLoc, Insertion); 13986 } 13987 13988 /// Determine whether a tag originally declared in context \p OldDC can 13989 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 13990 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13991 /// using-declaration). 13992 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13993 DeclContext *NewDC) { 13994 OldDC = OldDC->getRedeclContext(); 13995 NewDC = NewDC->getRedeclContext(); 13996 13997 if (OldDC->Equals(NewDC)) 13998 return true; 13999 14000 // In MSVC mode, we allow a redeclaration if the contexts are related (either 14001 // encloses the other). 14002 if (S.getLangOpts().MSVCCompat && 14003 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 14004 return true; 14005 14006 return false; 14007 } 14008 14009 /// This is invoked when we see 'struct foo' or 'struct {'. In the 14010 /// former case, Name will be non-null. In the later case, Name will be null. 14011 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 14012 /// reference/declaration/definition of a tag. 14013 /// 14014 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 14015 /// trailing-type-specifier) other than one in an alias-declaration. 14016 /// 14017 /// \param SkipBody If non-null, will be set to indicate if the caller should 14018 /// skip the definition of this tag and treat it as if it were a declaration. 14019 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 14020 SourceLocation KWLoc, CXXScopeSpec &SS, 14021 IdentifierInfo *Name, SourceLocation NameLoc, 14022 const ParsedAttributesView &Attrs, AccessSpecifier AS, 14023 SourceLocation ModulePrivateLoc, 14024 MultiTemplateParamsArg TemplateParameterLists, 14025 bool &OwnedDecl, bool &IsDependent, 14026 SourceLocation ScopedEnumKWLoc, 14027 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 14028 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 14029 SkipBodyInfo *SkipBody) { 14030 // If this is not a definition, it must have a name. 14031 IdentifierInfo *OrigName = Name; 14032 assert((Name != nullptr || TUK == TUK_Definition) && 14033 "Nameless record must be a definition!"); 14034 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 14035 14036 OwnedDecl = false; 14037 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14038 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 14039 14040 // FIXME: Check member specializations more carefully. 14041 bool isMemberSpecialization = false; 14042 bool Invalid = false; 14043 14044 // We only need to do this matching if we have template parameters 14045 // or a scope specifier, which also conveniently avoids this work 14046 // for non-C++ cases. 14047 if (TemplateParameterLists.size() > 0 || 14048 (SS.isNotEmpty() && TUK != TUK_Reference)) { 14049 if (TemplateParameterList *TemplateParams = 14050 MatchTemplateParametersToScopeSpecifier( 14051 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 14052 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 14053 if (Kind == TTK_Enum) { 14054 Diag(KWLoc, diag::err_enum_template); 14055 return nullptr; 14056 } 14057 14058 if (TemplateParams->size() > 0) { 14059 // This is a declaration or definition of a class template (which may 14060 // be a member of another template). 14061 14062 if (Invalid) 14063 return nullptr; 14064 14065 OwnedDecl = false; 14066 DeclResult Result = CheckClassTemplate( 14067 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 14068 AS, ModulePrivateLoc, 14069 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 14070 TemplateParameterLists.data(), SkipBody); 14071 return Result.get(); 14072 } else { 14073 // The "template<>" header is extraneous. 14074 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14075 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14076 isMemberSpecialization = true; 14077 } 14078 } 14079 } 14080 14081 // Figure out the underlying type if this a enum declaration. We need to do 14082 // this early, because it's needed to detect if this is an incompatible 14083 // redeclaration. 14084 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 14085 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 14086 14087 if (Kind == TTK_Enum) { 14088 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 14089 // No underlying type explicitly specified, or we failed to parse the 14090 // type, default to int. 14091 EnumUnderlying = Context.IntTy.getTypePtr(); 14092 } else if (UnderlyingType.get()) { 14093 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 14094 // integral type; any cv-qualification is ignored. 14095 TypeSourceInfo *TI = nullptr; 14096 GetTypeFromParser(UnderlyingType.get(), &TI); 14097 EnumUnderlying = TI; 14098 14099 if (CheckEnumUnderlyingType(TI)) 14100 // Recover by falling back to int. 14101 EnumUnderlying = Context.IntTy.getTypePtr(); 14102 14103 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 14104 UPPC_FixedUnderlyingType)) 14105 EnumUnderlying = Context.IntTy.getTypePtr(); 14106 14107 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14108 // For MSVC ABI compatibility, unfixed enums must use an underlying type 14109 // of 'int'. However, if this is an unfixed forward declaration, don't set 14110 // the underlying type unless the user enables -fms-compatibility. This 14111 // makes unfixed forward declared enums incomplete and is more conforming. 14112 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 14113 EnumUnderlying = Context.IntTy.getTypePtr(); 14114 } 14115 } 14116 14117 DeclContext *SearchDC = CurContext; 14118 DeclContext *DC = CurContext; 14119 bool isStdBadAlloc = false; 14120 bool isStdAlignValT = false; 14121 14122 RedeclarationKind Redecl = forRedeclarationInCurContext(); 14123 if (TUK == TUK_Friend || TUK == TUK_Reference) 14124 Redecl = NotForRedeclaration; 14125 14126 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 14127 /// implemented asks for structural equivalence checking, the returned decl 14128 /// here is passed back to the parser, allowing the tag body to be parsed. 14129 auto createTagFromNewDecl = [&]() -> TagDecl * { 14130 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 14131 // If there is an identifier, use the location of the identifier as the 14132 // location of the decl, otherwise use the location of the struct/union 14133 // keyword. 14134 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14135 TagDecl *New = nullptr; 14136 14137 if (Kind == TTK_Enum) { 14138 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 14139 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 14140 // If this is an undefined enum, bail. 14141 if (TUK != TUK_Definition && !Invalid) 14142 return nullptr; 14143 if (EnumUnderlying) { 14144 EnumDecl *ED = cast<EnumDecl>(New); 14145 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 14146 ED->setIntegerTypeSourceInfo(TI); 14147 else 14148 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 14149 ED->setPromotionType(ED->getIntegerType()); 14150 } 14151 } else { // struct/union 14152 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14153 nullptr); 14154 } 14155 14156 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14157 // Add alignment attributes if necessary; these attributes are checked 14158 // when the ASTContext lays out the structure. 14159 // 14160 // It is important for implementing the correct semantics that this 14161 // happen here (in ActOnTag). The #pragma pack stack is 14162 // maintained as a result of parser callbacks which can occur at 14163 // many points during the parsing of a struct declaration (because 14164 // the #pragma tokens are effectively skipped over during the 14165 // parsing of the struct). 14166 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14167 AddAlignmentAttributesForRecord(RD); 14168 AddMsStructLayoutForRecord(RD); 14169 } 14170 } 14171 New->setLexicalDeclContext(CurContext); 14172 return New; 14173 }; 14174 14175 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 14176 if (Name && SS.isNotEmpty()) { 14177 // We have a nested-name tag ('struct foo::bar'). 14178 14179 // Check for invalid 'foo::'. 14180 if (SS.isInvalid()) { 14181 Name = nullptr; 14182 goto CreateNewDecl; 14183 } 14184 14185 // If this is a friend or a reference to a class in a dependent 14186 // context, don't try to make a decl for it. 14187 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14188 DC = computeDeclContext(SS, false); 14189 if (!DC) { 14190 IsDependent = true; 14191 return nullptr; 14192 } 14193 } else { 14194 DC = computeDeclContext(SS, true); 14195 if (!DC) { 14196 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 14197 << SS.getRange(); 14198 return nullptr; 14199 } 14200 } 14201 14202 if (RequireCompleteDeclContext(SS, DC)) 14203 return nullptr; 14204 14205 SearchDC = DC; 14206 // Look-up name inside 'foo::'. 14207 LookupQualifiedName(Previous, DC); 14208 14209 if (Previous.isAmbiguous()) 14210 return nullptr; 14211 14212 if (Previous.empty()) { 14213 // Name lookup did not find anything. However, if the 14214 // nested-name-specifier refers to the current instantiation, 14215 // and that current instantiation has any dependent base 14216 // classes, we might find something at instantiation time: treat 14217 // this as a dependent elaborated-type-specifier. 14218 // But this only makes any sense for reference-like lookups. 14219 if (Previous.wasNotFoundInCurrentInstantiation() && 14220 (TUK == TUK_Reference || TUK == TUK_Friend)) { 14221 IsDependent = true; 14222 return nullptr; 14223 } 14224 14225 // A tag 'foo::bar' must already exist. 14226 Diag(NameLoc, diag::err_not_tag_in_scope) 14227 << Kind << Name << DC << SS.getRange(); 14228 Name = nullptr; 14229 Invalid = true; 14230 goto CreateNewDecl; 14231 } 14232 } else if (Name) { 14233 // C++14 [class.mem]p14: 14234 // If T is the name of a class, then each of the following shall have a 14235 // name different from T: 14236 // -- every member of class T that is itself a type 14237 if (TUK != TUK_Reference && TUK != TUK_Friend && 14238 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 14239 return nullptr; 14240 14241 // If this is a named struct, check to see if there was a previous forward 14242 // declaration or definition. 14243 // FIXME: We're looking into outer scopes here, even when we 14244 // shouldn't be. Doing so can result in ambiguities that we 14245 // shouldn't be diagnosing. 14246 LookupName(Previous, S); 14247 14248 // When declaring or defining a tag, ignore ambiguities introduced 14249 // by types using'ed into this scope. 14250 if (Previous.isAmbiguous() && 14251 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 14252 LookupResult::Filter F = Previous.makeFilter(); 14253 while (F.hasNext()) { 14254 NamedDecl *ND = F.next(); 14255 if (!ND->getDeclContext()->getRedeclContext()->Equals( 14256 SearchDC->getRedeclContext())) 14257 F.erase(); 14258 } 14259 F.done(); 14260 } 14261 14262 // C++11 [namespace.memdef]p3: 14263 // If the name in a friend declaration is neither qualified nor 14264 // a template-id and the declaration is a function or an 14265 // elaborated-type-specifier, the lookup to determine whether 14266 // the entity has been previously declared shall not consider 14267 // any scopes outside the innermost enclosing namespace. 14268 // 14269 // MSVC doesn't implement the above rule for types, so a friend tag 14270 // declaration may be a redeclaration of a type declared in an enclosing 14271 // scope. They do implement this rule for friend functions. 14272 // 14273 // Does it matter that this should be by scope instead of by 14274 // semantic context? 14275 if (!Previous.empty() && TUK == TUK_Friend) { 14276 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 14277 LookupResult::Filter F = Previous.makeFilter(); 14278 bool FriendSawTagOutsideEnclosingNamespace = false; 14279 while (F.hasNext()) { 14280 NamedDecl *ND = F.next(); 14281 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14282 if (DC->isFileContext() && 14283 !EnclosingNS->Encloses(ND->getDeclContext())) { 14284 if (getLangOpts().MSVCCompat) 14285 FriendSawTagOutsideEnclosingNamespace = true; 14286 else 14287 F.erase(); 14288 } 14289 } 14290 F.done(); 14291 14292 // Diagnose this MSVC extension in the easy case where lookup would have 14293 // unambiguously found something outside the enclosing namespace. 14294 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 14295 NamedDecl *ND = Previous.getFoundDecl(); 14296 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 14297 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 14298 } 14299 } 14300 14301 // Note: there used to be some attempt at recovery here. 14302 if (Previous.isAmbiguous()) 14303 return nullptr; 14304 14305 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 14306 // FIXME: This makes sure that we ignore the contexts associated 14307 // with C structs, unions, and enums when looking for a matching 14308 // tag declaration or definition. See the similar lookup tweak 14309 // in Sema::LookupName; is there a better way to deal with this? 14310 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 14311 SearchDC = SearchDC->getParent(); 14312 } 14313 } 14314 14315 if (Previous.isSingleResult() && 14316 Previous.getFoundDecl()->isTemplateParameter()) { 14317 // Maybe we will complain about the shadowed template parameter. 14318 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 14319 // Just pretend that we didn't see the previous declaration. 14320 Previous.clear(); 14321 } 14322 14323 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 14324 DC->Equals(getStdNamespace())) { 14325 if (Name->isStr("bad_alloc")) { 14326 // This is a declaration of or a reference to "std::bad_alloc". 14327 isStdBadAlloc = true; 14328 14329 // If std::bad_alloc has been implicitly declared (but made invisible to 14330 // name lookup), fill in this implicit declaration as the previous 14331 // declaration, so that the declarations get chained appropriately. 14332 if (Previous.empty() && StdBadAlloc) 14333 Previous.addDecl(getStdBadAlloc()); 14334 } else if (Name->isStr("align_val_t")) { 14335 isStdAlignValT = true; 14336 if (Previous.empty() && StdAlignValT) 14337 Previous.addDecl(getStdAlignValT()); 14338 } 14339 } 14340 14341 // If we didn't find a previous declaration, and this is a reference 14342 // (or friend reference), move to the correct scope. In C++, we 14343 // also need to do a redeclaration lookup there, just in case 14344 // there's a shadow friend decl. 14345 if (Name && Previous.empty() && 14346 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 14347 if (Invalid) goto CreateNewDecl; 14348 assert(SS.isEmpty()); 14349 14350 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 14351 // C++ [basic.scope.pdecl]p5: 14352 // -- for an elaborated-type-specifier of the form 14353 // 14354 // class-key identifier 14355 // 14356 // if the elaborated-type-specifier is used in the 14357 // decl-specifier-seq or parameter-declaration-clause of a 14358 // function defined in namespace scope, the identifier is 14359 // declared as a class-name in the namespace that contains 14360 // the declaration; otherwise, except as a friend 14361 // declaration, the identifier is declared in the smallest 14362 // non-class, non-function-prototype scope that contains the 14363 // declaration. 14364 // 14365 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 14366 // C structs and unions. 14367 // 14368 // It is an error in C++ to declare (rather than define) an enum 14369 // type, including via an elaborated type specifier. We'll 14370 // diagnose that later; for now, declare the enum in the same 14371 // scope as we would have picked for any other tag type. 14372 // 14373 // GNU C also supports this behavior as part of its incomplete 14374 // enum types extension, while GNU C++ does not. 14375 // 14376 // Find the context where we'll be declaring the tag. 14377 // FIXME: We would like to maintain the current DeclContext as the 14378 // lexical context, 14379 SearchDC = getTagInjectionContext(SearchDC); 14380 14381 // Find the scope where we'll be declaring the tag. 14382 S = getTagInjectionScope(S, getLangOpts()); 14383 } else { 14384 assert(TUK == TUK_Friend); 14385 // C++ [namespace.memdef]p3: 14386 // If a friend declaration in a non-local class first declares a 14387 // class or function, the friend class or function is a member of 14388 // the innermost enclosing namespace. 14389 SearchDC = SearchDC->getEnclosingNamespaceContext(); 14390 } 14391 14392 // In C++, we need to do a redeclaration lookup to properly 14393 // diagnose some problems. 14394 // FIXME: redeclaration lookup is also used (with and without C++) to find a 14395 // hidden declaration so that we don't get ambiguity errors when using a 14396 // type declared by an elaborated-type-specifier. In C that is not correct 14397 // and we should instead merge compatible types found by lookup. 14398 if (getLangOpts().CPlusPlus) { 14399 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14400 LookupQualifiedName(Previous, SearchDC); 14401 } else { 14402 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14403 LookupName(Previous, S); 14404 } 14405 } 14406 14407 // If we have a known previous declaration to use, then use it. 14408 if (Previous.empty() && SkipBody && SkipBody->Previous) 14409 Previous.addDecl(SkipBody->Previous); 14410 14411 if (!Previous.empty()) { 14412 NamedDecl *PrevDecl = Previous.getFoundDecl(); 14413 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 14414 14415 // It's okay to have a tag decl in the same scope as a typedef 14416 // which hides a tag decl in the same scope. Finding this 14417 // insanity with a redeclaration lookup can only actually happen 14418 // in C++. 14419 // 14420 // This is also okay for elaborated-type-specifiers, which is 14421 // technically forbidden by the current standard but which is 14422 // okay according to the likely resolution of an open issue; 14423 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 14424 if (getLangOpts().CPlusPlus) { 14425 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14426 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 14427 TagDecl *Tag = TT->getDecl(); 14428 if (Tag->getDeclName() == Name && 14429 Tag->getDeclContext()->getRedeclContext() 14430 ->Equals(TD->getDeclContext()->getRedeclContext())) { 14431 PrevDecl = Tag; 14432 Previous.clear(); 14433 Previous.addDecl(Tag); 14434 Previous.resolveKind(); 14435 } 14436 } 14437 } 14438 } 14439 14440 // If this is a redeclaration of a using shadow declaration, it must 14441 // declare a tag in the same context. In MSVC mode, we allow a 14442 // redefinition if either context is within the other. 14443 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 14444 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 14445 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 14446 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 14447 !(OldTag && isAcceptableTagRedeclContext( 14448 *this, OldTag->getDeclContext(), SearchDC))) { 14449 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 14450 Diag(Shadow->getTargetDecl()->getLocation(), 14451 diag::note_using_decl_target); 14452 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 14453 << 0; 14454 // Recover by ignoring the old declaration. 14455 Previous.clear(); 14456 goto CreateNewDecl; 14457 } 14458 } 14459 14460 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 14461 // If this is a use of a previous tag, or if the tag is already declared 14462 // in the same scope (so that the definition/declaration completes or 14463 // rementions the tag), reuse the decl. 14464 if (TUK == TUK_Reference || TUK == TUK_Friend || 14465 isDeclInScope(DirectPrevDecl, SearchDC, S, 14466 SS.isNotEmpty() || isMemberSpecialization)) { 14467 // Make sure that this wasn't declared as an enum and now used as a 14468 // struct or something similar. 14469 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14470 TUK == TUK_Definition, KWLoc, 14471 Name)) { 14472 bool SafeToContinue 14473 = (PrevTagDecl->getTagKind() != TTK_Enum && 14474 Kind != TTK_Enum); 14475 if (SafeToContinue) 14476 Diag(KWLoc, diag::err_use_with_wrong_tag) 14477 << Name 14478 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14479 PrevTagDecl->getKindName()); 14480 else 14481 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14482 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14483 14484 if (SafeToContinue) 14485 Kind = PrevTagDecl->getTagKind(); 14486 else { 14487 // Recover by making this an anonymous redefinition. 14488 Name = nullptr; 14489 Previous.clear(); 14490 Invalid = true; 14491 } 14492 } 14493 14494 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14495 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14496 14497 // If this is an elaborated-type-specifier for a scoped enumeration, 14498 // the 'class' keyword is not necessary and not permitted. 14499 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14500 if (ScopedEnum) 14501 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14502 << PrevEnum->isScoped() 14503 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14504 return PrevTagDecl; 14505 } 14506 14507 QualType EnumUnderlyingTy; 14508 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14509 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14510 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14511 EnumUnderlyingTy = QualType(T, 0); 14512 14513 // All conflicts with previous declarations are recovered by 14514 // returning the previous declaration, unless this is a definition, 14515 // in which case we want the caller to bail out. 14516 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14517 ScopedEnum, EnumUnderlyingTy, 14518 IsFixed, PrevEnum)) 14519 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14520 } 14521 14522 // C++11 [class.mem]p1: 14523 // A member shall not be declared twice in the member-specification, 14524 // except that a nested class or member class template can be declared 14525 // and then later defined. 14526 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14527 S->isDeclScope(PrevDecl)) { 14528 Diag(NameLoc, diag::ext_member_redeclared); 14529 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14530 } 14531 14532 if (!Invalid) { 14533 // If this is a use, just return the declaration we found, unless 14534 // we have attributes. 14535 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14536 if (!Attrs.empty()) { 14537 // FIXME: Diagnose these attributes. For now, we create a new 14538 // declaration to hold them. 14539 } else if (TUK == TUK_Reference && 14540 (PrevTagDecl->getFriendObjectKind() == 14541 Decl::FOK_Undeclared || 14542 PrevDecl->getOwningModule() != getCurrentModule()) && 14543 SS.isEmpty()) { 14544 // This declaration is a reference to an existing entity, but 14545 // has different visibility from that entity: it either makes 14546 // a friend visible or it makes a type visible in a new module. 14547 // In either case, create a new declaration. We only do this if 14548 // the declaration would have meant the same thing if no prior 14549 // declaration were found, that is, if it was found in the same 14550 // scope where we would have injected a declaration. 14551 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14552 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14553 return PrevTagDecl; 14554 // This is in the injected scope, create a new declaration in 14555 // that scope. 14556 S = getTagInjectionScope(S, getLangOpts()); 14557 } else { 14558 return PrevTagDecl; 14559 } 14560 } 14561 14562 // Diagnose attempts to redefine a tag. 14563 if (TUK == TUK_Definition) { 14564 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14565 // If we're defining a specialization and the previous definition 14566 // is from an implicit instantiation, don't emit an error 14567 // here; we'll catch this in the general case below. 14568 bool IsExplicitSpecializationAfterInstantiation = false; 14569 if (isMemberSpecialization) { 14570 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14571 IsExplicitSpecializationAfterInstantiation = 14572 RD->getTemplateSpecializationKind() != 14573 TSK_ExplicitSpecialization; 14574 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14575 IsExplicitSpecializationAfterInstantiation = 14576 ED->getTemplateSpecializationKind() != 14577 TSK_ExplicitSpecialization; 14578 } 14579 14580 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14581 // not keep more that one definition around (merge them). However, 14582 // ensure the decl passes the structural compatibility check in 14583 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14584 NamedDecl *Hidden = nullptr; 14585 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14586 // There is a definition of this tag, but it is not visible. We 14587 // explicitly make use of C++'s one definition rule here, and 14588 // assume that this definition is identical to the hidden one 14589 // we already have. Make the existing definition visible and 14590 // use it in place of this one. 14591 if (!getLangOpts().CPlusPlus) { 14592 // Postpone making the old definition visible until after we 14593 // complete parsing the new one and do the structural 14594 // comparison. 14595 SkipBody->CheckSameAsPrevious = true; 14596 SkipBody->New = createTagFromNewDecl(); 14597 SkipBody->Previous = Def; 14598 return Def; 14599 } else { 14600 SkipBody->ShouldSkip = true; 14601 SkipBody->Previous = Def; 14602 makeMergedDefinitionVisible(Hidden); 14603 // Carry on and handle it like a normal definition. We'll 14604 // skip starting the definitiion later. 14605 } 14606 } else if (!IsExplicitSpecializationAfterInstantiation) { 14607 // A redeclaration in function prototype scope in C isn't 14608 // visible elsewhere, so merely issue a warning. 14609 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14610 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14611 else 14612 Diag(NameLoc, diag::err_redefinition) << Name; 14613 notePreviousDefinition(Def, 14614 NameLoc.isValid() ? NameLoc : KWLoc); 14615 // If this is a redefinition, recover by making this 14616 // struct be anonymous, which will make any later 14617 // references get the previous definition. 14618 Name = nullptr; 14619 Previous.clear(); 14620 Invalid = true; 14621 } 14622 } else { 14623 // If the type is currently being defined, complain 14624 // about a nested redefinition. 14625 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14626 if (TD->isBeingDefined()) { 14627 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14628 Diag(PrevTagDecl->getLocation(), 14629 diag::note_previous_definition); 14630 Name = nullptr; 14631 Previous.clear(); 14632 Invalid = true; 14633 } 14634 } 14635 14636 // Okay, this is definition of a previously declared or referenced 14637 // tag. We're going to create a new Decl for it. 14638 } 14639 14640 // Okay, we're going to make a redeclaration. If this is some kind 14641 // of reference, make sure we build the redeclaration in the same DC 14642 // as the original, and ignore the current access specifier. 14643 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14644 SearchDC = PrevTagDecl->getDeclContext(); 14645 AS = AS_none; 14646 } 14647 } 14648 // If we get here we have (another) forward declaration or we 14649 // have a definition. Just create a new decl. 14650 14651 } else { 14652 // If we get here, this is a definition of a new tag type in a nested 14653 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14654 // new decl/type. We set PrevDecl to NULL so that the entities 14655 // have distinct types. 14656 Previous.clear(); 14657 } 14658 // If we get here, we're going to create a new Decl. If PrevDecl 14659 // is non-NULL, it's a definition of the tag declared by 14660 // PrevDecl. If it's NULL, we have a new definition. 14661 14662 // Otherwise, PrevDecl is not a tag, but was found with tag 14663 // lookup. This is only actually possible in C++, where a few 14664 // things like templates still live in the tag namespace. 14665 } else { 14666 // Use a better diagnostic if an elaborated-type-specifier 14667 // found the wrong kind of type on the first 14668 // (non-redeclaration) lookup. 14669 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14670 !Previous.isForRedeclaration()) { 14671 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14672 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14673 << Kind; 14674 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14675 Invalid = true; 14676 14677 // Otherwise, only diagnose if the declaration is in scope. 14678 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14679 SS.isNotEmpty() || isMemberSpecialization)) { 14680 // do nothing 14681 14682 // Diagnose implicit declarations introduced by elaborated types. 14683 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14684 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14685 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14686 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14687 Invalid = true; 14688 14689 // Otherwise it's a declaration. Call out a particularly common 14690 // case here. 14691 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14692 unsigned Kind = 0; 14693 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14694 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14695 << Name << Kind << TND->getUnderlyingType(); 14696 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14697 Invalid = true; 14698 14699 // Otherwise, diagnose. 14700 } else { 14701 // The tag name clashes with something else in the target scope, 14702 // issue an error and recover by making this tag be anonymous. 14703 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14704 notePreviousDefinition(PrevDecl, NameLoc); 14705 Name = nullptr; 14706 Invalid = true; 14707 } 14708 14709 // The existing declaration isn't relevant to us; we're in a 14710 // new scope, so clear out the previous declaration. 14711 Previous.clear(); 14712 } 14713 } 14714 14715 CreateNewDecl: 14716 14717 TagDecl *PrevDecl = nullptr; 14718 if (Previous.isSingleResult()) 14719 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14720 14721 // If there is an identifier, use the location of the identifier as the 14722 // location of the decl, otherwise use the location of the struct/union 14723 // keyword. 14724 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14725 14726 // Otherwise, create a new declaration. If there is a previous 14727 // declaration of the same entity, the two will be linked via 14728 // PrevDecl. 14729 TagDecl *New; 14730 14731 if (Kind == TTK_Enum) { 14732 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14733 // enum X { A, B, C } D; D should chain to X. 14734 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14735 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14736 ScopedEnumUsesClassTag, IsFixed); 14737 14738 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14739 StdAlignValT = cast<EnumDecl>(New); 14740 14741 // If this is an undefined enum, warn. 14742 if (TUK != TUK_Definition && !Invalid) { 14743 TagDecl *Def; 14744 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC) && 14745 cast<EnumDecl>(New)->isFixed()) { 14746 // C++0x: 7.2p2: opaque-enum-declaration. 14747 // Conflicts are diagnosed above. Do nothing. 14748 } 14749 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14750 Diag(Loc, diag::ext_forward_ref_enum_def) 14751 << New; 14752 Diag(Def->getLocation(), diag::note_previous_definition); 14753 } else { 14754 unsigned DiagID = diag::ext_forward_ref_enum; 14755 if (getLangOpts().MSVCCompat) 14756 DiagID = diag::ext_ms_forward_ref_enum; 14757 else if (getLangOpts().CPlusPlus) 14758 DiagID = diag::err_forward_ref_enum; 14759 Diag(Loc, DiagID); 14760 } 14761 } 14762 14763 if (EnumUnderlying) { 14764 EnumDecl *ED = cast<EnumDecl>(New); 14765 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14766 ED->setIntegerTypeSourceInfo(TI); 14767 else 14768 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14769 ED->setPromotionType(ED->getIntegerType()); 14770 assert(ED->isComplete() && "enum with type should be complete"); 14771 } 14772 } else { 14773 // struct/union/class 14774 14775 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14776 // struct X { int A; } D; D should chain to X. 14777 if (getLangOpts().CPlusPlus) { 14778 // FIXME: Look for a way to use RecordDecl for simple structs. 14779 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14780 cast_or_null<CXXRecordDecl>(PrevDecl)); 14781 14782 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14783 StdBadAlloc = cast<CXXRecordDecl>(New); 14784 } else 14785 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14786 cast_or_null<RecordDecl>(PrevDecl)); 14787 } 14788 14789 // C++11 [dcl.type]p3: 14790 // A type-specifier-seq shall not define a class or enumeration [...]. 14791 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14792 TUK == TUK_Definition) { 14793 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14794 << Context.getTagDeclType(New); 14795 Invalid = true; 14796 } 14797 14798 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14799 DC->getDeclKind() == Decl::Enum) { 14800 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14801 << Context.getTagDeclType(New); 14802 Invalid = true; 14803 } 14804 14805 // Maybe add qualifier info. 14806 if (SS.isNotEmpty()) { 14807 if (SS.isSet()) { 14808 // If this is either a declaration or a definition, check the 14809 // nested-name-specifier against the current context. 14810 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14811 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14812 isMemberSpecialization)) 14813 Invalid = true; 14814 14815 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14816 if (TemplateParameterLists.size() > 0) { 14817 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14818 } 14819 } 14820 else 14821 Invalid = true; 14822 } 14823 14824 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14825 // Add alignment attributes if necessary; these attributes are checked when 14826 // the ASTContext lays out the structure. 14827 // 14828 // It is important for implementing the correct semantics that this 14829 // happen here (in ActOnTag). The #pragma pack stack is 14830 // maintained as a result of parser callbacks which can occur at 14831 // many points during the parsing of a struct declaration (because 14832 // the #pragma tokens are effectively skipped over during the 14833 // parsing of the struct). 14834 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14835 AddAlignmentAttributesForRecord(RD); 14836 AddMsStructLayoutForRecord(RD); 14837 } 14838 } 14839 14840 if (ModulePrivateLoc.isValid()) { 14841 if (isMemberSpecialization) 14842 Diag(New->getLocation(), diag::err_module_private_specialization) 14843 << 2 14844 << FixItHint::CreateRemoval(ModulePrivateLoc); 14845 // __module_private__ does not apply to local classes. However, we only 14846 // diagnose this as an error when the declaration specifiers are 14847 // freestanding. Here, we just ignore the __module_private__. 14848 else if (!SearchDC->isFunctionOrMethod()) 14849 New->setModulePrivate(); 14850 } 14851 14852 // If this is a specialization of a member class (of a class template), 14853 // check the specialization. 14854 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14855 Invalid = true; 14856 14857 // If we're declaring or defining a tag in function prototype scope in C, 14858 // note that this type can only be used within the function and add it to 14859 // the list of decls to inject into the function definition scope. 14860 if ((Name || Kind == TTK_Enum) && 14861 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14862 if (getLangOpts().CPlusPlus) { 14863 // C++ [dcl.fct]p6: 14864 // Types shall not be defined in return or parameter types. 14865 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14866 Diag(Loc, diag::err_type_defined_in_param_type) 14867 << Name; 14868 Invalid = true; 14869 } 14870 } else if (!PrevDecl) { 14871 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14872 } 14873 } 14874 14875 if (Invalid) 14876 New->setInvalidDecl(); 14877 14878 // Set the lexical context. If the tag has a C++ scope specifier, the 14879 // lexical context will be different from the semantic context. 14880 New->setLexicalDeclContext(CurContext); 14881 14882 // Mark this as a friend decl if applicable. 14883 // In Microsoft mode, a friend declaration also acts as a forward 14884 // declaration so we always pass true to setObjectOfFriendDecl to make 14885 // the tag name visible. 14886 if (TUK == TUK_Friend) 14887 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14888 14889 // Set the access specifier. 14890 if (!Invalid && SearchDC->isRecord()) 14891 SetMemberAccessSpecifier(New, PrevDecl, AS); 14892 14893 if (PrevDecl) 14894 CheckRedeclarationModuleOwnership(New, PrevDecl); 14895 14896 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 14897 New->startDefinition(); 14898 14899 ProcessDeclAttributeList(S, New, Attrs); 14900 AddPragmaAttributes(S, New); 14901 14902 // If this has an identifier, add it to the scope stack. 14903 if (TUK == TUK_Friend) { 14904 // We might be replacing an existing declaration in the lookup tables; 14905 // if so, borrow its access specifier. 14906 if (PrevDecl) 14907 New->setAccess(PrevDecl->getAccess()); 14908 14909 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14910 DC->makeDeclVisibleInContext(New); 14911 if (Name) // can be null along some error paths 14912 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14913 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14914 } else if (Name) { 14915 S = getNonFieldDeclScope(S); 14916 PushOnScopeChains(New, S, true); 14917 } else { 14918 CurContext->addDecl(New); 14919 } 14920 14921 // If this is the C FILE type, notify the AST context. 14922 if (IdentifierInfo *II = New->getIdentifier()) 14923 if (!New->isInvalidDecl() && 14924 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14925 II->isStr("FILE")) 14926 Context.setFILEDecl(New); 14927 14928 if (PrevDecl) 14929 mergeDeclAttributes(New, PrevDecl); 14930 14931 // If there's a #pragma GCC visibility in scope, set the visibility of this 14932 // record. 14933 AddPushedVisibilityAttribute(New); 14934 14935 if (isMemberSpecialization && !New->isInvalidDecl()) 14936 CompleteMemberSpecialization(New, Previous); 14937 14938 OwnedDecl = true; 14939 // In C++, don't return an invalid declaration. We can't recover well from 14940 // the cases where we make the type anonymous. 14941 if (Invalid && getLangOpts().CPlusPlus) { 14942 if (New->isBeingDefined()) 14943 if (auto RD = dyn_cast<RecordDecl>(New)) 14944 RD->completeDefinition(); 14945 return nullptr; 14946 } else if (SkipBody && SkipBody->ShouldSkip) { 14947 return SkipBody->Previous; 14948 } else { 14949 return New; 14950 } 14951 } 14952 14953 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14954 AdjustDeclIfTemplate(TagD); 14955 TagDecl *Tag = cast<TagDecl>(TagD); 14956 14957 // Enter the tag context. 14958 PushDeclContext(S, Tag); 14959 14960 ActOnDocumentableDecl(TagD); 14961 14962 // If there's a #pragma GCC visibility in scope, set the visibility of this 14963 // record. 14964 AddPushedVisibilityAttribute(Tag); 14965 } 14966 14967 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14968 SkipBodyInfo &SkipBody) { 14969 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14970 return false; 14971 14972 // Make the previous decl visible. 14973 makeMergedDefinitionVisible(SkipBody.Previous); 14974 return true; 14975 } 14976 14977 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14978 assert(isa<ObjCContainerDecl>(IDecl) && 14979 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14980 DeclContext *OCD = cast<DeclContext>(IDecl); 14981 assert(getContainingDC(OCD) == CurContext && 14982 "The next DeclContext should be lexically contained in the current one."); 14983 CurContext = OCD; 14984 return IDecl; 14985 } 14986 14987 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14988 SourceLocation FinalLoc, 14989 bool IsFinalSpelledSealed, 14990 SourceLocation LBraceLoc) { 14991 AdjustDeclIfTemplate(TagD); 14992 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14993 14994 FieldCollector->StartClass(); 14995 14996 if (!Record->getIdentifier()) 14997 return; 14998 14999 if (FinalLoc.isValid()) 15000 Record->addAttr(new (Context) 15001 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 15002 15003 // C++ [class]p2: 15004 // [...] The class-name is also inserted into the scope of the 15005 // class itself; this is known as the injected-class-name. For 15006 // purposes of access checking, the injected-class-name is treated 15007 // as if it were a public member name. 15008 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 15009 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 15010 Record->getLocation(), Record->getIdentifier(), 15011 /*PrevDecl=*/nullptr, 15012 /*DelayTypeCreation=*/true); 15013 Context.getTypeDeclType(InjectedClassName, Record); 15014 InjectedClassName->setImplicit(); 15015 InjectedClassName->setAccess(AS_public); 15016 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 15017 InjectedClassName->setDescribedClassTemplate(Template); 15018 PushOnScopeChains(InjectedClassName, S); 15019 assert(InjectedClassName->isInjectedClassName() && 15020 "Broken injected-class-name"); 15021 } 15022 15023 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 15024 SourceRange BraceRange) { 15025 AdjustDeclIfTemplate(TagD); 15026 TagDecl *Tag = cast<TagDecl>(TagD); 15027 Tag->setBraceRange(BraceRange); 15028 15029 // Make sure we "complete" the definition even it is invalid. 15030 if (Tag->isBeingDefined()) { 15031 assert(Tag->isInvalidDecl() && "We should already have completed it"); 15032 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15033 RD->completeDefinition(); 15034 } 15035 15036 if (isa<CXXRecordDecl>(Tag)) { 15037 FieldCollector->FinishClass(); 15038 } 15039 15040 // Exit this scope of this tag's definition. 15041 PopDeclContext(); 15042 15043 if (getCurLexicalContext()->isObjCContainer() && 15044 Tag->getDeclContext()->isFileContext()) 15045 Tag->setTopLevelDeclInObjCContainer(); 15046 15047 // Notify the consumer that we've defined a tag. 15048 if (!Tag->isInvalidDecl()) 15049 Consumer.HandleTagDeclDefinition(Tag); 15050 } 15051 15052 void Sema::ActOnObjCContainerFinishDefinition() { 15053 // Exit this scope of this interface definition. 15054 PopDeclContext(); 15055 } 15056 15057 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 15058 assert(DC == CurContext && "Mismatch of container contexts"); 15059 OriginalLexicalContext = DC; 15060 ActOnObjCContainerFinishDefinition(); 15061 } 15062 15063 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 15064 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 15065 OriginalLexicalContext = nullptr; 15066 } 15067 15068 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 15069 AdjustDeclIfTemplate(TagD); 15070 TagDecl *Tag = cast<TagDecl>(TagD); 15071 Tag->setInvalidDecl(); 15072 15073 // Make sure we "complete" the definition even it is invalid. 15074 if (Tag->isBeingDefined()) { 15075 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15076 RD->completeDefinition(); 15077 } 15078 15079 // We're undoing ActOnTagStartDefinition here, not 15080 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 15081 // the FieldCollector. 15082 15083 PopDeclContext(); 15084 } 15085 15086 // Note that FieldName may be null for anonymous bitfields. 15087 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 15088 IdentifierInfo *FieldName, 15089 QualType FieldTy, bool IsMsStruct, 15090 Expr *BitWidth, bool *ZeroWidth) { 15091 // Default to true; that shouldn't confuse checks for emptiness 15092 if (ZeroWidth) 15093 *ZeroWidth = true; 15094 15095 // C99 6.7.2.1p4 - verify the field type. 15096 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 15097 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 15098 // Handle incomplete types with specific error. 15099 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 15100 return ExprError(); 15101 if (FieldName) 15102 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 15103 << FieldName << FieldTy << BitWidth->getSourceRange(); 15104 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 15105 << FieldTy << BitWidth->getSourceRange(); 15106 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 15107 UPPC_BitFieldWidth)) 15108 return ExprError(); 15109 15110 // If the bit-width is type- or value-dependent, don't try to check 15111 // it now. 15112 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 15113 return BitWidth; 15114 15115 llvm::APSInt Value; 15116 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 15117 if (ICE.isInvalid()) 15118 return ICE; 15119 BitWidth = ICE.get(); 15120 15121 if (Value != 0 && ZeroWidth) 15122 *ZeroWidth = false; 15123 15124 // Zero-width bitfield is ok for anonymous field. 15125 if (Value == 0 && FieldName) 15126 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 15127 15128 if (Value.isSigned() && Value.isNegative()) { 15129 if (FieldName) 15130 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 15131 << FieldName << Value.toString(10); 15132 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 15133 << Value.toString(10); 15134 } 15135 15136 if (!FieldTy->isDependentType()) { 15137 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 15138 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 15139 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 15140 15141 // Over-wide bitfields are an error in C or when using the MSVC bitfield 15142 // ABI. 15143 bool CStdConstraintViolation = 15144 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 15145 bool MSBitfieldViolation = 15146 Value.ugt(TypeStorageSize) && 15147 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 15148 if (CStdConstraintViolation || MSBitfieldViolation) { 15149 unsigned DiagWidth = 15150 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 15151 if (FieldName) 15152 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 15153 << FieldName << (unsigned)Value.getZExtValue() 15154 << !CStdConstraintViolation << DiagWidth; 15155 15156 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 15157 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 15158 << DiagWidth; 15159 } 15160 15161 // Warn on types where the user might conceivably expect to get all 15162 // specified bits as value bits: that's all integral types other than 15163 // 'bool'. 15164 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 15165 if (FieldName) 15166 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 15167 << FieldName << (unsigned)Value.getZExtValue() 15168 << (unsigned)TypeWidth; 15169 else 15170 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 15171 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 15172 } 15173 } 15174 15175 return BitWidth; 15176 } 15177 15178 /// ActOnField - Each field of a C struct/union is passed into this in order 15179 /// to create a FieldDecl object for it. 15180 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 15181 Declarator &D, Expr *BitfieldWidth) { 15182 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 15183 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 15184 /*InitStyle=*/ICIS_NoInit, AS_public); 15185 return Res; 15186 } 15187 15188 /// HandleField - Analyze a field of a C struct or a C++ data member. 15189 /// 15190 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 15191 SourceLocation DeclStart, 15192 Declarator &D, Expr *BitWidth, 15193 InClassInitStyle InitStyle, 15194 AccessSpecifier AS) { 15195 if (D.isDecompositionDeclarator()) { 15196 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 15197 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 15198 << Decomp.getSourceRange(); 15199 return nullptr; 15200 } 15201 15202 IdentifierInfo *II = D.getIdentifier(); 15203 SourceLocation Loc = DeclStart; 15204 if (II) Loc = D.getIdentifierLoc(); 15205 15206 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15207 QualType T = TInfo->getType(); 15208 if (getLangOpts().CPlusPlus) { 15209 CheckExtraCXXDefaultArguments(D); 15210 15211 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15212 UPPC_DataMemberType)) { 15213 D.setInvalidType(); 15214 T = Context.IntTy; 15215 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15216 } 15217 } 15218 15219 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15220 15221 if (D.getDeclSpec().isInlineSpecified()) 15222 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15223 << getLangOpts().CPlusPlus17; 15224 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15225 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15226 diag::err_invalid_thread) 15227 << DeclSpec::getSpecifierName(TSCS); 15228 15229 // Check to see if this name was declared as a member previously 15230 NamedDecl *PrevDecl = nullptr; 15231 LookupResult Previous(*this, II, Loc, LookupMemberName, 15232 ForVisibleRedeclaration); 15233 LookupName(Previous, S); 15234 switch (Previous.getResultKind()) { 15235 case LookupResult::Found: 15236 case LookupResult::FoundUnresolvedValue: 15237 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15238 break; 15239 15240 case LookupResult::FoundOverloaded: 15241 PrevDecl = Previous.getRepresentativeDecl(); 15242 break; 15243 15244 case LookupResult::NotFound: 15245 case LookupResult::NotFoundInCurrentInstantiation: 15246 case LookupResult::Ambiguous: 15247 break; 15248 } 15249 Previous.suppressDiagnostics(); 15250 15251 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15252 // Maybe we will complain about the shadowed template parameter. 15253 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15254 // Just pretend that we didn't see the previous declaration. 15255 PrevDecl = nullptr; 15256 } 15257 15258 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15259 PrevDecl = nullptr; 15260 15261 bool Mutable 15262 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 15263 SourceLocation TSSL = D.getBeginLoc(); 15264 FieldDecl *NewFD 15265 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 15266 TSSL, AS, PrevDecl, &D); 15267 15268 if (NewFD->isInvalidDecl()) 15269 Record->setInvalidDecl(); 15270 15271 if (D.getDeclSpec().isModulePrivateSpecified()) 15272 NewFD->setModulePrivate(); 15273 15274 if (NewFD->isInvalidDecl() && PrevDecl) { 15275 // Don't introduce NewFD into scope; there's already something 15276 // with the same name in the same scope. 15277 } else if (II) { 15278 PushOnScopeChains(NewFD, S); 15279 } else 15280 Record->addDecl(NewFD); 15281 15282 return NewFD; 15283 } 15284 15285 /// Build a new FieldDecl and check its well-formedness. 15286 /// 15287 /// This routine builds a new FieldDecl given the fields name, type, 15288 /// record, etc. \p PrevDecl should refer to any previous declaration 15289 /// with the same name and in the same scope as the field to be 15290 /// created. 15291 /// 15292 /// \returns a new FieldDecl. 15293 /// 15294 /// \todo The Declarator argument is a hack. It will be removed once 15295 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 15296 TypeSourceInfo *TInfo, 15297 RecordDecl *Record, SourceLocation Loc, 15298 bool Mutable, Expr *BitWidth, 15299 InClassInitStyle InitStyle, 15300 SourceLocation TSSL, 15301 AccessSpecifier AS, NamedDecl *PrevDecl, 15302 Declarator *D) { 15303 IdentifierInfo *II = Name.getAsIdentifierInfo(); 15304 bool InvalidDecl = false; 15305 if (D) InvalidDecl = D->isInvalidType(); 15306 15307 // If we receive a broken type, recover by assuming 'int' and 15308 // marking this declaration as invalid. 15309 if (T.isNull()) { 15310 InvalidDecl = true; 15311 T = Context.IntTy; 15312 } 15313 15314 QualType EltTy = Context.getBaseElementType(T); 15315 if (!EltTy->isDependentType()) { 15316 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 15317 // Fields of incomplete type force their record to be invalid. 15318 Record->setInvalidDecl(); 15319 InvalidDecl = true; 15320 } else { 15321 NamedDecl *Def; 15322 EltTy->isIncompleteType(&Def); 15323 if (Def && Def->isInvalidDecl()) { 15324 Record->setInvalidDecl(); 15325 InvalidDecl = true; 15326 } 15327 } 15328 } 15329 15330 // TR 18037 does not allow fields to be declared with address space 15331 if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || 15332 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 15333 Diag(Loc, diag::err_field_with_address_space); 15334 Record->setInvalidDecl(); 15335 InvalidDecl = true; 15336 } 15337 15338 if (LangOpts.OpenCL) { 15339 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 15340 // used as structure or union field: image, sampler, event or block types. 15341 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 15342 T->isBlockPointerType()) { 15343 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 15344 Record->setInvalidDecl(); 15345 InvalidDecl = true; 15346 } 15347 // OpenCL v1.2 s6.9.c: bitfields are not supported. 15348 if (BitWidth) { 15349 Diag(Loc, diag::err_opencl_bitfields); 15350 InvalidDecl = true; 15351 } 15352 } 15353 15354 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 15355 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 15356 T.hasQualifiers()) { 15357 InvalidDecl = true; 15358 Diag(Loc, diag::err_anon_bitfield_qualifiers); 15359 } 15360 15361 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15362 // than a variably modified type. 15363 if (!InvalidDecl && T->isVariablyModifiedType()) { 15364 bool SizeIsNegative; 15365 llvm::APSInt Oversized; 15366 15367 TypeSourceInfo *FixedTInfo = 15368 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 15369 SizeIsNegative, 15370 Oversized); 15371 if (FixedTInfo) { 15372 Diag(Loc, diag::warn_illegal_constant_array_size); 15373 TInfo = FixedTInfo; 15374 T = FixedTInfo->getType(); 15375 } else { 15376 if (SizeIsNegative) 15377 Diag(Loc, diag::err_typecheck_negative_array_size); 15378 else if (Oversized.getBoolValue()) 15379 Diag(Loc, diag::err_array_too_large) 15380 << Oversized.toString(10); 15381 else 15382 Diag(Loc, diag::err_typecheck_field_variable_size); 15383 InvalidDecl = true; 15384 } 15385 } 15386 15387 // Fields can not have abstract class types 15388 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 15389 diag::err_abstract_type_in_decl, 15390 AbstractFieldType)) 15391 InvalidDecl = true; 15392 15393 bool ZeroWidth = false; 15394 if (InvalidDecl) 15395 BitWidth = nullptr; 15396 // If this is declared as a bit-field, check the bit-field. 15397 if (BitWidth) { 15398 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 15399 &ZeroWidth).get(); 15400 if (!BitWidth) { 15401 InvalidDecl = true; 15402 BitWidth = nullptr; 15403 ZeroWidth = false; 15404 } 15405 } 15406 15407 // Check that 'mutable' is consistent with the type of the declaration. 15408 if (!InvalidDecl && Mutable) { 15409 unsigned DiagID = 0; 15410 if (T->isReferenceType()) 15411 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 15412 : diag::err_mutable_reference; 15413 else if (T.isConstQualified()) 15414 DiagID = diag::err_mutable_const; 15415 15416 if (DiagID) { 15417 SourceLocation ErrLoc = Loc; 15418 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 15419 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 15420 Diag(ErrLoc, DiagID); 15421 if (DiagID != diag::ext_mutable_reference) { 15422 Mutable = false; 15423 InvalidDecl = true; 15424 } 15425 } 15426 } 15427 15428 // C++11 [class.union]p8 (DR1460): 15429 // At most one variant member of a union may have a 15430 // brace-or-equal-initializer. 15431 if (InitStyle != ICIS_NoInit) 15432 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 15433 15434 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 15435 BitWidth, Mutable, InitStyle); 15436 if (InvalidDecl) 15437 NewFD->setInvalidDecl(); 15438 15439 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 15440 Diag(Loc, diag::err_duplicate_member) << II; 15441 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15442 NewFD->setInvalidDecl(); 15443 } 15444 15445 if (!InvalidDecl && getLangOpts().CPlusPlus) { 15446 if (Record->isUnion()) { 15447 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15448 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15449 if (RDecl->getDefinition()) { 15450 // C++ [class.union]p1: An object of a class with a non-trivial 15451 // constructor, a non-trivial copy constructor, a non-trivial 15452 // destructor, or a non-trivial copy assignment operator 15453 // cannot be a member of a union, nor can an array of such 15454 // objects. 15455 if (CheckNontrivialField(NewFD)) 15456 NewFD->setInvalidDecl(); 15457 } 15458 } 15459 15460 // C++ [class.union]p1: If a union contains a member of reference type, 15461 // the program is ill-formed, except when compiling with MSVC extensions 15462 // enabled. 15463 if (EltTy->isReferenceType()) { 15464 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15465 diag::ext_union_member_of_reference_type : 15466 diag::err_union_member_of_reference_type) 15467 << NewFD->getDeclName() << EltTy; 15468 if (!getLangOpts().MicrosoftExt) 15469 NewFD->setInvalidDecl(); 15470 } 15471 } 15472 } 15473 15474 // FIXME: We need to pass in the attributes given an AST 15475 // representation, not a parser representation. 15476 if (D) { 15477 // FIXME: The current scope is almost... but not entirely... correct here. 15478 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15479 15480 if (NewFD->hasAttrs()) 15481 CheckAlignasUnderalignment(NewFD); 15482 } 15483 15484 // In auto-retain/release, infer strong retension for fields of 15485 // retainable type. 15486 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15487 NewFD->setInvalidDecl(); 15488 15489 if (T.isObjCGCWeak()) 15490 Diag(Loc, diag::warn_attribute_weak_on_field); 15491 15492 NewFD->setAccess(AS); 15493 return NewFD; 15494 } 15495 15496 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15497 assert(FD); 15498 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15499 15500 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15501 return false; 15502 15503 QualType EltTy = Context.getBaseElementType(FD->getType()); 15504 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15505 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15506 if (RDecl->getDefinition()) { 15507 // We check for copy constructors before constructors 15508 // because otherwise we'll never get complaints about 15509 // copy constructors. 15510 15511 CXXSpecialMember member = CXXInvalid; 15512 // We're required to check for any non-trivial constructors. Since the 15513 // implicit default constructor is suppressed if there are any 15514 // user-declared constructors, we just need to check that there is a 15515 // trivial default constructor and a trivial copy constructor. (We don't 15516 // worry about move constructors here, since this is a C++98 check.) 15517 if (RDecl->hasNonTrivialCopyConstructor()) 15518 member = CXXCopyConstructor; 15519 else if (!RDecl->hasTrivialDefaultConstructor()) 15520 member = CXXDefaultConstructor; 15521 else if (RDecl->hasNonTrivialCopyAssignment()) 15522 member = CXXCopyAssignment; 15523 else if (RDecl->hasNonTrivialDestructor()) 15524 member = CXXDestructor; 15525 15526 if (member != CXXInvalid) { 15527 if (!getLangOpts().CPlusPlus11 && 15528 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15529 // Objective-C++ ARC: it is an error to have a non-trivial field of 15530 // a union. However, system headers in Objective-C programs 15531 // occasionally have Objective-C lifetime objects within unions, 15532 // and rather than cause the program to fail, we make those 15533 // members unavailable. 15534 SourceLocation Loc = FD->getLocation(); 15535 if (getSourceManager().isInSystemHeader(Loc)) { 15536 if (!FD->hasAttr<UnavailableAttr>()) 15537 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15538 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15539 return false; 15540 } 15541 } 15542 15543 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15544 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15545 diag::err_illegal_union_or_anon_struct_member) 15546 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15547 DiagnoseNontrivial(RDecl, member); 15548 return !getLangOpts().CPlusPlus11; 15549 } 15550 } 15551 } 15552 15553 return false; 15554 } 15555 15556 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15557 /// AST enum value. 15558 static ObjCIvarDecl::AccessControl 15559 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15560 switch (ivarVisibility) { 15561 default: llvm_unreachable("Unknown visitibility kind"); 15562 case tok::objc_private: return ObjCIvarDecl::Private; 15563 case tok::objc_public: return ObjCIvarDecl::Public; 15564 case tok::objc_protected: return ObjCIvarDecl::Protected; 15565 case tok::objc_package: return ObjCIvarDecl::Package; 15566 } 15567 } 15568 15569 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15570 /// in order to create an IvarDecl object for it. 15571 Decl *Sema::ActOnIvar(Scope *S, 15572 SourceLocation DeclStart, 15573 Declarator &D, Expr *BitfieldWidth, 15574 tok::ObjCKeywordKind Visibility) { 15575 15576 IdentifierInfo *II = D.getIdentifier(); 15577 Expr *BitWidth = (Expr*)BitfieldWidth; 15578 SourceLocation Loc = DeclStart; 15579 if (II) Loc = D.getIdentifierLoc(); 15580 15581 // FIXME: Unnamed fields can be handled in various different ways, for 15582 // example, unnamed unions inject all members into the struct namespace! 15583 15584 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15585 QualType T = TInfo->getType(); 15586 15587 if (BitWidth) { 15588 // 6.7.2.1p3, 6.7.2.1p4 15589 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15590 if (!BitWidth) 15591 D.setInvalidType(); 15592 } else { 15593 // Not a bitfield. 15594 15595 // validate II. 15596 15597 } 15598 if (T->isReferenceType()) { 15599 Diag(Loc, diag::err_ivar_reference_type); 15600 D.setInvalidType(); 15601 } 15602 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15603 // than a variably modified type. 15604 else if (T->isVariablyModifiedType()) { 15605 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15606 D.setInvalidType(); 15607 } 15608 15609 // Get the visibility (access control) for this ivar. 15610 ObjCIvarDecl::AccessControl ac = 15611 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15612 : ObjCIvarDecl::None; 15613 // Must set ivar's DeclContext to its enclosing interface. 15614 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15615 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15616 return nullptr; 15617 ObjCContainerDecl *EnclosingContext; 15618 if (ObjCImplementationDecl *IMPDecl = 15619 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15620 if (LangOpts.ObjCRuntime.isFragile()) { 15621 // Case of ivar declared in an implementation. Context is that of its class. 15622 EnclosingContext = IMPDecl->getClassInterface(); 15623 assert(EnclosingContext && "Implementation has no class interface!"); 15624 } 15625 else 15626 EnclosingContext = EnclosingDecl; 15627 } else { 15628 if (ObjCCategoryDecl *CDecl = 15629 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15630 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15631 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15632 return nullptr; 15633 } 15634 } 15635 EnclosingContext = EnclosingDecl; 15636 } 15637 15638 // Construct the decl. 15639 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15640 DeclStart, Loc, II, T, 15641 TInfo, ac, (Expr *)BitfieldWidth); 15642 15643 if (II) { 15644 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15645 ForVisibleRedeclaration); 15646 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15647 && !isa<TagDecl>(PrevDecl)) { 15648 Diag(Loc, diag::err_duplicate_member) << II; 15649 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15650 NewID->setInvalidDecl(); 15651 } 15652 } 15653 15654 // Process attributes attached to the ivar. 15655 ProcessDeclAttributes(S, NewID, D); 15656 15657 if (D.isInvalidType()) 15658 NewID->setInvalidDecl(); 15659 15660 // In ARC, infer 'retaining' for ivars of retainable type. 15661 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15662 NewID->setInvalidDecl(); 15663 15664 if (D.getDeclSpec().isModulePrivateSpecified()) 15665 NewID->setModulePrivate(); 15666 15667 if (II) { 15668 // FIXME: When interfaces are DeclContexts, we'll need to add 15669 // these to the interface. 15670 S->AddDecl(NewID); 15671 IdResolver.AddDecl(NewID); 15672 } 15673 15674 if (LangOpts.ObjCRuntime.isNonFragile() && 15675 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15676 Diag(Loc, diag::warn_ivars_in_interface); 15677 15678 return NewID; 15679 } 15680 15681 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15682 /// class and class extensions. For every class \@interface and class 15683 /// extension \@interface, if the last ivar is a bitfield of any type, 15684 /// then add an implicit `char :0` ivar to the end of that interface. 15685 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15686 SmallVectorImpl<Decl *> &AllIvarDecls) { 15687 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15688 return; 15689 15690 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15691 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15692 15693 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15694 return; 15695 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15696 if (!ID) { 15697 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15698 if (!CD->IsClassExtension()) 15699 return; 15700 } 15701 // No need to add this to end of @implementation. 15702 else 15703 return; 15704 } 15705 // All conditions are met. Add a new bitfield to the tail end of ivars. 15706 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15707 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15708 15709 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15710 DeclLoc, DeclLoc, nullptr, 15711 Context.CharTy, 15712 Context.getTrivialTypeSourceInfo(Context.CharTy, 15713 DeclLoc), 15714 ObjCIvarDecl::Private, BW, 15715 true); 15716 AllIvarDecls.push_back(Ivar); 15717 } 15718 15719 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15720 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15721 SourceLocation RBrac, 15722 const ParsedAttributesView &Attrs) { 15723 assert(EnclosingDecl && "missing record or interface decl"); 15724 15725 // If this is an Objective-C @implementation or category and we have 15726 // new fields here we should reset the layout of the interface since 15727 // it will now change. 15728 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15729 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15730 switch (DC->getKind()) { 15731 default: break; 15732 case Decl::ObjCCategory: 15733 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15734 break; 15735 case Decl::ObjCImplementation: 15736 Context. 15737 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15738 break; 15739 } 15740 } 15741 15742 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15743 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 15744 15745 // Start counting up the number of named members; make sure to include 15746 // members of anonymous structs and unions in the total. 15747 unsigned NumNamedMembers = 0; 15748 if (Record) { 15749 for (const auto *I : Record->decls()) { 15750 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15751 if (IFD->getDeclName()) 15752 ++NumNamedMembers; 15753 } 15754 } 15755 15756 // Verify that all the fields are okay. 15757 SmallVector<FieldDecl*, 32> RecFields; 15758 15759 bool ObjCFieldLifetimeErrReported = false; 15760 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15761 i != end; ++i) { 15762 FieldDecl *FD = cast<FieldDecl>(*i); 15763 15764 // Get the type for the field. 15765 const Type *FDTy = FD->getType().getTypePtr(); 15766 15767 if (!FD->isAnonymousStructOrUnion()) { 15768 // Remember all fields written by the user. 15769 RecFields.push_back(FD); 15770 } 15771 15772 // If the field is already invalid for some reason, don't emit more 15773 // diagnostics about it. 15774 if (FD->isInvalidDecl()) { 15775 EnclosingDecl->setInvalidDecl(); 15776 continue; 15777 } 15778 15779 // C99 6.7.2.1p2: 15780 // A structure or union shall not contain a member with 15781 // incomplete or function type (hence, a structure shall not 15782 // contain an instance of itself, but may contain a pointer to 15783 // an instance of itself), except that the last member of a 15784 // structure with more than one named member may have incomplete 15785 // array type; such a structure (and any union containing, 15786 // possibly recursively, a member that is such a structure) 15787 // shall not be a member of a structure or an element of an 15788 // array. 15789 bool IsLastField = (i + 1 == Fields.end()); 15790 if (FDTy->isFunctionType()) { 15791 // Field declared as a function. 15792 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15793 << FD->getDeclName(); 15794 FD->setInvalidDecl(); 15795 EnclosingDecl->setInvalidDecl(); 15796 continue; 15797 } else if (FDTy->isIncompleteArrayType() && 15798 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15799 if (Record) { 15800 // Flexible array member. 15801 // Microsoft and g++ is more permissive regarding flexible array. 15802 // It will accept flexible array in union and also 15803 // as the sole element of a struct/class. 15804 unsigned DiagID = 0; 15805 if (!Record->isUnion() && !IsLastField) { 15806 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15807 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15808 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15809 FD->setInvalidDecl(); 15810 EnclosingDecl->setInvalidDecl(); 15811 continue; 15812 } else if (Record->isUnion()) 15813 DiagID = getLangOpts().MicrosoftExt 15814 ? diag::ext_flexible_array_union_ms 15815 : getLangOpts().CPlusPlus 15816 ? diag::ext_flexible_array_union_gnu 15817 : diag::err_flexible_array_union; 15818 else if (NumNamedMembers < 1) 15819 DiagID = getLangOpts().MicrosoftExt 15820 ? diag::ext_flexible_array_empty_aggregate_ms 15821 : getLangOpts().CPlusPlus 15822 ? diag::ext_flexible_array_empty_aggregate_gnu 15823 : diag::err_flexible_array_empty_aggregate; 15824 15825 if (DiagID) 15826 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15827 << Record->getTagKind(); 15828 // While the layout of types that contain virtual bases is not specified 15829 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15830 // virtual bases after the derived members. This would make a flexible 15831 // array member declared at the end of an object not adjacent to the end 15832 // of the type. 15833 if (CXXRecord && CXXRecord->getNumVBases() != 0) 15834 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15835 << FD->getDeclName() << Record->getTagKind(); 15836 if (!getLangOpts().C99) 15837 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15838 << FD->getDeclName() << Record->getTagKind(); 15839 15840 // If the element type has a non-trivial destructor, we would not 15841 // implicitly destroy the elements, so disallow it for now. 15842 // 15843 // FIXME: GCC allows this. We should probably either implicitly delete 15844 // the destructor of the containing class, or just allow this. 15845 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15846 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15847 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15848 << FD->getDeclName() << FD->getType(); 15849 FD->setInvalidDecl(); 15850 EnclosingDecl->setInvalidDecl(); 15851 continue; 15852 } 15853 // Okay, we have a legal flexible array member at the end of the struct. 15854 Record->setHasFlexibleArrayMember(true); 15855 } else { 15856 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15857 // unless they are followed by another ivar. That check is done 15858 // elsewhere, after synthesized ivars are known. 15859 } 15860 } else if (!FDTy->isDependentType() && 15861 RequireCompleteType(FD->getLocation(), FD->getType(), 15862 diag::err_field_incomplete)) { 15863 // Incomplete type 15864 FD->setInvalidDecl(); 15865 EnclosingDecl->setInvalidDecl(); 15866 continue; 15867 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15868 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15869 // A type which contains a flexible array member is considered to be a 15870 // flexible array member. 15871 Record->setHasFlexibleArrayMember(true); 15872 if (!Record->isUnion()) { 15873 // If this is a struct/class and this is not the last element, reject 15874 // it. Note that GCC supports variable sized arrays in the middle of 15875 // structures. 15876 if (!IsLastField) 15877 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15878 << FD->getDeclName() << FD->getType(); 15879 else { 15880 // We support flexible arrays at the end of structs in 15881 // other structs as an extension. 15882 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15883 << FD->getDeclName(); 15884 } 15885 } 15886 } 15887 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15888 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15889 diag::err_abstract_type_in_decl, 15890 AbstractIvarType)) { 15891 // Ivars can not have abstract class types 15892 FD->setInvalidDecl(); 15893 } 15894 if (Record && FDTTy->getDecl()->hasObjectMember()) 15895 Record->setHasObjectMember(true); 15896 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15897 Record->setHasVolatileMember(true); 15898 } else if (FDTy->isObjCObjectType()) { 15899 /// A field cannot be an Objective-c object 15900 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15901 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15902 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15903 FD->setType(T); 15904 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15905 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { 15906 // It's an error in ARC or Weak if a field has lifetime. 15907 // We don't want to report this in a system header, though, 15908 // so we just make the field unavailable. 15909 // FIXME: that's really not sufficient; we need to make the type 15910 // itself invalid to, say, initialize or copy. 15911 QualType T = FD->getType(); 15912 if (T.hasNonTrivialObjCLifetime()) { 15913 SourceLocation loc = FD->getLocation(); 15914 if (getSourceManager().isInSystemHeader(loc)) { 15915 if (!FD->hasAttr<UnavailableAttr>()) { 15916 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15917 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15918 } 15919 } else { 15920 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15921 << T->isBlockPointerType() << Record->getTagKind(); 15922 } 15923 ObjCFieldLifetimeErrReported = true; 15924 } 15925 } else if (getLangOpts().ObjC && 15926 getLangOpts().getGC() != LangOptions::NonGC && 15927 Record && !Record->hasObjectMember()) { 15928 if (FD->getType()->isObjCObjectPointerType() || 15929 FD->getType().isObjCGCStrong()) 15930 Record->setHasObjectMember(true); 15931 else if (Context.getAsArrayType(FD->getType())) { 15932 QualType BaseType = Context.getBaseElementType(FD->getType()); 15933 if (BaseType->isRecordType() && 15934 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15935 Record->setHasObjectMember(true); 15936 else if (BaseType->isObjCObjectPointerType() || 15937 BaseType.isObjCGCStrong()) 15938 Record->setHasObjectMember(true); 15939 } 15940 } 15941 15942 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 15943 QualType FT = FD->getType(); 15944 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 15945 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 15946 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 15947 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 15948 Record->setNonTrivialToPrimitiveCopy(true); 15949 if (FT.isDestructedType()) { 15950 Record->setNonTrivialToPrimitiveDestroy(true); 15951 Record->setParamDestroyedInCallee(true); 15952 } 15953 15954 if (const auto *RT = FT->getAs<RecordType>()) { 15955 if (RT->getDecl()->getArgPassingRestrictions() == 15956 RecordDecl::APK_CanNeverPassInRegs) 15957 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15958 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 15959 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15960 } 15961 15962 if (Record && FD->getType().isVolatileQualified()) 15963 Record->setHasVolatileMember(true); 15964 // Keep track of the number of named members. 15965 if (FD->getIdentifier()) 15966 ++NumNamedMembers; 15967 } 15968 15969 // Okay, we successfully defined 'Record'. 15970 if (Record) { 15971 bool Completed = false; 15972 if (CXXRecord) { 15973 if (!CXXRecord->isInvalidDecl()) { 15974 // Set access bits correctly on the directly-declared conversions. 15975 for (CXXRecordDecl::conversion_iterator 15976 I = CXXRecord->conversion_begin(), 15977 E = CXXRecord->conversion_end(); I != E; ++I) 15978 I.setAccess((*I)->getAccess()); 15979 } 15980 15981 if (!CXXRecord->isDependentType()) { 15982 // Add any implicitly-declared members to this class. 15983 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15984 15985 if (!CXXRecord->isInvalidDecl()) { 15986 // If we have virtual base classes, we may end up finding multiple 15987 // final overriders for a given virtual function. Check for this 15988 // problem now. 15989 if (CXXRecord->getNumVBases()) { 15990 CXXFinalOverriderMap FinalOverriders; 15991 CXXRecord->getFinalOverriders(FinalOverriders); 15992 15993 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15994 MEnd = FinalOverriders.end(); 15995 M != MEnd; ++M) { 15996 for (OverridingMethods::iterator SO = M->second.begin(), 15997 SOEnd = M->second.end(); 15998 SO != SOEnd; ++SO) { 15999 assert(SO->second.size() > 0 && 16000 "Virtual function without overriding functions?"); 16001 if (SO->second.size() == 1) 16002 continue; 16003 16004 // C++ [class.virtual]p2: 16005 // In a derived class, if a virtual member function of a base 16006 // class subobject has more than one final overrider the 16007 // program is ill-formed. 16008 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 16009 << (const NamedDecl *)M->first << Record; 16010 Diag(M->first->getLocation(), 16011 diag::note_overridden_virtual_function); 16012 for (OverridingMethods::overriding_iterator 16013 OM = SO->second.begin(), 16014 OMEnd = SO->second.end(); 16015 OM != OMEnd; ++OM) 16016 Diag(OM->Method->getLocation(), diag::note_final_overrider) 16017 << (const NamedDecl *)M->first << OM->Method->getParent(); 16018 16019 Record->setInvalidDecl(); 16020 } 16021 } 16022 CXXRecord->completeDefinition(&FinalOverriders); 16023 Completed = true; 16024 } 16025 } 16026 } 16027 } 16028 16029 if (!Completed) 16030 Record->completeDefinition(); 16031 16032 // Handle attributes before checking the layout. 16033 ProcessDeclAttributeList(S, Record, Attrs); 16034 16035 // We may have deferred checking for a deleted destructor. Check now. 16036 if (CXXRecord) { 16037 auto *Dtor = CXXRecord->getDestructor(); 16038 if (Dtor && Dtor->isImplicit() && 16039 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 16040 CXXRecord->setImplicitDestructorIsDeleted(); 16041 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 16042 } 16043 } 16044 16045 if (Record->hasAttrs()) { 16046 CheckAlignasUnderalignment(Record); 16047 16048 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 16049 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 16050 IA->getRange(), IA->getBestCase(), 16051 IA->getSemanticSpelling()); 16052 } 16053 16054 // Check if the structure/union declaration is a type that can have zero 16055 // size in C. For C this is a language extension, for C++ it may cause 16056 // compatibility problems. 16057 bool CheckForZeroSize; 16058 if (!getLangOpts().CPlusPlus) { 16059 CheckForZeroSize = true; 16060 } else { 16061 // For C++ filter out types that cannot be referenced in C code. 16062 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 16063 CheckForZeroSize = 16064 CXXRecord->getLexicalDeclContext()->isExternCContext() && 16065 !CXXRecord->isDependentType() && 16066 CXXRecord->isCLike(); 16067 } 16068 if (CheckForZeroSize) { 16069 bool ZeroSize = true; 16070 bool IsEmpty = true; 16071 unsigned NonBitFields = 0; 16072 for (RecordDecl::field_iterator I = Record->field_begin(), 16073 E = Record->field_end(); 16074 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 16075 IsEmpty = false; 16076 if (I->isUnnamedBitfield()) { 16077 if (!I->isZeroLengthBitField(Context)) 16078 ZeroSize = false; 16079 } else { 16080 ++NonBitFields; 16081 QualType FieldType = I->getType(); 16082 if (FieldType->isIncompleteType() || 16083 !Context.getTypeSizeInChars(FieldType).isZero()) 16084 ZeroSize = false; 16085 } 16086 } 16087 16088 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 16089 // allowed in C++, but warn if its declaration is inside 16090 // extern "C" block. 16091 if (ZeroSize) { 16092 Diag(RecLoc, getLangOpts().CPlusPlus ? 16093 diag::warn_zero_size_struct_union_in_extern_c : 16094 diag::warn_zero_size_struct_union_compat) 16095 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 16096 } 16097 16098 // Structs without named members are extension in C (C99 6.7.2.1p7), 16099 // but are accepted by GCC. 16100 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 16101 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 16102 diag::ext_no_named_members_in_struct_union) 16103 << Record->isUnion(); 16104 } 16105 } 16106 } else { 16107 ObjCIvarDecl **ClsFields = 16108 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 16109 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 16110 ID->setEndOfDefinitionLoc(RBrac); 16111 // Add ivar's to class's DeclContext. 16112 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16113 ClsFields[i]->setLexicalDeclContext(ID); 16114 ID->addDecl(ClsFields[i]); 16115 } 16116 // Must enforce the rule that ivars in the base classes may not be 16117 // duplicates. 16118 if (ID->getSuperClass()) 16119 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 16120 } else if (ObjCImplementationDecl *IMPDecl = 16121 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16122 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 16123 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 16124 // Ivar declared in @implementation never belongs to the implementation. 16125 // Only it is in implementation's lexical context. 16126 ClsFields[I]->setLexicalDeclContext(IMPDecl); 16127 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 16128 IMPDecl->setIvarLBraceLoc(LBrac); 16129 IMPDecl->setIvarRBraceLoc(RBrac); 16130 } else if (ObjCCategoryDecl *CDecl = 16131 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16132 // case of ivars in class extension; all other cases have been 16133 // reported as errors elsewhere. 16134 // FIXME. Class extension does not have a LocEnd field. 16135 // CDecl->setLocEnd(RBrac); 16136 // Add ivar's to class extension's DeclContext. 16137 // Diagnose redeclaration of private ivars. 16138 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 16139 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16140 if (IDecl) { 16141 if (const ObjCIvarDecl *ClsIvar = 16142 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 16143 Diag(ClsFields[i]->getLocation(), 16144 diag::err_duplicate_ivar_declaration); 16145 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 16146 continue; 16147 } 16148 for (const auto *Ext : IDecl->known_extensions()) { 16149 if (const ObjCIvarDecl *ClsExtIvar 16150 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 16151 Diag(ClsFields[i]->getLocation(), 16152 diag::err_duplicate_ivar_declaration); 16153 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 16154 continue; 16155 } 16156 } 16157 } 16158 ClsFields[i]->setLexicalDeclContext(CDecl); 16159 CDecl->addDecl(ClsFields[i]); 16160 } 16161 CDecl->setIvarLBraceLoc(LBrac); 16162 CDecl->setIvarRBraceLoc(RBrac); 16163 } 16164 } 16165 } 16166 16167 /// Determine whether the given integral value is representable within 16168 /// the given type T. 16169 static bool isRepresentableIntegerValue(ASTContext &Context, 16170 llvm::APSInt &Value, 16171 QualType T) { 16172 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 16173 "Integral type required!"); 16174 unsigned BitWidth = Context.getIntWidth(T); 16175 16176 if (Value.isUnsigned() || Value.isNonNegative()) { 16177 if (T->isSignedIntegerOrEnumerationType()) 16178 --BitWidth; 16179 return Value.getActiveBits() <= BitWidth; 16180 } 16181 return Value.getMinSignedBits() <= BitWidth; 16182 } 16183 16184 // Given an integral type, return the next larger integral type 16185 // (or a NULL type of no such type exists). 16186 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 16187 // FIXME: Int128/UInt128 support, which also needs to be introduced into 16188 // enum checking below. 16189 assert((T->isIntegralType(Context) || 16190 T->isEnumeralType()) && "Integral type required!"); 16191 const unsigned NumTypes = 4; 16192 QualType SignedIntegralTypes[NumTypes] = { 16193 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 16194 }; 16195 QualType UnsignedIntegralTypes[NumTypes] = { 16196 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 16197 Context.UnsignedLongLongTy 16198 }; 16199 16200 unsigned BitWidth = Context.getTypeSize(T); 16201 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 16202 : UnsignedIntegralTypes; 16203 for (unsigned I = 0; I != NumTypes; ++I) 16204 if (Context.getTypeSize(Types[I]) > BitWidth) 16205 return Types[I]; 16206 16207 return QualType(); 16208 } 16209 16210 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 16211 EnumConstantDecl *LastEnumConst, 16212 SourceLocation IdLoc, 16213 IdentifierInfo *Id, 16214 Expr *Val) { 16215 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16216 llvm::APSInt EnumVal(IntWidth); 16217 QualType EltTy; 16218 16219 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 16220 Val = nullptr; 16221 16222 if (Val) 16223 Val = DefaultLvalueConversion(Val).get(); 16224 16225 if (Val) { 16226 if (Enum->isDependentType() || Val->isTypeDependent()) 16227 EltTy = Context.DependentTy; 16228 else { 16229 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 16230 !getLangOpts().MSVCCompat) { 16231 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 16232 // constant-expression in the enumerator-definition shall be a converted 16233 // constant expression of the underlying type. 16234 EltTy = Enum->getIntegerType(); 16235 ExprResult Converted = 16236 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 16237 CCEK_Enumerator); 16238 if (Converted.isInvalid()) 16239 Val = nullptr; 16240 else 16241 Val = Converted.get(); 16242 } else if (!Val->isValueDependent() && 16243 !(Val = VerifyIntegerConstantExpression(Val, 16244 &EnumVal).get())) { 16245 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 16246 } else { 16247 if (Enum->isComplete()) { 16248 EltTy = Enum->getIntegerType(); 16249 16250 // In Obj-C and Microsoft mode, require the enumeration value to be 16251 // representable in the underlying type of the enumeration. In C++11, 16252 // we perform a non-narrowing conversion as part of converted constant 16253 // expression checking. 16254 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16255 if (getLangOpts().MSVCCompat) { 16256 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 16257 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 16258 } else 16259 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 16260 } else 16261 Val = ImpCastExprToType(Val, EltTy, 16262 EltTy->isBooleanType() ? 16263 CK_IntegralToBoolean : CK_IntegralCast) 16264 .get(); 16265 } else if (getLangOpts().CPlusPlus) { 16266 // C++11 [dcl.enum]p5: 16267 // If the underlying type is not fixed, the type of each enumerator 16268 // is the type of its initializing value: 16269 // - If an initializer is specified for an enumerator, the 16270 // initializing value has the same type as the expression. 16271 EltTy = Val->getType(); 16272 } else { 16273 // C99 6.7.2.2p2: 16274 // The expression that defines the value of an enumeration constant 16275 // shall be an integer constant expression that has a value 16276 // representable as an int. 16277 16278 // Complain if the value is not representable in an int. 16279 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 16280 Diag(IdLoc, diag::ext_enum_value_not_int) 16281 << EnumVal.toString(10) << Val->getSourceRange() 16282 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 16283 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 16284 // Force the type of the expression to 'int'. 16285 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 16286 } 16287 EltTy = Val->getType(); 16288 } 16289 } 16290 } 16291 } 16292 16293 if (!Val) { 16294 if (Enum->isDependentType()) 16295 EltTy = Context.DependentTy; 16296 else if (!LastEnumConst) { 16297 // C++0x [dcl.enum]p5: 16298 // If the underlying type is not fixed, the type of each enumerator 16299 // is the type of its initializing value: 16300 // - If no initializer is specified for the first enumerator, the 16301 // initializing value has an unspecified integral type. 16302 // 16303 // GCC uses 'int' for its unspecified integral type, as does 16304 // C99 6.7.2.2p3. 16305 if (Enum->isFixed()) { 16306 EltTy = Enum->getIntegerType(); 16307 } 16308 else { 16309 EltTy = Context.IntTy; 16310 } 16311 } else { 16312 // Assign the last value + 1. 16313 EnumVal = LastEnumConst->getInitVal(); 16314 ++EnumVal; 16315 EltTy = LastEnumConst->getType(); 16316 16317 // Check for overflow on increment. 16318 if (EnumVal < LastEnumConst->getInitVal()) { 16319 // C++0x [dcl.enum]p5: 16320 // If the underlying type is not fixed, the type of each enumerator 16321 // is the type of its initializing value: 16322 // 16323 // - Otherwise the type of the initializing value is the same as 16324 // the type of the initializing value of the preceding enumerator 16325 // unless the incremented value is not representable in that type, 16326 // in which case the type is an unspecified integral type 16327 // sufficient to contain the incremented value. If no such type 16328 // exists, the program is ill-formed. 16329 QualType T = getNextLargerIntegralType(Context, EltTy); 16330 if (T.isNull() || Enum->isFixed()) { 16331 // There is no integral type larger enough to represent this 16332 // value. Complain, then allow the value to wrap around. 16333 EnumVal = LastEnumConst->getInitVal(); 16334 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 16335 ++EnumVal; 16336 if (Enum->isFixed()) 16337 // When the underlying type is fixed, this is ill-formed. 16338 Diag(IdLoc, diag::err_enumerator_wrapped) 16339 << EnumVal.toString(10) 16340 << EltTy; 16341 else 16342 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 16343 << EnumVal.toString(10); 16344 } else { 16345 EltTy = T; 16346 } 16347 16348 // Retrieve the last enumerator's value, extent that type to the 16349 // type that is supposed to be large enough to represent the incremented 16350 // value, then increment. 16351 EnumVal = LastEnumConst->getInitVal(); 16352 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16353 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 16354 ++EnumVal; 16355 16356 // If we're not in C++, diagnose the overflow of enumerator values, 16357 // which in C99 means that the enumerator value is not representable in 16358 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 16359 // permits enumerator values that are representable in some larger 16360 // integral type. 16361 if (!getLangOpts().CPlusPlus && !T.isNull()) 16362 Diag(IdLoc, diag::warn_enum_value_overflow); 16363 } else if (!getLangOpts().CPlusPlus && 16364 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16365 // Enforce C99 6.7.2.2p2 even when we compute the next value. 16366 Diag(IdLoc, diag::ext_enum_value_not_int) 16367 << EnumVal.toString(10) << 1; 16368 } 16369 } 16370 } 16371 16372 if (!EltTy->isDependentType()) { 16373 // Make the enumerator value match the signedness and size of the 16374 // enumerator's type. 16375 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 16376 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16377 } 16378 16379 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 16380 Val, EnumVal); 16381 } 16382 16383 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 16384 SourceLocation IILoc) { 16385 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 16386 !getLangOpts().CPlusPlus) 16387 return SkipBodyInfo(); 16388 16389 // We have an anonymous enum definition. Look up the first enumerator to 16390 // determine if we should merge the definition with an existing one and 16391 // skip the body. 16392 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 16393 forRedeclarationInCurContext()); 16394 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 16395 if (!PrevECD) 16396 return SkipBodyInfo(); 16397 16398 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 16399 NamedDecl *Hidden; 16400 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 16401 SkipBodyInfo Skip; 16402 Skip.Previous = Hidden; 16403 return Skip; 16404 } 16405 16406 return SkipBodyInfo(); 16407 } 16408 16409 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 16410 SourceLocation IdLoc, IdentifierInfo *Id, 16411 const ParsedAttributesView &Attrs, 16412 SourceLocation EqualLoc, Expr *Val) { 16413 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 16414 EnumConstantDecl *LastEnumConst = 16415 cast_or_null<EnumConstantDecl>(lastEnumConst); 16416 16417 // The scope passed in may not be a decl scope. Zip up the scope tree until 16418 // we find one that is. 16419 S = getNonFieldDeclScope(S); 16420 16421 // Verify that there isn't already something declared with this name in this 16422 // scope. 16423 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 16424 LookupName(R, S); 16425 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 16426 16427 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16428 // Maybe we will complain about the shadowed template parameter. 16429 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 16430 // Just pretend that we didn't see the previous declaration. 16431 PrevDecl = nullptr; 16432 } 16433 16434 // C++ [class.mem]p15: 16435 // If T is the name of a class, then each of the following shall have a name 16436 // different from T: 16437 // - every enumerator of every member of class T that is an unscoped 16438 // enumerated type 16439 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 16440 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 16441 DeclarationNameInfo(Id, IdLoc)); 16442 16443 EnumConstantDecl *New = 16444 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 16445 if (!New) 16446 return nullptr; 16447 16448 if (PrevDecl) { 16449 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 16450 // Check for other kinds of shadowing not already handled. 16451 CheckShadow(New, PrevDecl, R); 16452 } 16453 16454 // When in C++, we may get a TagDecl with the same name; in this case the 16455 // enum constant will 'hide' the tag. 16456 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 16457 "Received TagDecl when not in C++!"); 16458 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 16459 if (isa<EnumConstantDecl>(PrevDecl)) 16460 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 16461 else 16462 Diag(IdLoc, diag::err_redefinition) << Id; 16463 notePreviousDefinition(PrevDecl, IdLoc); 16464 return nullptr; 16465 } 16466 } 16467 16468 // Process attributes. 16469 ProcessDeclAttributeList(S, New, Attrs); 16470 AddPragmaAttributes(S, New); 16471 16472 // Register this decl in the current scope stack. 16473 New->setAccess(TheEnumDecl->getAccess()); 16474 PushOnScopeChains(New, S); 16475 16476 ActOnDocumentableDecl(New); 16477 16478 return New; 16479 } 16480 16481 // Returns true when the enum initial expression does not trigger the 16482 // duplicate enum warning. A few common cases are exempted as follows: 16483 // Element2 = Element1 16484 // Element2 = Element1 + 1 16485 // Element2 = Element1 - 1 16486 // Where Element2 and Element1 are from the same enum. 16487 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16488 Expr *InitExpr = ECD->getInitExpr(); 16489 if (!InitExpr) 16490 return true; 16491 InitExpr = InitExpr->IgnoreImpCasts(); 16492 16493 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16494 if (!BO->isAdditiveOp()) 16495 return true; 16496 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16497 if (!IL) 16498 return true; 16499 if (IL->getValue() != 1) 16500 return true; 16501 16502 InitExpr = BO->getLHS(); 16503 } 16504 16505 // This checks if the elements are from the same enum. 16506 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16507 if (!DRE) 16508 return true; 16509 16510 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16511 if (!EnumConstant) 16512 return true; 16513 16514 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16515 Enum) 16516 return true; 16517 16518 return false; 16519 } 16520 16521 // Emits a warning when an element is implicitly set a value that 16522 // a previous element has already been set to. 16523 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16524 EnumDecl *Enum, QualType EnumType) { 16525 // Avoid anonymous enums 16526 if (!Enum->getIdentifier()) 16527 return; 16528 16529 // Only check for small enums. 16530 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16531 return; 16532 16533 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16534 return; 16535 16536 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16537 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16538 16539 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16540 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 16541 16542 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16543 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16544 llvm::APSInt Val = D->getInitVal(); 16545 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16546 }; 16547 16548 DuplicatesVector DupVector; 16549 ValueToVectorMap EnumMap; 16550 16551 // Populate the EnumMap with all values represented by enum constants without 16552 // an initializer. 16553 for (auto *Element : Elements) { 16554 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16555 16556 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16557 // this constant. Skip this enum since it may be ill-formed. 16558 if (!ECD) { 16559 return; 16560 } 16561 16562 // Constants with initalizers are handled in the next loop. 16563 if (ECD->getInitExpr()) 16564 continue; 16565 16566 // Duplicate values are handled in the next loop. 16567 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16568 } 16569 16570 if (EnumMap.size() == 0) 16571 return; 16572 16573 // Create vectors for any values that has duplicates. 16574 for (auto *Element : Elements) { 16575 // The last loop returned if any constant was null. 16576 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16577 if (!ValidDuplicateEnum(ECD, Enum)) 16578 continue; 16579 16580 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16581 if (Iter == EnumMap.end()) 16582 continue; 16583 16584 DeclOrVector& Entry = Iter->second; 16585 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16586 // Ensure constants are different. 16587 if (D == ECD) 16588 continue; 16589 16590 // Create new vector and push values onto it. 16591 auto Vec = llvm::make_unique<ECDVector>(); 16592 Vec->push_back(D); 16593 Vec->push_back(ECD); 16594 16595 // Update entry to point to the duplicates vector. 16596 Entry = Vec.get(); 16597 16598 // Store the vector somewhere we can consult later for quick emission of 16599 // diagnostics. 16600 DupVector.emplace_back(std::move(Vec)); 16601 continue; 16602 } 16603 16604 ECDVector *Vec = Entry.get<ECDVector*>(); 16605 // Make sure constants are not added more than once. 16606 if (*Vec->begin() == ECD) 16607 continue; 16608 16609 Vec->push_back(ECD); 16610 } 16611 16612 // Emit diagnostics. 16613 for (const auto &Vec : DupVector) { 16614 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16615 16616 // Emit warning for one enum constant. 16617 auto *FirstECD = Vec->front(); 16618 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16619 << FirstECD << FirstECD->getInitVal().toString(10) 16620 << FirstECD->getSourceRange(); 16621 16622 // Emit one note for each of the remaining enum constants with 16623 // the same value. 16624 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16625 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16626 << ECD << ECD->getInitVal().toString(10) 16627 << ECD->getSourceRange(); 16628 } 16629 } 16630 16631 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16632 bool AllowMask) const { 16633 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16634 assert(ED->isCompleteDefinition() && "expected enum definition"); 16635 16636 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16637 llvm::APInt &FlagBits = R.first->second; 16638 16639 if (R.second) { 16640 for (auto *E : ED->enumerators()) { 16641 const auto &EVal = E->getInitVal(); 16642 // Only single-bit enumerators introduce new flag values. 16643 if (EVal.isPowerOf2()) 16644 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16645 } 16646 } 16647 16648 // A value is in a flag enum if either its bits are a subset of the enum's 16649 // flag bits (the first condition) or we are allowing masks and the same is 16650 // true of its complement (the second condition). When masks are allowed, we 16651 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16652 // 16653 // While it's true that any value could be used as a mask, the assumption is 16654 // that a mask will have all of the insignificant bits set. Anything else is 16655 // likely a logic error. 16656 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16657 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16658 } 16659 16660 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16661 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 16662 const ParsedAttributesView &Attrs) { 16663 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16664 QualType EnumType = Context.getTypeDeclType(Enum); 16665 16666 ProcessDeclAttributeList(S, Enum, Attrs); 16667 16668 if (Enum->isDependentType()) { 16669 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16670 EnumConstantDecl *ECD = 16671 cast_or_null<EnumConstantDecl>(Elements[i]); 16672 if (!ECD) continue; 16673 16674 ECD->setType(EnumType); 16675 } 16676 16677 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16678 return; 16679 } 16680 16681 // TODO: If the result value doesn't fit in an int, it must be a long or long 16682 // long value. ISO C does not support this, but GCC does as an extension, 16683 // emit a warning. 16684 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16685 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16686 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16687 16688 // Verify that all the values are okay, compute the size of the values, and 16689 // reverse the list. 16690 unsigned NumNegativeBits = 0; 16691 unsigned NumPositiveBits = 0; 16692 16693 // Keep track of whether all elements have type int. 16694 bool AllElementsInt = true; 16695 16696 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16697 EnumConstantDecl *ECD = 16698 cast_or_null<EnumConstantDecl>(Elements[i]); 16699 if (!ECD) continue; // Already issued a diagnostic. 16700 16701 const llvm::APSInt &InitVal = ECD->getInitVal(); 16702 16703 // Keep track of the size of positive and negative values. 16704 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16705 NumPositiveBits = std::max(NumPositiveBits, 16706 (unsigned)InitVal.getActiveBits()); 16707 else 16708 NumNegativeBits = std::max(NumNegativeBits, 16709 (unsigned)InitVal.getMinSignedBits()); 16710 16711 // Keep track of whether every enum element has type int (very common). 16712 if (AllElementsInt) 16713 AllElementsInt = ECD->getType() == Context.IntTy; 16714 } 16715 16716 // Figure out the type that should be used for this enum. 16717 QualType BestType; 16718 unsigned BestWidth; 16719 16720 // C++0x N3000 [conv.prom]p3: 16721 // An rvalue of an unscoped enumeration type whose underlying 16722 // type is not fixed can be converted to an rvalue of the first 16723 // of the following types that can represent all the values of 16724 // the enumeration: int, unsigned int, long int, unsigned long 16725 // int, long long int, or unsigned long long int. 16726 // C99 6.4.4.3p2: 16727 // An identifier declared as an enumeration constant has type int. 16728 // The C99 rule is modified by a gcc extension 16729 QualType BestPromotionType; 16730 16731 bool Packed = Enum->hasAttr<PackedAttr>(); 16732 // -fshort-enums is the equivalent to specifying the packed attribute on all 16733 // enum definitions. 16734 if (LangOpts.ShortEnums) 16735 Packed = true; 16736 16737 // If the enum already has a type because it is fixed or dictated by the 16738 // target, promote that type instead of analyzing the enumerators. 16739 if (Enum->isComplete()) { 16740 BestType = Enum->getIntegerType(); 16741 if (BestType->isPromotableIntegerType()) 16742 BestPromotionType = Context.getPromotedIntegerType(BestType); 16743 else 16744 BestPromotionType = BestType; 16745 16746 BestWidth = Context.getIntWidth(BestType); 16747 } 16748 else if (NumNegativeBits) { 16749 // If there is a negative value, figure out the smallest integer type (of 16750 // int/long/longlong) that fits. 16751 // If it's packed, check also if it fits a char or a short. 16752 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16753 BestType = Context.SignedCharTy; 16754 BestWidth = CharWidth; 16755 } else if (Packed && NumNegativeBits <= ShortWidth && 16756 NumPositiveBits < ShortWidth) { 16757 BestType = Context.ShortTy; 16758 BestWidth = ShortWidth; 16759 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16760 BestType = Context.IntTy; 16761 BestWidth = IntWidth; 16762 } else { 16763 BestWidth = Context.getTargetInfo().getLongWidth(); 16764 16765 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16766 BestType = Context.LongTy; 16767 } else { 16768 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16769 16770 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16771 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16772 BestType = Context.LongLongTy; 16773 } 16774 } 16775 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16776 } else { 16777 // If there is no negative value, figure out the smallest type that fits 16778 // all of the enumerator values. 16779 // If it's packed, check also if it fits a char or a short. 16780 if (Packed && NumPositiveBits <= CharWidth) { 16781 BestType = Context.UnsignedCharTy; 16782 BestPromotionType = Context.IntTy; 16783 BestWidth = CharWidth; 16784 } else if (Packed && NumPositiveBits <= ShortWidth) { 16785 BestType = Context.UnsignedShortTy; 16786 BestPromotionType = Context.IntTy; 16787 BestWidth = ShortWidth; 16788 } else if (NumPositiveBits <= IntWidth) { 16789 BestType = Context.UnsignedIntTy; 16790 BestWidth = IntWidth; 16791 BestPromotionType 16792 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16793 ? Context.UnsignedIntTy : Context.IntTy; 16794 } else if (NumPositiveBits <= 16795 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16796 BestType = Context.UnsignedLongTy; 16797 BestPromotionType 16798 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16799 ? Context.UnsignedLongTy : Context.LongTy; 16800 } else { 16801 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16802 assert(NumPositiveBits <= BestWidth && 16803 "How could an initializer get larger than ULL?"); 16804 BestType = Context.UnsignedLongLongTy; 16805 BestPromotionType 16806 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16807 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16808 } 16809 } 16810 16811 // Loop over all of the enumerator constants, changing their types to match 16812 // the type of the enum if needed. 16813 for (auto *D : Elements) { 16814 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16815 if (!ECD) continue; // Already issued a diagnostic. 16816 16817 // Standard C says the enumerators have int type, but we allow, as an 16818 // extension, the enumerators to be larger than int size. If each 16819 // enumerator value fits in an int, type it as an int, otherwise type it the 16820 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16821 // that X has type 'int', not 'unsigned'. 16822 16823 // Determine whether the value fits into an int. 16824 llvm::APSInt InitVal = ECD->getInitVal(); 16825 16826 // If it fits into an integer type, force it. Otherwise force it to match 16827 // the enum decl type. 16828 QualType NewTy; 16829 unsigned NewWidth; 16830 bool NewSign; 16831 if (!getLangOpts().CPlusPlus && 16832 !Enum->isFixed() && 16833 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16834 NewTy = Context.IntTy; 16835 NewWidth = IntWidth; 16836 NewSign = true; 16837 } else if (ECD->getType() == BestType) { 16838 // Already the right type! 16839 if (getLangOpts().CPlusPlus) 16840 // C++ [dcl.enum]p4: Following the closing brace of an 16841 // enum-specifier, each enumerator has the type of its 16842 // enumeration. 16843 ECD->setType(EnumType); 16844 continue; 16845 } else { 16846 NewTy = BestType; 16847 NewWidth = BestWidth; 16848 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16849 } 16850 16851 // Adjust the APSInt value. 16852 InitVal = InitVal.extOrTrunc(NewWidth); 16853 InitVal.setIsSigned(NewSign); 16854 ECD->setInitVal(InitVal); 16855 16856 // Adjust the Expr initializer and type. 16857 if (ECD->getInitExpr() && 16858 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16859 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16860 CK_IntegralCast, 16861 ECD->getInitExpr(), 16862 /*base paths*/ nullptr, 16863 VK_RValue)); 16864 if (getLangOpts().CPlusPlus) 16865 // C++ [dcl.enum]p4: Following the closing brace of an 16866 // enum-specifier, each enumerator has the type of its 16867 // enumeration. 16868 ECD->setType(EnumType); 16869 else 16870 ECD->setType(NewTy); 16871 } 16872 16873 Enum->completeDefinition(BestType, BestPromotionType, 16874 NumPositiveBits, NumNegativeBits); 16875 16876 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16877 16878 if (Enum->isClosedFlag()) { 16879 for (Decl *D : Elements) { 16880 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16881 if (!ECD) continue; // Already issued a diagnostic. 16882 16883 llvm::APSInt InitVal = ECD->getInitVal(); 16884 if (InitVal != 0 && !InitVal.isPowerOf2() && 16885 !IsValueInFlagEnum(Enum, InitVal, true)) 16886 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16887 << ECD << Enum; 16888 } 16889 } 16890 16891 // Now that the enum type is defined, ensure it's not been underaligned. 16892 if (Enum->hasAttrs()) 16893 CheckAlignasUnderalignment(Enum); 16894 } 16895 16896 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16897 SourceLocation StartLoc, 16898 SourceLocation EndLoc) { 16899 StringLiteral *AsmString = cast<StringLiteral>(expr); 16900 16901 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16902 AsmString, StartLoc, 16903 EndLoc); 16904 CurContext->addDecl(New); 16905 return New; 16906 } 16907 16908 static void checkModuleImportContext(Sema &S, Module *M, 16909 SourceLocation ImportLoc, DeclContext *DC, 16910 bool FromInclude = false) { 16911 SourceLocation ExternCLoc; 16912 16913 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16914 switch (LSD->getLanguage()) { 16915 case LinkageSpecDecl::lang_c: 16916 if (ExternCLoc.isInvalid()) 16917 ExternCLoc = LSD->getBeginLoc(); 16918 break; 16919 case LinkageSpecDecl::lang_cxx: 16920 break; 16921 } 16922 DC = LSD->getParent(); 16923 } 16924 16925 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 16926 DC = DC->getParent(); 16927 16928 if (!isa<TranslationUnitDecl>(DC)) { 16929 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16930 ? diag::ext_module_import_not_at_top_level_noop 16931 : diag::err_module_import_not_at_top_level_fatal) 16932 << M->getFullModuleName() << DC; 16933 S.Diag(cast<Decl>(DC)->getBeginLoc(), 16934 diag::note_module_import_not_at_top_level) 16935 << DC; 16936 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16937 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16938 << M->getFullModuleName(); 16939 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16940 } 16941 } 16942 16943 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16944 SourceLocation ModuleLoc, 16945 ModuleDeclKind MDK, 16946 ModuleIdPath Path) { 16947 assert(getLangOpts().ModulesTS && 16948 "should only have module decl in modules TS"); 16949 16950 // A module implementation unit requires that we are not compiling a module 16951 // of any kind. A module interface unit requires that we are not compiling a 16952 // module map. 16953 switch (getLangOpts().getCompilingModule()) { 16954 case LangOptions::CMK_None: 16955 // It's OK to compile a module interface as a normal translation unit. 16956 break; 16957 16958 case LangOptions::CMK_ModuleInterface: 16959 if (MDK != ModuleDeclKind::Implementation) 16960 break; 16961 16962 // We were asked to compile a module interface unit but this is a module 16963 // implementation unit. That indicates the 'export' is missing. 16964 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16965 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16966 MDK = ModuleDeclKind::Interface; 16967 break; 16968 16969 case LangOptions::CMK_ModuleMap: 16970 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16971 return nullptr; 16972 16973 case LangOptions::CMK_HeaderModule: 16974 Diag(ModuleLoc, diag::err_module_decl_in_header_module); 16975 return nullptr; 16976 } 16977 16978 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16979 16980 // FIXME: Most of this work should be done by the preprocessor rather than 16981 // here, in order to support macro import. 16982 16983 // Only one module-declaration is permitted per source file. 16984 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16985 Diag(ModuleLoc, diag::err_module_redeclaration); 16986 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16987 diag::note_prev_module_declaration); 16988 return nullptr; 16989 } 16990 16991 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16992 // modules, the dots here are just another character that can appear in a 16993 // module name. 16994 std::string ModuleName; 16995 for (auto &Piece : Path) { 16996 if (!ModuleName.empty()) 16997 ModuleName += "."; 16998 ModuleName += Piece.first->getName(); 16999 } 17000 17001 // If a module name was explicitly specified on the command line, it must be 17002 // correct. 17003 if (!getLangOpts().CurrentModule.empty() && 17004 getLangOpts().CurrentModule != ModuleName) { 17005 Diag(Path.front().second, diag::err_current_module_name_mismatch) 17006 << SourceRange(Path.front().second, Path.back().second) 17007 << getLangOpts().CurrentModule; 17008 return nullptr; 17009 } 17010 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 17011 17012 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 17013 Module *Mod; 17014 17015 switch (MDK) { 17016 case ModuleDeclKind::Interface: { 17017 // We can't have parsed or imported a definition of this module or parsed a 17018 // module map defining it already. 17019 if (auto *M = Map.findModule(ModuleName)) { 17020 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 17021 if (M->DefinitionLoc.isValid()) 17022 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 17023 else if (const auto *FE = M->getASTFile()) 17024 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 17025 << FE->getName(); 17026 Mod = M; 17027 break; 17028 } 17029 17030 // Create a Module for the module that we're defining. 17031 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 17032 ModuleScopes.front().Module); 17033 assert(Mod && "module creation should not fail"); 17034 break; 17035 } 17036 17037 case ModuleDeclKind::Partition: 17038 // FIXME: Check we are in a submodule of the named module. 17039 return nullptr; 17040 17041 case ModuleDeclKind::Implementation: 17042 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 17043 PP.getIdentifierInfo(ModuleName), Path[0].second); 17044 Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc}, 17045 Module::AllVisible, 17046 /*IsIncludeDirective=*/false); 17047 if (!Mod) { 17048 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 17049 // Create an empty module interface unit for error recovery. 17050 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 17051 ModuleScopes.front().Module); 17052 } 17053 break; 17054 } 17055 17056 // Switch from the global module to the named module. 17057 ModuleScopes.back().Module = Mod; 17058 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 17059 VisibleModules.setVisible(Mod, ModuleLoc); 17060 17061 // From now on, we have an owning module for all declarations we see. 17062 // However, those declarations are module-private unless explicitly 17063 // exported. 17064 auto *TU = Context.getTranslationUnitDecl(); 17065 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 17066 TU->setLocalOwningModule(Mod); 17067 17068 // FIXME: Create a ModuleDecl. 17069 return nullptr; 17070 } 17071 17072 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 17073 SourceLocation ImportLoc, 17074 ModuleIdPath Path) { 17075 // Flatten the module path for a Modules TS module name. 17076 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc; 17077 if (getLangOpts().ModulesTS) { 17078 std::string ModuleName; 17079 for (auto &Piece : Path) { 17080 if (!ModuleName.empty()) 17081 ModuleName += "."; 17082 ModuleName += Piece.first->getName(); 17083 } 17084 ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second}; 17085 Path = ModuleIdPath(ModuleNameLoc); 17086 } 17087 17088 Module *Mod = 17089 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 17090 /*IsIncludeDirective=*/false); 17091 if (!Mod) 17092 return true; 17093 17094 VisibleModules.setVisible(Mod, ImportLoc); 17095 17096 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 17097 17098 // FIXME: we should support importing a submodule within a different submodule 17099 // of the same top-level module. Until we do, make it an error rather than 17100 // silently ignoring the import. 17101 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 17102 // warn on a redundant import of the current module? 17103 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 17104 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 17105 Diag(ImportLoc, getLangOpts().isCompilingModule() 17106 ? diag::err_module_self_import 17107 : diag::err_module_import_in_implementation) 17108 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 17109 17110 SmallVector<SourceLocation, 2> IdentifierLocs; 17111 Module *ModCheck = Mod; 17112 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 17113 // If we've run out of module parents, just drop the remaining identifiers. 17114 // We need the length to be consistent. 17115 if (!ModCheck) 17116 break; 17117 ModCheck = ModCheck->Parent; 17118 17119 IdentifierLocs.push_back(Path[I].second); 17120 } 17121 17122 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 17123 Mod, IdentifierLocs); 17124 if (!ModuleScopes.empty()) 17125 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 17126 CurContext->addDecl(Import); 17127 17128 // Re-export the module if needed. 17129 if (Import->isExported() && 17130 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) 17131 getCurrentModule()->Exports.emplace_back(Mod, false); 17132 17133 return Import; 17134 } 17135 17136 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 17137 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 17138 BuildModuleInclude(DirectiveLoc, Mod); 17139 } 17140 17141 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 17142 // Determine whether we're in the #include buffer for a module. The #includes 17143 // in that buffer do not qualify as module imports; they're just an 17144 // implementation detail of us building the module. 17145 // 17146 // FIXME: Should we even get ActOnModuleInclude calls for those? 17147 bool IsInModuleIncludes = 17148 TUKind == TU_Module && 17149 getSourceManager().isWrittenInMainFile(DirectiveLoc); 17150 17151 bool ShouldAddImport = !IsInModuleIncludes; 17152 17153 // If this module import was due to an inclusion directive, create an 17154 // implicit import declaration to capture it in the AST. 17155 if (ShouldAddImport) { 17156 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 17157 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 17158 DirectiveLoc, Mod, 17159 DirectiveLoc); 17160 if (!ModuleScopes.empty()) 17161 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 17162 TU->addDecl(ImportD); 17163 Consumer.HandleImplicitImportDecl(ImportD); 17164 } 17165 17166 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 17167 VisibleModules.setVisible(Mod, DirectiveLoc); 17168 } 17169 17170 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 17171 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 17172 17173 ModuleScopes.push_back({}); 17174 ModuleScopes.back().Module = Mod; 17175 if (getLangOpts().ModulesLocalVisibility) 17176 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 17177 17178 VisibleModules.setVisible(Mod, DirectiveLoc); 17179 17180 // The enclosing context is now part of this module. 17181 // FIXME: Consider creating a child DeclContext to hold the entities 17182 // lexically within the module. 17183 if (getLangOpts().trackLocalOwningModule()) { 17184 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 17185 cast<Decl>(DC)->setModuleOwnershipKind( 17186 getLangOpts().ModulesLocalVisibility 17187 ? Decl::ModuleOwnershipKind::VisibleWhenImported 17188 : Decl::ModuleOwnershipKind::Visible); 17189 cast<Decl>(DC)->setLocalOwningModule(Mod); 17190 } 17191 } 17192 } 17193 17194 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 17195 if (getLangOpts().ModulesLocalVisibility) { 17196 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 17197 // Leaving a module hides namespace names, so our visible namespace cache 17198 // is now out of date. 17199 VisibleNamespaceCache.clear(); 17200 } 17201 17202 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 17203 "left the wrong module scope"); 17204 ModuleScopes.pop_back(); 17205 17206 // We got to the end of processing a local module. Create an 17207 // ImportDecl as we would for an imported module. 17208 FileID File = getSourceManager().getFileID(EomLoc); 17209 SourceLocation DirectiveLoc; 17210 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 17211 // We reached the end of a #included module header. Use the #include loc. 17212 assert(File != getSourceManager().getMainFileID() && 17213 "end of submodule in main source file"); 17214 DirectiveLoc = getSourceManager().getIncludeLoc(File); 17215 } else { 17216 // We reached an EOM pragma. Use the pragma location. 17217 DirectiveLoc = EomLoc; 17218 } 17219 BuildModuleInclude(DirectiveLoc, Mod); 17220 17221 // Any further declarations are in whatever module we returned to. 17222 if (getLangOpts().trackLocalOwningModule()) { 17223 // The parser guarantees that this is the same context that we entered 17224 // the module within. 17225 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 17226 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 17227 if (!getCurrentModule()) 17228 cast<Decl>(DC)->setModuleOwnershipKind( 17229 Decl::ModuleOwnershipKind::Unowned); 17230 } 17231 } 17232 } 17233 17234 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 17235 Module *Mod) { 17236 // Bail if we're not allowed to implicitly import a module here. 17237 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 17238 VisibleModules.isVisible(Mod)) 17239 return; 17240 17241 // Create the implicit import declaration. 17242 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 17243 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 17244 Loc, Mod, Loc); 17245 TU->addDecl(ImportD); 17246 Consumer.HandleImplicitImportDecl(ImportD); 17247 17248 // Make the module visible. 17249 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 17250 VisibleModules.setVisible(Mod, Loc); 17251 } 17252 17253 /// We have parsed the start of an export declaration, including the '{' 17254 /// (if present). 17255 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 17256 SourceLocation LBraceLoc) { 17257 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 17258 17259 // C++ Modules TS draft: 17260 // An export-declaration shall appear in the purview of a module other than 17261 // the global module. 17262 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 17263 Diag(ExportLoc, diag::err_export_not_in_module_interface); 17264 17265 // An export-declaration [...] shall not contain more than one 17266 // export keyword. 17267 // 17268 // The intent here is that an export-declaration cannot appear within another 17269 // export-declaration. 17270 if (D->isExported()) 17271 Diag(ExportLoc, diag::err_export_within_export); 17272 17273 CurContext->addDecl(D); 17274 PushDeclContext(S, D); 17275 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 17276 return D; 17277 } 17278 17279 /// Complete the definition of an export declaration. 17280 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 17281 auto *ED = cast<ExportDecl>(D); 17282 if (RBraceLoc.isValid()) 17283 ED->setRBraceLoc(RBraceLoc); 17284 17285 // FIXME: Diagnose export of internal-linkage declaration (including 17286 // anonymous namespace). 17287 17288 PopDeclContext(); 17289 return D; 17290 } 17291 17292 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17293 IdentifierInfo* AliasName, 17294 SourceLocation PragmaLoc, 17295 SourceLocation NameLoc, 17296 SourceLocation AliasNameLoc) { 17297 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17298 LookupOrdinaryName); 17299 AsmLabelAttr *Attr = 17300 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 17301 17302 // If a declaration that: 17303 // 1) declares a function or a variable 17304 // 2) has external linkage 17305 // already exists, add a label attribute to it. 17306 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17307 if (isDeclExternC(PrevDecl)) 17308 PrevDecl->addAttr(Attr); 17309 else 17310 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17311 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17312 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17313 } else 17314 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17315 } 17316 17317 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17318 SourceLocation PragmaLoc, 17319 SourceLocation NameLoc) { 17320 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17321 17322 if (PrevDecl) { 17323 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 17324 } else { 17325 (void)WeakUndeclaredIdentifiers.insert( 17326 std::pair<IdentifierInfo*,WeakInfo> 17327 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17328 } 17329 } 17330 17331 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17332 IdentifierInfo* AliasName, 17333 SourceLocation PragmaLoc, 17334 SourceLocation NameLoc, 17335 SourceLocation AliasNameLoc) { 17336 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17337 LookupOrdinaryName); 17338 WeakInfo W = WeakInfo(Name, NameLoc); 17339 17340 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17341 if (!PrevDecl->hasAttr<AliasAttr>()) 17342 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17343 DeclApplyPragmaWeak(TUScope, ND, W); 17344 } else { 17345 (void)WeakUndeclaredIdentifiers.insert( 17346 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 17347 } 17348 } 17349 17350 Decl *Sema::getObjCDeclContext() const { 17351 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 17352 } 17353