1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw___ibm128: 145 case tok::kw_wchar_t: 146 case tok::kw_bool: 147 case tok::kw___underlying_type: 148 case tok::kw___auto_type: 149 return true; 150 151 case tok::annot_typename: 152 case tok::kw_char16_t: 153 case tok::kw_char32_t: 154 case tok::kw_typeof: 155 case tok::annot_decltype: 156 case tok::kw_decltype: 157 return getLangOpts().CPlusPlus; 158 159 case tok::kw_char8_t: 160 return getLangOpts().Char8; 161 162 default: 163 break; 164 } 165 166 return false; 167 } 168 169 namespace { 170 enum class UnqualifiedTypeNameLookupResult { 171 NotFound, 172 FoundNonType, 173 FoundType 174 }; 175 } // end anonymous namespace 176 177 /// Tries to perform unqualified lookup of the type decls in bases for 178 /// dependent class. 179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 180 /// type decl, \a FoundType if only type decls are found. 181 static UnqualifiedTypeNameLookupResult 182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 183 SourceLocation NameLoc, 184 const CXXRecordDecl *RD) { 185 if (!RD->hasDefinition()) 186 return UnqualifiedTypeNameLookupResult::NotFound; 187 // Look for type decls in base classes. 188 UnqualifiedTypeNameLookupResult FoundTypeDecl = 189 UnqualifiedTypeNameLookupResult::NotFound; 190 for (const auto &Base : RD->bases()) { 191 const CXXRecordDecl *BaseRD = nullptr; 192 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 193 BaseRD = BaseTT->getAsCXXRecordDecl(); 194 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 195 // Look for type decls in dependent base classes that have known primary 196 // templates. 197 if (!TST || !TST->isDependentType()) 198 continue; 199 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 200 if (!TD) 201 continue; 202 if (auto *BasePrimaryTemplate = 203 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 204 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 205 BaseRD = BasePrimaryTemplate; 206 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 207 if (const ClassTemplatePartialSpecializationDecl *PS = 208 CTD->findPartialSpecialization(Base.getType())) 209 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 210 BaseRD = PS; 211 } 212 } 213 } 214 if (BaseRD) { 215 for (NamedDecl *ND : BaseRD->lookup(&II)) { 216 if (!isa<TypeDecl>(ND)) 217 return UnqualifiedTypeNameLookupResult::FoundNonType; 218 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 219 } 220 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 221 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 222 case UnqualifiedTypeNameLookupResult::FoundNonType: 223 return UnqualifiedTypeNameLookupResult::FoundNonType; 224 case UnqualifiedTypeNameLookupResult::FoundType: 225 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 226 break; 227 case UnqualifiedTypeNameLookupResult::NotFound: 228 break; 229 } 230 } 231 } 232 } 233 234 return FoundTypeDecl; 235 } 236 237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 238 const IdentifierInfo &II, 239 SourceLocation NameLoc) { 240 // Lookup in the parent class template context, if any. 241 const CXXRecordDecl *RD = nullptr; 242 UnqualifiedTypeNameLookupResult FoundTypeDecl = 243 UnqualifiedTypeNameLookupResult::NotFound; 244 for (DeclContext *DC = S.CurContext; 245 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 246 DC = DC->getParent()) { 247 // Look for type decls in dependent base classes that have known primary 248 // templates. 249 RD = dyn_cast<CXXRecordDecl>(DC); 250 if (RD && RD->getDescribedClassTemplate()) 251 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 252 } 253 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 254 return nullptr; 255 256 // We found some types in dependent base classes. Recover as if the user 257 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 258 // lookup during template instantiation. 259 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 260 261 ASTContext &Context = S.Context; 262 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 263 cast<Type>(Context.getRecordType(RD))); 264 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 265 266 CXXScopeSpec SS; 267 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 268 269 TypeLocBuilder Builder; 270 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 271 DepTL.setNameLoc(NameLoc); 272 DepTL.setElaboratedKeywordLoc(SourceLocation()); 273 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 274 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 275 } 276 277 /// If the identifier refers to a type name within this scope, 278 /// return the declaration of that type. 279 /// 280 /// This routine performs ordinary name lookup of the identifier II 281 /// within the given scope, with optional C++ scope specifier SS, to 282 /// determine whether the name refers to a type. If so, returns an 283 /// opaque pointer (actually a QualType) corresponding to that 284 /// type. Otherwise, returns NULL. 285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 286 Scope *S, CXXScopeSpec *SS, 287 bool isClassName, bool HasTrailingDot, 288 ParsedType ObjectTypePtr, 289 bool IsCtorOrDtorName, 290 bool WantNontrivialTypeSourceInfo, 291 bool IsClassTemplateDeductionContext, 292 IdentifierInfo **CorrectedII) { 293 // FIXME: Consider allowing this outside C++1z mode as an extension. 294 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 295 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 296 !isClassName && !HasTrailingDot; 297 298 // Determine where we will perform name lookup. 299 DeclContext *LookupCtx = nullptr; 300 if (ObjectTypePtr) { 301 QualType ObjectType = ObjectTypePtr.get(); 302 if (ObjectType->isRecordType()) 303 LookupCtx = computeDeclContext(ObjectType); 304 } else if (SS && SS->isNotEmpty()) { 305 LookupCtx = computeDeclContext(*SS, false); 306 307 if (!LookupCtx) { 308 if (isDependentScopeSpecifier(*SS)) { 309 // C++ [temp.res]p3: 310 // A qualified-id that refers to a type and in which the 311 // nested-name-specifier depends on a template-parameter (14.6.2) 312 // shall be prefixed by the keyword typename to indicate that the 313 // qualified-id denotes a type, forming an 314 // elaborated-type-specifier (7.1.5.3). 315 // 316 // We therefore do not perform any name lookup if the result would 317 // refer to a member of an unknown specialization. 318 if (!isClassName && !IsCtorOrDtorName) 319 return nullptr; 320 321 // We know from the grammar that this name refers to a type, 322 // so build a dependent node to describe the type. 323 if (WantNontrivialTypeSourceInfo) 324 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 325 326 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 327 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 328 II, NameLoc); 329 return ParsedType::make(T); 330 } 331 332 return nullptr; 333 } 334 335 if (!LookupCtx->isDependentContext() && 336 RequireCompleteDeclContext(*SS, LookupCtx)) 337 return nullptr; 338 } 339 340 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 341 // lookup for class-names. 342 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 343 LookupOrdinaryName; 344 LookupResult Result(*this, &II, NameLoc, Kind); 345 if (LookupCtx) { 346 // Perform "qualified" name lookup into the declaration context we 347 // computed, which is either the type of the base of a member access 348 // expression or the declaration context associated with a prior 349 // nested-name-specifier. 350 LookupQualifiedName(Result, LookupCtx); 351 352 if (ObjectTypePtr && Result.empty()) { 353 // C++ [basic.lookup.classref]p3: 354 // If the unqualified-id is ~type-name, the type-name is looked up 355 // in the context of the entire postfix-expression. If the type T of 356 // the object expression is of a class type C, the type-name is also 357 // looked up in the scope of class C. At least one of the lookups shall 358 // find a name that refers to (possibly cv-qualified) T. 359 LookupName(Result, S); 360 } 361 } else { 362 // Perform unqualified name lookup. 363 LookupName(Result, S); 364 365 // For unqualified lookup in a class template in MSVC mode, look into 366 // dependent base classes where the primary class template is known. 367 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 368 if (ParsedType TypeInBase = 369 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 370 return TypeInBase; 371 } 372 } 373 374 NamedDecl *IIDecl = nullptr; 375 switch (Result.getResultKind()) { 376 case LookupResult::NotFound: 377 case LookupResult::NotFoundInCurrentInstantiation: 378 if (CorrectedII) { 379 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 380 AllowDeducedTemplate); 381 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 382 S, SS, CCC, CTK_ErrorRecovery); 383 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 384 TemplateTy Template; 385 bool MemberOfUnknownSpecialization; 386 UnqualifiedId TemplateName; 387 TemplateName.setIdentifier(NewII, NameLoc); 388 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 389 CXXScopeSpec NewSS, *NewSSPtr = SS; 390 if (SS && NNS) { 391 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 392 NewSSPtr = &NewSS; 393 } 394 if (Correction && (NNS || NewII != &II) && 395 // Ignore a correction to a template type as the to-be-corrected 396 // identifier is not a template (typo correction for template names 397 // is handled elsewhere). 398 !(getLangOpts().CPlusPlus && NewSSPtr && 399 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 400 Template, MemberOfUnknownSpecialization))) { 401 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 402 isClassName, HasTrailingDot, ObjectTypePtr, 403 IsCtorOrDtorName, 404 WantNontrivialTypeSourceInfo, 405 IsClassTemplateDeductionContext); 406 if (Ty) { 407 diagnoseTypo(Correction, 408 PDiag(diag::err_unknown_type_or_class_name_suggest) 409 << Result.getLookupName() << isClassName); 410 if (SS && NNS) 411 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 412 *CorrectedII = NewII; 413 return Ty; 414 } 415 } 416 } 417 // If typo correction failed or was not performed, fall through 418 LLVM_FALLTHROUGH; 419 case LookupResult::FoundOverloaded: 420 case LookupResult::FoundUnresolvedValue: 421 Result.suppressDiagnostics(); 422 return nullptr; 423 424 case LookupResult::Ambiguous: 425 // Recover from type-hiding ambiguities by hiding the type. We'll 426 // do the lookup again when looking for an object, and we can 427 // diagnose the error then. If we don't do this, then the error 428 // about hiding the type will be immediately followed by an error 429 // that only makes sense if the identifier was treated like a type. 430 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 431 Result.suppressDiagnostics(); 432 return nullptr; 433 } 434 435 // Look to see if we have a type anywhere in the list of results. 436 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 437 Res != ResEnd; ++Res) { 438 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 439 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 440 RealRes) || 441 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 442 if (!IIDecl || 443 // Make the selection of the recovery decl deterministic. 444 RealRes->getLocation() < IIDecl->getLocation()) 445 IIDecl = RealRes; 446 } 447 } 448 449 if (!IIDecl) { 450 // None of the entities we found is a type, so there is no way 451 // to even assume that the result is a type. In this case, don't 452 // complain about the ambiguity. The parser will either try to 453 // perform this lookup again (e.g., as an object name), which 454 // will produce the ambiguity, or will complain that it expected 455 // a type name. 456 Result.suppressDiagnostics(); 457 return nullptr; 458 } 459 460 // We found a type within the ambiguous lookup; diagnose the 461 // ambiguity and then return that type. This might be the right 462 // answer, or it might not be, but it suppresses any attempt to 463 // perform the name lookup again. 464 break; 465 466 case LookupResult::Found: 467 IIDecl = Result.getFoundDecl(); 468 break; 469 } 470 471 assert(IIDecl && "Didn't find decl"); 472 473 QualType T; 474 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 475 // C++ [class.qual]p2: A lookup that would find the injected-class-name 476 // instead names the constructors of the class, except when naming a class. 477 // This is ill-formed when we're not actually forming a ctor or dtor name. 478 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 479 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 480 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 481 FoundRD->isInjectedClassName() && 482 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 483 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 484 << &II << /*Type*/1; 485 486 DiagnoseUseOfDecl(IIDecl, NameLoc); 487 488 T = Context.getTypeDeclType(TD); 489 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 490 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 491 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 492 if (!HasTrailingDot) 493 T = Context.getObjCInterfaceType(IDecl); 494 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 495 (void)DiagnoseUseOfDecl(UD, NameLoc); 496 // Recover with 'int' 497 T = Context.IntTy; 498 } else if (AllowDeducedTemplate) { 499 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 500 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 501 QualType(), false); 502 } 503 504 if (T.isNull()) { 505 // If it's not plausibly a type, suppress diagnostics. 506 Result.suppressDiagnostics(); 507 return nullptr; 508 } 509 510 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 511 // constructor or destructor name (in such a case, the scope specifier 512 // will be attached to the enclosing Expr or Decl node). 513 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 514 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { 515 if (WantNontrivialTypeSourceInfo) { 516 // Construct a type with type-source information. 517 TypeLocBuilder Builder; 518 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 519 520 T = getElaboratedType(ETK_None, *SS, T); 521 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 522 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 523 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 524 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 525 } else { 526 T = getElaboratedType(ETK_None, *SS, T); 527 } 528 } 529 530 return ParsedType::make(T); 531 } 532 533 // Builds a fake NNS for the given decl context. 534 static NestedNameSpecifier * 535 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 536 for (;; DC = DC->getLookupParent()) { 537 DC = DC->getPrimaryContext(); 538 auto *ND = dyn_cast<NamespaceDecl>(DC); 539 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 540 return NestedNameSpecifier::Create(Context, nullptr, ND); 541 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 542 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 543 RD->getTypeForDecl()); 544 else if (isa<TranslationUnitDecl>(DC)) 545 return NestedNameSpecifier::GlobalSpecifier(Context); 546 } 547 llvm_unreachable("something isn't in TU scope?"); 548 } 549 550 /// Find the parent class with dependent bases of the innermost enclosing method 551 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 552 /// up allowing unqualified dependent type names at class-level, which MSVC 553 /// correctly rejects. 554 static const CXXRecordDecl * 555 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 556 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 557 DC = DC->getPrimaryContext(); 558 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 559 if (MD->getParent()->hasAnyDependentBases()) 560 return MD->getParent(); 561 } 562 return nullptr; 563 } 564 565 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 566 SourceLocation NameLoc, 567 bool IsTemplateTypeArg) { 568 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 569 570 NestedNameSpecifier *NNS = nullptr; 571 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 572 // If we weren't able to parse a default template argument, delay lookup 573 // until instantiation time by making a non-dependent DependentTypeName. We 574 // pretend we saw a NestedNameSpecifier referring to the current scope, and 575 // lookup is retried. 576 // FIXME: This hurts our diagnostic quality, since we get errors like "no 577 // type named 'Foo' in 'current_namespace'" when the user didn't write any 578 // name specifiers. 579 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 580 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 581 } else if (const CXXRecordDecl *RD = 582 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 583 // Build a DependentNameType that will perform lookup into RD at 584 // instantiation time. 585 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 586 RD->getTypeForDecl()); 587 588 // Diagnose that this identifier was undeclared, and retry the lookup during 589 // template instantiation. 590 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 591 << RD; 592 } else { 593 // This is not a situation that we should recover from. 594 return ParsedType(); 595 } 596 597 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 598 599 // Build type location information. We synthesized the qualifier, so we have 600 // to build a fake NestedNameSpecifierLoc. 601 NestedNameSpecifierLocBuilder NNSLocBuilder; 602 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 603 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 604 605 TypeLocBuilder Builder; 606 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 607 DepTL.setNameLoc(NameLoc); 608 DepTL.setElaboratedKeywordLoc(SourceLocation()); 609 DepTL.setQualifierLoc(QualifierLoc); 610 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 611 } 612 613 /// isTagName() - This method is called *for error recovery purposes only* 614 /// to determine if the specified name is a valid tag name ("struct foo"). If 615 /// so, this returns the TST for the tag corresponding to it (TST_enum, 616 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 617 /// cases in C where the user forgot to specify the tag. 618 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 619 // Do a tag name lookup in this scope. 620 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 621 LookupName(R, S, false); 622 R.suppressDiagnostics(); 623 if (R.getResultKind() == LookupResult::Found) 624 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 625 switch (TD->getTagKind()) { 626 case TTK_Struct: return DeclSpec::TST_struct; 627 case TTK_Interface: return DeclSpec::TST_interface; 628 case TTK_Union: return DeclSpec::TST_union; 629 case TTK_Class: return DeclSpec::TST_class; 630 case TTK_Enum: return DeclSpec::TST_enum; 631 } 632 } 633 634 return DeclSpec::TST_unspecified; 635 } 636 637 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 638 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 639 /// then downgrade the missing typename error to a warning. 640 /// This is needed for MSVC compatibility; Example: 641 /// @code 642 /// template<class T> class A { 643 /// public: 644 /// typedef int TYPE; 645 /// }; 646 /// template<class T> class B : public A<T> { 647 /// public: 648 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 649 /// }; 650 /// @endcode 651 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 652 if (CurContext->isRecord()) { 653 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 654 return true; 655 656 const Type *Ty = SS->getScopeRep()->getAsType(); 657 658 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 659 for (const auto &Base : RD->bases()) 660 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 661 return true; 662 return S->isFunctionPrototypeScope(); 663 } 664 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 665 } 666 667 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 668 SourceLocation IILoc, 669 Scope *S, 670 CXXScopeSpec *SS, 671 ParsedType &SuggestedType, 672 bool IsTemplateName) { 673 // Don't report typename errors for editor placeholders. 674 if (II->isEditorPlaceholder()) 675 return; 676 // We don't have anything to suggest (yet). 677 SuggestedType = nullptr; 678 679 // There may have been a typo in the name of the type. Look up typo 680 // results, in case we have something that we can suggest. 681 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 682 /*AllowTemplates=*/IsTemplateName, 683 /*AllowNonTemplates=*/!IsTemplateName); 684 if (TypoCorrection Corrected = 685 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 686 CCC, CTK_ErrorRecovery)) { 687 // FIXME: Support error recovery for the template-name case. 688 bool CanRecover = !IsTemplateName; 689 if (Corrected.isKeyword()) { 690 // We corrected to a keyword. 691 diagnoseTypo(Corrected, 692 PDiag(IsTemplateName ? diag::err_no_template_suggest 693 : diag::err_unknown_typename_suggest) 694 << II); 695 II = Corrected.getCorrectionAsIdentifierInfo(); 696 } else { 697 // We found a similarly-named type or interface; suggest that. 698 if (!SS || !SS->isSet()) { 699 diagnoseTypo(Corrected, 700 PDiag(IsTemplateName ? diag::err_no_template_suggest 701 : diag::err_unknown_typename_suggest) 702 << II, CanRecover); 703 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 704 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 705 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 706 II->getName().equals(CorrectedStr); 707 diagnoseTypo(Corrected, 708 PDiag(IsTemplateName 709 ? diag::err_no_member_template_suggest 710 : diag::err_unknown_nested_typename_suggest) 711 << II << DC << DroppedSpecifier << SS->getRange(), 712 CanRecover); 713 } else { 714 llvm_unreachable("could not have corrected a typo here"); 715 } 716 717 if (!CanRecover) 718 return; 719 720 CXXScopeSpec tmpSS; 721 if (Corrected.getCorrectionSpecifier()) 722 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 723 SourceRange(IILoc)); 724 // FIXME: Support class template argument deduction here. 725 SuggestedType = 726 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 727 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 728 /*IsCtorOrDtorName=*/false, 729 /*WantNontrivialTypeSourceInfo=*/true); 730 } 731 return; 732 } 733 734 if (getLangOpts().CPlusPlus && !IsTemplateName) { 735 // See if II is a class template that the user forgot to pass arguments to. 736 UnqualifiedId Name; 737 Name.setIdentifier(II, IILoc); 738 CXXScopeSpec EmptySS; 739 TemplateTy TemplateResult; 740 bool MemberOfUnknownSpecialization; 741 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 742 Name, nullptr, true, TemplateResult, 743 MemberOfUnknownSpecialization) == TNK_Type_template) { 744 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 745 return; 746 } 747 } 748 749 // FIXME: Should we move the logic that tries to recover from a missing tag 750 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 751 752 if (!SS || (!SS->isSet() && !SS->isInvalid())) 753 Diag(IILoc, IsTemplateName ? diag::err_no_template 754 : diag::err_unknown_typename) 755 << II; 756 else if (DeclContext *DC = computeDeclContext(*SS, false)) 757 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 758 : diag::err_typename_nested_not_found) 759 << II << DC << SS->getRange(); 760 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 761 SuggestedType = 762 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 763 } else if (isDependentScopeSpecifier(*SS)) { 764 unsigned DiagID = diag::err_typename_missing; 765 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 766 DiagID = diag::ext_typename_missing; 767 768 Diag(SS->getRange().getBegin(), DiagID) 769 << SS->getScopeRep() << II->getName() 770 << SourceRange(SS->getRange().getBegin(), IILoc) 771 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 772 SuggestedType = ActOnTypenameType(S, SourceLocation(), 773 *SS, *II, IILoc).get(); 774 } else { 775 assert(SS && SS->isInvalid() && 776 "Invalid scope specifier has already been diagnosed"); 777 } 778 } 779 780 /// Determine whether the given result set contains either a type name 781 /// or 782 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 783 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 784 NextToken.is(tok::less); 785 786 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 787 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 788 return true; 789 790 if (CheckTemplate && isa<TemplateDecl>(*I)) 791 return true; 792 } 793 794 return false; 795 } 796 797 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 798 Scope *S, CXXScopeSpec &SS, 799 IdentifierInfo *&Name, 800 SourceLocation NameLoc) { 801 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 802 SemaRef.LookupParsedName(R, S, &SS); 803 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 804 StringRef FixItTagName; 805 switch (Tag->getTagKind()) { 806 case TTK_Class: 807 FixItTagName = "class "; 808 break; 809 810 case TTK_Enum: 811 FixItTagName = "enum "; 812 break; 813 814 case TTK_Struct: 815 FixItTagName = "struct "; 816 break; 817 818 case TTK_Interface: 819 FixItTagName = "__interface "; 820 break; 821 822 case TTK_Union: 823 FixItTagName = "union "; 824 break; 825 } 826 827 StringRef TagName = FixItTagName.drop_back(); 828 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 829 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 830 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 831 832 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 833 I != IEnd; ++I) 834 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 835 << Name << TagName; 836 837 // Replace lookup results with just the tag decl. 838 Result.clear(Sema::LookupTagName); 839 SemaRef.LookupParsedName(Result, S, &SS); 840 return true; 841 } 842 843 return false; 844 } 845 846 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 847 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 848 QualType T, SourceLocation NameLoc) { 849 ASTContext &Context = S.Context; 850 851 TypeLocBuilder Builder; 852 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 853 854 T = S.getElaboratedType(ETK_None, SS, T); 855 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 856 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 857 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 858 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 859 } 860 861 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 862 IdentifierInfo *&Name, 863 SourceLocation NameLoc, 864 const Token &NextToken, 865 CorrectionCandidateCallback *CCC) { 866 DeclarationNameInfo NameInfo(Name, NameLoc); 867 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 868 869 assert(NextToken.isNot(tok::coloncolon) && 870 "parse nested name specifiers before calling ClassifyName"); 871 if (getLangOpts().CPlusPlus && SS.isSet() && 872 isCurrentClassName(*Name, S, &SS)) { 873 // Per [class.qual]p2, this names the constructors of SS, not the 874 // injected-class-name. We don't have a classification for that. 875 // There's not much point caching this result, since the parser 876 // will reject it later. 877 return NameClassification::Unknown(); 878 } 879 880 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 881 LookupParsedName(Result, S, &SS, !CurMethod); 882 883 if (SS.isInvalid()) 884 return NameClassification::Error(); 885 886 // For unqualified lookup in a class template in MSVC mode, look into 887 // dependent base classes where the primary class template is known. 888 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 889 if (ParsedType TypeInBase = 890 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 891 return TypeInBase; 892 } 893 894 // Perform lookup for Objective-C instance variables (including automatically 895 // synthesized instance variables), if we're in an Objective-C method. 896 // FIXME: This lookup really, really needs to be folded in to the normal 897 // unqualified lookup mechanism. 898 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 899 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 900 if (Ivar.isInvalid()) 901 return NameClassification::Error(); 902 if (Ivar.isUsable()) 903 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 904 905 // We defer builtin creation until after ivar lookup inside ObjC methods. 906 if (Result.empty()) 907 LookupBuiltin(Result); 908 } 909 910 bool SecondTry = false; 911 bool IsFilteredTemplateName = false; 912 913 Corrected: 914 switch (Result.getResultKind()) { 915 case LookupResult::NotFound: 916 // If an unqualified-id is followed by a '(', then we have a function 917 // call. 918 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 919 // In C++, this is an ADL-only call. 920 // FIXME: Reference? 921 if (getLangOpts().CPlusPlus) 922 return NameClassification::UndeclaredNonType(); 923 924 // C90 6.3.2.2: 925 // If the expression that precedes the parenthesized argument list in a 926 // function call consists solely of an identifier, and if no 927 // declaration is visible for this identifier, the identifier is 928 // implicitly declared exactly as if, in the innermost block containing 929 // the function call, the declaration 930 // 931 // extern int identifier (); 932 // 933 // appeared. 934 // 935 // We also allow this in C99 as an extension. 936 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 937 return NameClassification::NonType(D); 938 } 939 940 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 941 // In C++20 onwards, this could be an ADL-only call to a function 942 // template, and we're required to assume that this is a template name. 943 // 944 // FIXME: Find a way to still do typo correction in this case. 945 TemplateName Template = 946 Context.getAssumedTemplateName(NameInfo.getName()); 947 return NameClassification::UndeclaredTemplate(Template); 948 } 949 950 // In C, we first see whether there is a tag type by the same name, in 951 // which case it's likely that the user just forgot to write "enum", 952 // "struct", or "union". 953 if (!getLangOpts().CPlusPlus && !SecondTry && 954 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 955 break; 956 } 957 958 // Perform typo correction to determine if there is another name that is 959 // close to this name. 960 if (!SecondTry && CCC) { 961 SecondTry = true; 962 if (TypoCorrection Corrected = 963 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 964 &SS, *CCC, CTK_ErrorRecovery)) { 965 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 966 unsigned QualifiedDiag = diag::err_no_member_suggest; 967 968 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 969 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 970 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 971 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 972 UnqualifiedDiag = diag::err_no_template_suggest; 973 QualifiedDiag = diag::err_no_member_template_suggest; 974 } else if (UnderlyingFirstDecl && 975 (isa<TypeDecl>(UnderlyingFirstDecl) || 976 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 977 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 978 UnqualifiedDiag = diag::err_unknown_typename_suggest; 979 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 980 } 981 982 if (SS.isEmpty()) { 983 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 984 } else {// FIXME: is this even reachable? Test it. 985 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 986 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 987 Name->getName().equals(CorrectedStr); 988 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 989 << Name << computeDeclContext(SS, false) 990 << DroppedSpecifier << SS.getRange()); 991 } 992 993 // Update the name, so that the caller has the new name. 994 Name = Corrected.getCorrectionAsIdentifierInfo(); 995 996 // Typo correction corrected to a keyword. 997 if (Corrected.isKeyword()) 998 return Name; 999 1000 // Also update the LookupResult... 1001 // FIXME: This should probably go away at some point 1002 Result.clear(); 1003 Result.setLookupName(Corrected.getCorrection()); 1004 if (FirstDecl) 1005 Result.addDecl(FirstDecl); 1006 1007 // If we found an Objective-C instance variable, let 1008 // LookupInObjCMethod build the appropriate expression to 1009 // reference the ivar. 1010 // FIXME: This is a gross hack. 1011 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1012 DeclResult R = 1013 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1014 if (R.isInvalid()) 1015 return NameClassification::Error(); 1016 if (R.isUsable()) 1017 return NameClassification::NonType(Ivar); 1018 } 1019 1020 goto Corrected; 1021 } 1022 } 1023 1024 // We failed to correct; just fall through and let the parser deal with it. 1025 Result.suppressDiagnostics(); 1026 return NameClassification::Unknown(); 1027 1028 case LookupResult::NotFoundInCurrentInstantiation: { 1029 // We performed name lookup into the current instantiation, and there were 1030 // dependent bases, so we treat this result the same way as any other 1031 // dependent nested-name-specifier. 1032 1033 // C++ [temp.res]p2: 1034 // A name used in a template declaration or definition and that is 1035 // dependent on a template-parameter is assumed not to name a type 1036 // unless the applicable name lookup finds a type name or the name is 1037 // qualified by the keyword typename. 1038 // 1039 // FIXME: If the next token is '<', we might want to ask the parser to 1040 // perform some heroics to see if we actually have a 1041 // template-argument-list, which would indicate a missing 'template' 1042 // keyword here. 1043 return NameClassification::DependentNonType(); 1044 } 1045 1046 case LookupResult::Found: 1047 case LookupResult::FoundOverloaded: 1048 case LookupResult::FoundUnresolvedValue: 1049 break; 1050 1051 case LookupResult::Ambiguous: 1052 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1053 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1054 /*AllowDependent=*/false)) { 1055 // C++ [temp.local]p3: 1056 // A lookup that finds an injected-class-name (10.2) can result in an 1057 // ambiguity in certain cases (for example, if it is found in more than 1058 // one base class). If all of the injected-class-names that are found 1059 // refer to specializations of the same class template, and if the name 1060 // is followed by a template-argument-list, the reference refers to the 1061 // class template itself and not a specialization thereof, and is not 1062 // ambiguous. 1063 // 1064 // This filtering can make an ambiguous result into an unambiguous one, 1065 // so try again after filtering out template names. 1066 FilterAcceptableTemplateNames(Result); 1067 if (!Result.isAmbiguous()) { 1068 IsFilteredTemplateName = true; 1069 break; 1070 } 1071 } 1072 1073 // Diagnose the ambiguity and return an error. 1074 return NameClassification::Error(); 1075 } 1076 1077 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1078 (IsFilteredTemplateName || 1079 hasAnyAcceptableTemplateNames( 1080 Result, /*AllowFunctionTemplates=*/true, 1081 /*AllowDependent=*/false, 1082 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1083 getLangOpts().CPlusPlus20))) { 1084 // C++ [temp.names]p3: 1085 // After name lookup (3.4) finds that a name is a template-name or that 1086 // an operator-function-id or a literal- operator-id refers to a set of 1087 // overloaded functions any member of which is a function template if 1088 // this is followed by a <, the < is always taken as the delimiter of a 1089 // template-argument-list and never as the less-than operator. 1090 // C++2a [temp.names]p2: 1091 // A name is also considered to refer to a template if it is an 1092 // unqualified-id followed by a < and name lookup finds either one 1093 // or more functions or finds nothing. 1094 if (!IsFilteredTemplateName) 1095 FilterAcceptableTemplateNames(Result); 1096 1097 bool IsFunctionTemplate; 1098 bool IsVarTemplate; 1099 TemplateName Template; 1100 if (Result.end() - Result.begin() > 1) { 1101 IsFunctionTemplate = true; 1102 Template = Context.getOverloadedTemplateName(Result.begin(), 1103 Result.end()); 1104 } else if (!Result.empty()) { 1105 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1106 *Result.begin(), /*AllowFunctionTemplates=*/true, 1107 /*AllowDependent=*/false)); 1108 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1109 IsVarTemplate = isa<VarTemplateDecl>(TD); 1110 1111 if (SS.isNotEmpty()) 1112 Template = 1113 Context.getQualifiedTemplateName(SS.getScopeRep(), 1114 /*TemplateKeyword=*/false, TD); 1115 else 1116 Template = TemplateName(TD); 1117 } else { 1118 // All results were non-template functions. This is a function template 1119 // name. 1120 IsFunctionTemplate = true; 1121 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1122 } 1123 1124 if (IsFunctionTemplate) { 1125 // Function templates always go through overload resolution, at which 1126 // point we'll perform the various checks (e.g., accessibility) we need 1127 // to based on which function we selected. 1128 Result.suppressDiagnostics(); 1129 1130 return NameClassification::FunctionTemplate(Template); 1131 } 1132 1133 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1134 : NameClassification::TypeTemplate(Template); 1135 } 1136 1137 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1138 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1139 DiagnoseUseOfDecl(Type, NameLoc); 1140 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1141 QualType T = Context.getTypeDeclType(Type); 1142 if (SS.isNotEmpty()) 1143 return buildNestedType(*this, SS, T, NameLoc); 1144 return ParsedType::make(T); 1145 } 1146 1147 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1148 if (!Class) { 1149 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1150 if (ObjCCompatibleAliasDecl *Alias = 1151 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1152 Class = Alias->getClassInterface(); 1153 } 1154 1155 if (Class) { 1156 DiagnoseUseOfDecl(Class, NameLoc); 1157 1158 if (NextToken.is(tok::period)) { 1159 // Interface. <something> is parsed as a property reference expression. 1160 // Just return "unknown" as a fall-through for now. 1161 Result.suppressDiagnostics(); 1162 return NameClassification::Unknown(); 1163 } 1164 1165 QualType T = Context.getObjCInterfaceType(Class); 1166 return ParsedType::make(T); 1167 } 1168 1169 if (isa<ConceptDecl>(FirstDecl)) 1170 return NameClassification::Concept( 1171 TemplateName(cast<TemplateDecl>(FirstDecl))); 1172 1173 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1174 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1175 return NameClassification::Error(); 1176 } 1177 1178 // We can have a type template here if we're classifying a template argument. 1179 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1180 !isa<VarTemplateDecl>(FirstDecl)) 1181 return NameClassification::TypeTemplate( 1182 TemplateName(cast<TemplateDecl>(FirstDecl))); 1183 1184 // Check for a tag type hidden by a non-type decl in a few cases where it 1185 // seems likely a type is wanted instead of the non-type that was found. 1186 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1187 if ((NextToken.is(tok::identifier) || 1188 (NextIsOp && 1189 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1190 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1191 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1192 DiagnoseUseOfDecl(Type, NameLoc); 1193 QualType T = Context.getTypeDeclType(Type); 1194 if (SS.isNotEmpty()) 1195 return buildNestedType(*this, SS, T, NameLoc); 1196 return ParsedType::make(T); 1197 } 1198 1199 // If we already know which single declaration is referenced, just annotate 1200 // that declaration directly. Defer resolving even non-overloaded class 1201 // member accesses, as we need to defer certain access checks until we know 1202 // the context. 1203 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1204 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1205 return NameClassification::NonType(Result.getRepresentativeDecl()); 1206 1207 // Otherwise, this is an overload set that we will need to resolve later. 1208 Result.suppressDiagnostics(); 1209 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1210 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1211 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1212 Result.begin(), Result.end())); 1213 } 1214 1215 ExprResult 1216 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1217 SourceLocation NameLoc) { 1218 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1219 CXXScopeSpec SS; 1220 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1221 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1222 } 1223 1224 ExprResult 1225 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1226 IdentifierInfo *Name, 1227 SourceLocation NameLoc, 1228 bool IsAddressOfOperand) { 1229 DeclarationNameInfo NameInfo(Name, NameLoc); 1230 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1231 NameInfo, IsAddressOfOperand, 1232 /*TemplateArgs=*/nullptr); 1233 } 1234 1235 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1236 NamedDecl *Found, 1237 SourceLocation NameLoc, 1238 const Token &NextToken) { 1239 if (getCurMethodDecl() && SS.isEmpty()) 1240 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1241 return BuildIvarRefExpr(S, NameLoc, Ivar); 1242 1243 // Reconstruct the lookup result. 1244 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1245 Result.addDecl(Found); 1246 Result.resolveKind(); 1247 1248 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1249 return BuildDeclarationNameExpr(SS, Result, ADL); 1250 } 1251 1252 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1253 // For an implicit class member access, transform the result into a member 1254 // access expression if necessary. 1255 auto *ULE = cast<UnresolvedLookupExpr>(E); 1256 if ((*ULE->decls_begin())->isCXXClassMember()) { 1257 CXXScopeSpec SS; 1258 SS.Adopt(ULE->getQualifierLoc()); 1259 1260 // Reconstruct the lookup result. 1261 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1262 LookupOrdinaryName); 1263 Result.setNamingClass(ULE->getNamingClass()); 1264 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1265 Result.addDecl(*I, I.getAccess()); 1266 Result.resolveKind(); 1267 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1268 nullptr, S); 1269 } 1270 1271 // Otherwise, this is already in the form we needed, and no further checks 1272 // are necessary. 1273 return ULE; 1274 } 1275 1276 Sema::TemplateNameKindForDiagnostics 1277 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1278 auto *TD = Name.getAsTemplateDecl(); 1279 if (!TD) 1280 return TemplateNameKindForDiagnostics::DependentTemplate; 1281 if (isa<ClassTemplateDecl>(TD)) 1282 return TemplateNameKindForDiagnostics::ClassTemplate; 1283 if (isa<FunctionTemplateDecl>(TD)) 1284 return TemplateNameKindForDiagnostics::FunctionTemplate; 1285 if (isa<VarTemplateDecl>(TD)) 1286 return TemplateNameKindForDiagnostics::VarTemplate; 1287 if (isa<TypeAliasTemplateDecl>(TD)) 1288 return TemplateNameKindForDiagnostics::AliasTemplate; 1289 if (isa<TemplateTemplateParmDecl>(TD)) 1290 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1291 if (isa<ConceptDecl>(TD)) 1292 return TemplateNameKindForDiagnostics::Concept; 1293 return TemplateNameKindForDiagnostics::DependentTemplate; 1294 } 1295 1296 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1297 assert(DC->getLexicalParent() == CurContext && 1298 "The next DeclContext should be lexically contained in the current one."); 1299 CurContext = DC; 1300 S->setEntity(DC); 1301 } 1302 1303 void Sema::PopDeclContext() { 1304 assert(CurContext && "DeclContext imbalance!"); 1305 1306 CurContext = CurContext->getLexicalParent(); 1307 assert(CurContext && "Popped translation unit!"); 1308 } 1309 1310 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1311 Decl *D) { 1312 // Unlike PushDeclContext, the context to which we return is not necessarily 1313 // the containing DC of TD, because the new context will be some pre-existing 1314 // TagDecl definition instead of a fresh one. 1315 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1316 CurContext = cast<TagDecl>(D)->getDefinition(); 1317 assert(CurContext && "skipping definition of undefined tag"); 1318 // Start lookups from the parent of the current context; we don't want to look 1319 // into the pre-existing complete definition. 1320 S->setEntity(CurContext->getLookupParent()); 1321 return Result; 1322 } 1323 1324 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1325 CurContext = static_cast<decltype(CurContext)>(Context); 1326 } 1327 1328 /// EnterDeclaratorContext - Used when we must lookup names in the context 1329 /// of a declarator's nested name specifier. 1330 /// 1331 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1332 // C++0x [basic.lookup.unqual]p13: 1333 // A name used in the definition of a static data member of class 1334 // X (after the qualified-id of the static member) is looked up as 1335 // if the name was used in a member function of X. 1336 // C++0x [basic.lookup.unqual]p14: 1337 // If a variable member of a namespace is defined outside of the 1338 // scope of its namespace then any name used in the definition of 1339 // the variable member (after the declarator-id) is looked up as 1340 // if the definition of the variable member occurred in its 1341 // namespace. 1342 // Both of these imply that we should push a scope whose context 1343 // is the semantic context of the declaration. We can't use 1344 // PushDeclContext here because that context is not necessarily 1345 // lexically contained in the current context. Fortunately, 1346 // the containing scope should have the appropriate information. 1347 1348 assert(!S->getEntity() && "scope already has entity"); 1349 1350 #ifndef NDEBUG 1351 Scope *Ancestor = S->getParent(); 1352 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1353 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1354 #endif 1355 1356 CurContext = DC; 1357 S->setEntity(DC); 1358 1359 if (S->getParent()->isTemplateParamScope()) { 1360 // Also set the corresponding entities for all immediately-enclosing 1361 // template parameter scopes. 1362 EnterTemplatedContext(S->getParent(), DC); 1363 } 1364 } 1365 1366 void Sema::ExitDeclaratorContext(Scope *S) { 1367 assert(S->getEntity() == CurContext && "Context imbalance!"); 1368 1369 // Switch back to the lexical context. The safety of this is 1370 // enforced by an assert in EnterDeclaratorContext. 1371 Scope *Ancestor = S->getParent(); 1372 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1373 CurContext = Ancestor->getEntity(); 1374 1375 // We don't need to do anything with the scope, which is going to 1376 // disappear. 1377 } 1378 1379 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1380 assert(S->isTemplateParamScope() && 1381 "expected to be initializing a template parameter scope"); 1382 1383 // C++20 [temp.local]p7: 1384 // In the definition of a member of a class template that appears outside 1385 // of the class template definition, the name of a member of the class 1386 // template hides the name of a template-parameter of any enclosing class 1387 // templates (but not a template-parameter of the member if the member is a 1388 // class or function template). 1389 // C++20 [temp.local]p9: 1390 // In the definition of a class template or in the definition of a member 1391 // of such a template that appears outside of the template definition, for 1392 // each non-dependent base class (13.8.2.1), if the name of the base class 1393 // or the name of a member of the base class is the same as the name of a 1394 // template-parameter, the base class name or member name hides the 1395 // template-parameter name (6.4.10). 1396 // 1397 // This means that a template parameter scope should be searched immediately 1398 // after searching the DeclContext for which it is a template parameter 1399 // scope. For example, for 1400 // template<typename T> template<typename U> template<typename V> 1401 // void N::A<T>::B<U>::f(...) 1402 // we search V then B<U> (and base classes) then U then A<T> (and base 1403 // classes) then T then N then ::. 1404 unsigned ScopeDepth = getTemplateDepth(S); 1405 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1406 DeclContext *SearchDCAfterScope = DC; 1407 for (; DC; DC = DC->getLookupParent()) { 1408 if (const TemplateParameterList *TPL = 1409 cast<Decl>(DC)->getDescribedTemplateParams()) { 1410 unsigned DCDepth = TPL->getDepth() + 1; 1411 if (DCDepth > ScopeDepth) 1412 continue; 1413 if (ScopeDepth == DCDepth) 1414 SearchDCAfterScope = DC = DC->getLookupParent(); 1415 break; 1416 } 1417 } 1418 S->setLookupEntity(SearchDCAfterScope); 1419 } 1420 } 1421 1422 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1423 // We assume that the caller has already called 1424 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1425 FunctionDecl *FD = D->getAsFunction(); 1426 if (!FD) 1427 return; 1428 1429 // Same implementation as PushDeclContext, but enters the context 1430 // from the lexical parent, rather than the top-level class. 1431 assert(CurContext == FD->getLexicalParent() && 1432 "The next DeclContext should be lexically contained in the current one."); 1433 CurContext = FD; 1434 S->setEntity(CurContext); 1435 1436 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1437 ParmVarDecl *Param = FD->getParamDecl(P); 1438 // If the parameter has an identifier, then add it to the scope 1439 if (Param->getIdentifier()) { 1440 S->AddDecl(Param); 1441 IdResolver.AddDecl(Param); 1442 } 1443 } 1444 } 1445 1446 void Sema::ActOnExitFunctionContext() { 1447 // Same implementation as PopDeclContext, but returns to the lexical parent, 1448 // rather than the top-level class. 1449 assert(CurContext && "DeclContext imbalance!"); 1450 CurContext = CurContext->getLexicalParent(); 1451 assert(CurContext && "Popped translation unit!"); 1452 } 1453 1454 /// Determine whether we allow overloading of the function 1455 /// PrevDecl with another declaration. 1456 /// 1457 /// This routine determines whether overloading is possible, not 1458 /// whether some new function is actually an overload. It will return 1459 /// true in C++ (where we can always provide overloads) or, as an 1460 /// extension, in C when the previous function is already an 1461 /// overloaded function declaration or has the "overloadable" 1462 /// attribute. 1463 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1464 ASTContext &Context, 1465 const FunctionDecl *New) { 1466 if (Context.getLangOpts().CPlusPlus) 1467 return true; 1468 1469 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1470 return true; 1471 1472 return Previous.getResultKind() == LookupResult::Found && 1473 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1474 New->hasAttr<OverloadableAttr>()); 1475 } 1476 1477 /// Add this decl to the scope shadowed decl chains. 1478 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1479 // Move up the scope chain until we find the nearest enclosing 1480 // non-transparent context. The declaration will be introduced into this 1481 // scope. 1482 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1483 S = S->getParent(); 1484 1485 // Add scoped declarations into their context, so that they can be 1486 // found later. Declarations without a context won't be inserted 1487 // into any context. 1488 if (AddToContext) 1489 CurContext->addDecl(D); 1490 1491 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1492 // are function-local declarations. 1493 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1494 return; 1495 1496 // Template instantiations should also not be pushed into scope. 1497 if (isa<FunctionDecl>(D) && 1498 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1499 return; 1500 1501 // If this replaces anything in the current scope, 1502 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1503 IEnd = IdResolver.end(); 1504 for (; I != IEnd; ++I) { 1505 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1506 S->RemoveDecl(*I); 1507 IdResolver.RemoveDecl(*I); 1508 1509 // Should only need to replace one decl. 1510 break; 1511 } 1512 } 1513 1514 S->AddDecl(D); 1515 1516 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1517 // Implicitly-generated labels may end up getting generated in an order that 1518 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1519 // the label at the appropriate place in the identifier chain. 1520 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1521 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1522 if (IDC == CurContext) { 1523 if (!S->isDeclScope(*I)) 1524 continue; 1525 } else if (IDC->Encloses(CurContext)) 1526 break; 1527 } 1528 1529 IdResolver.InsertDeclAfter(I, D); 1530 } else { 1531 IdResolver.AddDecl(D); 1532 } 1533 warnOnReservedIdentifier(D); 1534 } 1535 1536 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1537 bool AllowInlineNamespace) { 1538 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1539 } 1540 1541 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1542 DeclContext *TargetDC = DC->getPrimaryContext(); 1543 do { 1544 if (DeclContext *ScopeDC = S->getEntity()) 1545 if (ScopeDC->getPrimaryContext() == TargetDC) 1546 return S; 1547 } while ((S = S->getParent())); 1548 1549 return nullptr; 1550 } 1551 1552 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1553 DeclContext*, 1554 ASTContext&); 1555 1556 /// Filters out lookup results that don't fall within the given scope 1557 /// as determined by isDeclInScope. 1558 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1559 bool ConsiderLinkage, 1560 bool AllowInlineNamespace) { 1561 LookupResult::Filter F = R.makeFilter(); 1562 while (F.hasNext()) { 1563 NamedDecl *D = F.next(); 1564 1565 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1566 continue; 1567 1568 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1569 continue; 1570 1571 F.erase(); 1572 } 1573 1574 F.done(); 1575 } 1576 1577 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1578 /// have compatible owning modules. 1579 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1580 // FIXME: The Modules TS is not clear about how friend declarations are 1581 // to be treated. It's not meaningful to have different owning modules for 1582 // linkage in redeclarations of the same entity, so for now allow the 1583 // redeclaration and change the owning modules to match. 1584 if (New->getFriendObjectKind() && 1585 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1586 New->setLocalOwningModule(Old->getOwningModule()); 1587 makeMergedDefinitionVisible(New); 1588 return false; 1589 } 1590 1591 Module *NewM = New->getOwningModule(); 1592 Module *OldM = Old->getOwningModule(); 1593 1594 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1595 NewM = NewM->Parent; 1596 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1597 OldM = OldM->Parent; 1598 1599 if (NewM == OldM) 1600 return false; 1601 1602 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1603 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1604 if (NewIsModuleInterface || OldIsModuleInterface) { 1605 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1606 // if a declaration of D [...] appears in the purview of a module, all 1607 // other such declarations shall appear in the purview of the same module 1608 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1609 << New 1610 << NewIsModuleInterface 1611 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1612 << OldIsModuleInterface 1613 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1614 Diag(Old->getLocation(), diag::note_previous_declaration); 1615 New->setInvalidDecl(); 1616 return true; 1617 } 1618 1619 return false; 1620 } 1621 1622 static bool isUsingDecl(NamedDecl *D) { 1623 return isa<UsingShadowDecl>(D) || 1624 isa<UnresolvedUsingTypenameDecl>(D) || 1625 isa<UnresolvedUsingValueDecl>(D); 1626 } 1627 1628 /// Removes using shadow declarations from the lookup results. 1629 static void RemoveUsingDecls(LookupResult &R) { 1630 LookupResult::Filter F = R.makeFilter(); 1631 while (F.hasNext()) 1632 if (isUsingDecl(F.next())) 1633 F.erase(); 1634 1635 F.done(); 1636 } 1637 1638 /// Check for this common pattern: 1639 /// @code 1640 /// class S { 1641 /// S(const S&); // DO NOT IMPLEMENT 1642 /// void operator=(const S&); // DO NOT IMPLEMENT 1643 /// }; 1644 /// @endcode 1645 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1646 // FIXME: Should check for private access too but access is set after we get 1647 // the decl here. 1648 if (D->doesThisDeclarationHaveABody()) 1649 return false; 1650 1651 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1652 return CD->isCopyConstructor(); 1653 return D->isCopyAssignmentOperator(); 1654 } 1655 1656 // We need this to handle 1657 // 1658 // typedef struct { 1659 // void *foo() { return 0; } 1660 // } A; 1661 // 1662 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1663 // for example. If 'A', foo will have external linkage. If we have '*A', 1664 // foo will have no linkage. Since we can't know until we get to the end 1665 // of the typedef, this function finds out if D might have non-external linkage. 1666 // Callers should verify at the end of the TU if it D has external linkage or 1667 // not. 1668 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1669 const DeclContext *DC = D->getDeclContext(); 1670 while (!DC->isTranslationUnit()) { 1671 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1672 if (!RD->hasNameForLinkage()) 1673 return true; 1674 } 1675 DC = DC->getParent(); 1676 } 1677 1678 return !D->isExternallyVisible(); 1679 } 1680 1681 // FIXME: This needs to be refactored; some other isInMainFile users want 1682 // these semantics. 1683 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1684 if (S.TUKind != TU_Complete) 1685 return false; 1686 return S.SourceMgr.isInMainFile(Loc); 1687 } 1688 1689 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1690 assert(D); 1691 1692 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1693 return false; 1694 1695 // Ignore all entities declared within templates, and out-of-line definitions 1696 // of members of class templates. 1697 if (D->getDeclContext()->isDependentContext() || 1698 D->getLexicalDeclContext()->isDependentContext()) 1699 return false; 1700 1701 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1702 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1703 return false; 1704 // A non-out-of-line declaration of a member specialization was implicitly 1705 // instantiated; it's the out-of-line declaration that we're interested in. 1706 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1707 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1708 return false; 1709 1710 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1711 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1712 return false; 1713 } else { 1714 // 'static inline' functions are defined in headers; don't warn. 1715 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1716 return false; 1717 } 1718 1719 if (FD->doesThisDeclarationHaveABody() && 1720 Context.DeclMustBeEmitted(FD)) 1721 return false; 1722 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1723 // Constants and utility variables are defined in headers with internal 1724 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1725 // like "inline".) 1726 if (!isMainFileLoc(*this, VD->getLocation())) 1727 return false; 1728 1729 if (Context.DeclMustBeEmitted(VD)) 1730 return false; 1731 1732 if (VD->isStaticDataMember() && 1733 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1734 return false; 1735 if (VD->isStaticDataMember() && 1736 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1737 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1738 return false; 1739 1740 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1741 return false; 1742 } else { 1743 return false; 1744 } 1745 1746 // Only warn for unused decls internal to the translation unit. 1747 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1748 // for inline functions defined in the main source file, for instance. 1749 return mightHaveNonExternalLinkage(D); 1750 } 1751 1752 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1753 if (!D) 1754 return; 1755 1756 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1757 const FunctionDecl *First = FD->getFirstDecl(); 1758 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1759 return; // First should already be in the vector. 1760 } 1761 1762 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1763 const VarDecl *First = VD->getFirstDecl(); 1764 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1765 return; // First should already be in the vector. 1766 } 1767 1768 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1769 UnusedFileScopedDecls.push_back(D); 1770 } 1771 1772 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1773 if (D->isInvalidDecl()) 1774 return false; 1775 1776 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1777 // For a decomposition declaration, warn if none of the bindings are 1778 // referenced, instead of if the variable itself is referenced (which 1779 // it is, by the bindings' expressions). 1780 for (auto *BD : DD->bindings()) 1781 if (BD->isReferenced()) 1782 return false; 1783 } else if (!D->getDeclName()) { 1784 return false; 1785 } else if (D->isReferenced() || D->isUsed()) { 1786 return false; 1787 } 1788 1789 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1790 return false; 1791 1792 if (isa<LabelDecl>(D)) 1793 return true; 1794 1795 // Except for labels, we only care about unused decls that are local to 1796 // functions. 1797 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1798 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1799 // For dependent types, the diagnostic is deferred. 1800 WithinFunction = 1801 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1802 if (!WithinFunction) 1803 return false; 1804 1805 if (isa<TypedefNameDecl>(D)) 1806 return true; 1807 1808 // White-list anything that isn't a local variable. 1809 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1810 return false; 1811 1812 // Types of valid local variables should be complete, so this should succeed. 1813 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1814 1815 // White-list anything with an __attribute__((unused)) type. 1816 const auto *Ty = VD->getType().getTypePtr(); 1817 1818 // Only look at the outermost level of typedef. 1819 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1820 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1821 return false; 1822 } 1823 1824 // If we failed to complete the type for some reason, or if the type is 1825 // dependent, don't diagnose the variable. 1826 if (Ty->isIncompleteType() || Ty->isDependentType()) 1827 return false; 1828 1829 // Look at the element type to ensure that the warning behaviour is 1830 // consistent for both scalars and arrays. 1831 Ty = Ty->getBaseElementTypeUnsafe(); 1832 1833 if (const TagType *TT = Ty->getAs<TagType>()) { 1834 const TagDecl *Tag = TT->getDecl(); 1835 if (Tag->hasAttr<UnusedAttr>()) 1836 return false; 1837 1838 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1839 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1840 return false; 1841 1842 if (const Expr *Init = VD->getInit()) { 1843 if (const ExprWithCleanups *Cleanups = 1844 dyn_cast<ExprWithCleanups>(Init)) 1845 Init = Cleanups->getSubExpr(); 1846 const CXXConstructExpr *Construct = 1847 dyn_cast<CXXConstructExpr>(Init); 1848 if (Construct && !Construct->isElidable()) { 1849 CXXConstructorDecl *CD = Construct->getConstructor(); 1850 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1851 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1852 return false; 1853 } 1854 1855 // Suppress the warning if we don't know how this is constructed, and 1856 // it could possibly be non-trivial constructor. 1857 if (Init->isTypeDependent()) 1858 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1859 if (!Ctor->isTrivial()) 1860 return false; 1861 } 1862 } 1863 } 1864 1865 // TODO: __attribute__((unused)) templates? 1866 } 1867 1868 return true; 1869 } 1870 1871 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1872 FixItHint &Hint) { 1873 if (isa<LabelDecl>(D)) { 1874 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1875 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1876 true); 1877 if (AfterColon.isInvalid()) 1878 return; 1879 Hint = FixItHint::CreateRemoval( 1880 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1881 } 1882 } 1883 1884 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1885 if (D->getTypeForDecl()->isDependentType()) 1886 return; 1887 1888 for (auto *TmpD : D->decls()) { 1889 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1890 DiagnoseUnusedDecl(T); 1891 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1892 DiagnoseUnusedNestedTypedefs(R); 1893 } 1894 } 1895 1896 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1897 /// unless they are marked attr(unused). 1898 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1899 if (!ShouldDiagnoseUnusedDecl(D)) 1900 return; 1901 1902 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1903 // typedefs can be referenced later on, so the diagnostics are emitted 1904 // at end-of-translation-unit. 1905 UnusedLocalTypedefNameCandidates.insert(TD); 1906 return; 1907 } 1908 1909 FixItHint Hint; 1910 GenerateFixForUnusedDecl(D, Context, Hint); 1911 1912 unsigned DiagID; 1913 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1914 DiagID = diag::warn_unused_exception_param; 1915 else if (isa<LabelDecl>(D)) 1916 DiagID = diag::warn_unused_label; 1917 else 1918 DiagID = diag::warn_unused_variable; 1919 1920 Diag(D->getLocation(), DiagID) << D << Hint; 1921 } 1922 1923 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 1924 // If it's not referenced, it can't be set. 1925 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>()) 1926 return; 1927 1928 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 1929 1930 if (Ty->isReferenceType() || Ty->isDependentType()) 1931 return; 1932 1933 if (const TagType *TT = Ty->getAs<TagType>()) { 1934 const TagDecl *Tag = TT->getDecl(); 1935 if (Tag->hasAttr<UnusedAttr>()) 1936 return; 1937 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 1938 // mimic gcc's behavior. 1939 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1940 if (!RD->hasAttr<WarnUnusedAttr>()) 1941 return; 1942 } 1943 } 1944 1945 auto iter = RefsMinusAssignments.find(VD); 1946 if (iter == RefsMinusAssignments.end()) 1947 return; 1948 1949 assert(iter->getSecond() >= 0 && 1950 "Found a negative number of references to a VarDecl"); 1951 if (iter->getSecond() != 0) 1952 return; 1953 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 1954 : diag::warn_unused_but_set_variable; 1955 Diag(VD->getLocation(), DiagID) << VD; 1956 } 1957 1958 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1959 // Verify that we have no forward references left. If so, there was a goto 1960 // or address of a label taken, but no definition of it. Label fwd 1961 // definitions are indicated with a null substmt which is also not a resolved 1962 // MS inline assembly label name. 1963 bool Diagnose = false; 1964 if (L->isMSAsmLabel()) 1965 Diagnose = !L->isResolvedMSAsmLabel(); 1966 else 1967 Diagnose = L->getStmt() == nullptr; 1968 if (Diagnose) 1969 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1970 } 1971 1972 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1973 S->mergeNRVOIntoParent(); 1974 1975 if (S->decl_empty()) return; 1976 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1977 "Scope shouldn't contain decls!"); 1978 1979 for (auto *TmpD : S->decls()) { 1980 assert(TmpD && "This decl didn't get pushed??"); 1981 1982 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1983 NamedDecl *D = cast<NamedDecl>(TmpD); 1984 1985 // Diagnose unused variables in this scope. 1986 if (!S->hasUnrecoverableErrorOccurred()) { 1987 DiagnoseUnusedDecl(D); 1988 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1989 DiagnoseUnusedNestedTypedefs(RD); 1990 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1991 DiagnoseUnusedButSetDecl(VD); 1992 RefsMinusAssignments.erase(VD); 1993 } 1994 } 1995 1996 if (!D->getDeclName()) continue; 1997 1998 // If this was a forward reference to a label, verify it was defined. 1999 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2000 CheckPoppedLabel(LD, *this); 2001 2002 // Remove this name from our lexical scope, and warn on it if we haven't 2003 // already. 2004 IdResolver.RemoveDecl(D); 2005 auto ShadowI = ShadowingDecls.find(D); 2006 if (ShadowI != ShadowingDecls.end()) { 2007 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2008 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2009 << D << FD << FD->getParent(); 2010 Diag(FD->getLocation(), diag::note_previous_declaration); 2011 } 2012 ShadowingDecls.erase(ShadowI); 2013 } 2014 } 2015 } 2016 2017 /// Look for an Objective-C class in the translation unit. 2018 /// 2019 /// \param Id The name of the Objective-C class we're looking for. If 2020 /// typo-correction fixes this name, the Id will be updated 2021 /// to the fixed name. 2022 /// 2023 /// \param IdLoc The location of the name in the translation unit. 2024 /// 2025 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2026 /// if there is no class with the given name. 2027 /// 2028 /// \returns The declaration of the named Objective-C class, or NULL if the 2029 /// class could not be found. 2030 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2031 SourceLocation IdLoc, 2032 bool DoTypoCorrection) { 2033 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2034 // creation from this context. 2035 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2036 2037 if (!IDecl && DoTypoCorrection) { 2038 // Perform typo correction at the given location, but only if we 2039 // find an Objective-C class name. 2040 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2041 if (TypoCorrection C = 2042 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2043 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2044 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2045 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2046 Id = IDecl->getIdentifier(); 2047 } 2048 } 2049 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2050 // This routine must always return a class definition, if any. 2051 if (Def && Def->getDefinition()) 2052 Def = Def->getDefinition(); 2053 return Def; 2054 } 2055 2056 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2057 /// from S, where a non-field would be declared. This routine copes 2058 /// with the difference between C and C++ scoping rules in structs and 2059 /// unions. For example, the following code is well-formed in C but 2060 /// ill-formed in C++: 2061 /// @code 2062 /// struct S6 { 2063 /// enum { BAR } e; 2064 /// }; 2065 /// 2066 /// void test_S6() { 2067 /// struct S6 a; 2068 /// a.e = BAR; 2069 /// } 2070 /// @endcode 2071 /// For the declaration of BAR, this routine will return a different 2072 /// scope. The scope S will be the scope of the unnamed enumeration 2073 /// within S6. In C++, this routine will return the scope associated 2074 /// with S6, because the enumeration's scope is a transparent 2075 /// context but structures can contain non-field names. In C, this 2076 /// routine will return the translation unit scope, since the 2077 /// enumeration's scope is a transparent context and structures cannot 2078 /// contain non-field names. 2079 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2080 while (((S->getFlags() & Scope::DeclScope) == 0) || 2081 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2082 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2083 S = S->getParent(); 2084 return S; 2085 } 2086 2087 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2088 ASTContext::GetBuiltinTypeError Error) { 2089 switch (Error) { 2090 case ASTContext::GE_None: 2091 return ""; 2092 case ASTContext::GE_Missing_type: 2093 return BuiltinInfo.getHeaderName(ID); 2094 case ASTContext::GE_Missing_stdio: 2095 return "stdio.h"; 2096 case ASTContext::GE_Missing_setjmp: 2097 return "setjmp.h"; 2098 case ASTContext::GE_Missing_ucontext: 2099 return "ucontext.h"; 2100 } 2101 llvm_unreachable("unhandled error kind"); 2102 } 2103 2104 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2105 unsigned ID, SourceLocation Loc) { 2106 DeclContext *Parent = Context.getTranslationUnitDecl(); 2107 2108 if (getLangOpts().CPlusPlus) { 2109 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2110 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2111 CLinkageDecl->setImplicit(); 2112 Parent->addDecl(CLinkageDecl); 2113 Parent = CLinkageDecl; 2114 } 2115 2116 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2117 /*TInfo=*/nullptr, SC_Extern, 2118 getCurFPFeatures().isFPConstrained(), 2119 false, Type->isFunctionProtoType()); 2120 New->setImplicit(); 2121 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2122 2123 // Create Decl objects for each parameter, adding them to the 2124 // FunctionDecl. 2125 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2126 SmallVector<ParmVarDecl *, 16> Params; 2127 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2128 ParmVarDecl *parm = ParmVarDecl::Create( 2129 Context, New, SourceLocation(), SourceLocation(), nullptr, 2130 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2131 parm->setScopeInfo(0, i); 2132 Params.push_back(parm); 2133 } 2134 New->setParams(Params); 2135 } 2136 2137 AddKnownFunctionAttributes(New); 2138 return New; 2139 } 2140 2141 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2142 /// file scope. lazily create a decl for it. ForRedeclaration is true 2143 /// if we're creating this built-in in anticipation of redeclaring the 2144 /// built-in. 2145 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2146 Scope *S, bool ForRedeclaration, 2147 SourceLocation Loc) { 2148 LookupNecessaryTypesForBuiltin(S, ID); 2149 2150 ASTContext::GetBuiltinTypeError Error; 2151 QualType R = Context.GetBuiltinType(ID, Error); 2152 if (Error) { 2153 if (!ForRedeclaration) 2154 return nullptr; 2155 2156 // If we have a builtin without an associated type we should not emit a 2157 // warning when we were not able to find a type for it. 2158 if (Error == ASTContext::GE_Missing_type || 2159 Context.BuiltinInfo.allowTypeMismatch(ID)) 2160 return nullptr; 2161 2162 // If we could not find a type for setjmp it is because the jmp_buf type was 2163 // not defined prior to the setjmp declaration. 2164 if (Error == ASTContext::GE_Missing_setjmp) { 2165 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2166 << Context.BuiltinInfo.getName(ID); 2167 return nullptr; 2168 } 2169 2170 // Generally, we emit a warning that the declaration requires the 2171 // appropriate header. 2172 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2173 << getHeaderName(Context.BuiltinInfo, ID, Error) 2174 << Context.BuiltinInfo.getName(ID); 2175 return nullptr; 2176 } 2177 2178 if (!ForRedeclaration && 2179 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2180 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2181 Diag(Loc, diag::ext_implicit_lib_function_decl) 2182 << Context.BuiltinInfo.getName(ID) << R; 2183 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2184 Diag(Loc, diag::note_include_header_or_declare) 2185 << Header << Context.BuiltinInfo.getName(ID); 2186 } 2187 2188 if (R.isNull()) 2189 return nullptr; 2190 2191 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2192 RegisterLocallyScopedExternCDecl(New, S); 2193 2194 // TUScope is the translation-unit scope to insert this function into. 2195 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2196 // relate Scopes to DeclContexts, and probably eliminate CurContext 2197 // entirely, but we're not there yet. 2198 DeclContext *SavedContext = CurContext; 2199 CurContext = New->getDeclContext(); 2200 PushOnScopeChains(New, TUScope); 2201 CurContext = SavedContext; 2202 return New; 2203 } 2204 2205 /// Typedef declarations don't have linkage, but they still denote the same 2206 /// entity if their types are the same. 2207 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2208 /// isSameEntity. 2209 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2210 TypedefNameDecl *Decl, 2211 LookupResult &Previous) { 2212 // This is only interesting when modules are enabled. 2213 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2214 return; 2215 2216 // Empty sets are uninteresting. 2217 if (Previous.empty()) 2218 return; 2219 2220 LookupResult::Filter Filter = Previous.makeFilter(); 2221 while (Filter.hasNext()) { 2222 NamedDecl *Old = Filter.next(); 2223 2224 // Non-hidden declarations are never ignored. 2225 if (S.isVisible(Old)) 2226 continue; 2227 2228 // Declarations of the same entity are not ignored, even if they have 2229 // different linkages. 2230 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2231 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2232 Decl->getUnderlyingType())) 2233 continue; 2234 2235 // If both declarations give a tag declaration a typedef name for linkage 2236 // purposes, then they declare the same entity. 2237 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2238 Decl->getAnonDeclWithTypedefName()) 2239 continue; 2240 } 2241 2242 Filter.erase(); 2243 } 2244 2245 Filter.done(); 2246 } 2247 2248 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2249 QualType OldType; 2250 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2251 OldType = OldTypedef->getUnderlyingType(); 2252 else 2253 OldType = Context.getTypeDeclType(Old); 2254 QualType NewType = New->getUnderlyingType(); 2255 2256 if (NewType->isVariablyModifiedType()) { 2257 // Must not redefine a typedef with a variably-modified type. 2258 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2259 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2260 << Kind << NewType; 2261 if (Old->getLocation().isValid()) 2262 notePreviousDefinition(Old, New->getLocation()); 2263 New->setInvalidDecl(); 2264 return true; 2265 } 2266 2267 if (OldType != NewType && 2268 !OldType->isDependentType() && 2269 !NewType->isDependentType() && 2270 !Context.hasSameType(OldType, NewType)) { 2271 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2272 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2273 << Kind << NewType << OldType; 2274 if (Old->getLocation().isValid()) 2275 notePreviousDefinition(Old, New->getLocation()); 2276 New->setInvalidDecl(); 2277 return true; 2278 } 2279 return false; 2280 } 2281 2282 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2283 /// same name and scope as a previous declaration 'Old'. Figure out 2284 /// how to resolve this situation, merging decls or emitting 2285 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2286 /// 2287 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2288 LookupResult &OldDecls) { 2289 // If the new decl is known invalid already, don't bother doing any 2290 // merging checks. 2291 if (New->isInvalidDecl()) return; 2292 2293 // Allow multiple definitions for ObjC built-in typedefs. 2294 // FIXME: Verify the underlying types are equivalent! 2295 if (getLangOpts().ObjC) { 2296 const IdentifierInfo *TypeID = New->getIdentifier(); 2297 switch (TypeID->getLength()) { 2298 default: break; 2299 case 2: 2300 { 2301 if (!TypeID->isStr("id")) 2302 break; 2303 QualType T = New->getUnderlyingType(); 2304 if (!T->isPointerType()) 2305 break; 2306 if (!T->isVoidPointerType()) { 2307 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2308 if (!PT->isStructureType()) 2309 break; 2310 } 2311 Context.setObjCIdRedefinitionType(T); 2312 // Install the built-in type for 'id', ignoring the current definition. 2313 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2314 return; 2315 } 2316 case 5: 2317 if (!TypeID->isStr("Class")) 2318 break; 2319 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2320 // Install the built-in type for 'Class', ignoring the current definition. 2321 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2322 return; 2323 case 3: 2324 if (!TypeID->isStr("SEL")) 2325 break; 2326 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2327 // Install the built-in type for 'SEL', ignoring the current definition. 2328 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2329 return; 2330 } 2331 // Fall through - the typedef name was not a builtin type. 2332 } 2333 2334 // Verify the old decl was also a type. 2335 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2336 if (!Old) { 2337 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2338 << New->getDeclName(); 2339 2340 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2341 if (OldD->getLocation().isValid()) 2342 notePreviousDefinition(OldD, New->getLocation()); 2343 2344 return New->setInvalidDecl(); 2345 } 2346 2347 // If the old declaration is invalid, just give up here. 2348 if (Old->isInvalidDecl()) 2349 return New->setInvalidDecl(); 2350 2351 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2352 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2353 auto *NewTag = New->getAnonDeclWithTypedefName(); 2354 NamedDecl *Hidden = nullptr; 2355 if (OldTag && NewTag && 2356 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2357 !hasVisibleDefinition(OldTag, &Hidden)) { 2358 // There is a definition of this tag, but it is not visible. Use it 2359 // instead of our tag. 2360 New->setTypeForDecl(OldTD->getTypeForDecl()); 2361 if (OldTD->isModed()) 2362 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2363 OldTD->getUnderlyingType()); 2364 else 2365 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2366 2367 // Make the old tag definition visible. 2368 makeMergedDefinitionVisible(Hidden); 2369 2370 // If this was an unscoped enumeration, yank all of its enumerators 2371 // out of the scope. 2372 if (isa<EnumDecl>(NewTag)) { 2373 Scope *EnumScope = getNonFieldDeclScope(S); 2374 for (auto *D : NewTag->decls()) { 2375 auto *ED = cast<EnumConstantDecl>(D); 2376 assert(EnumScope->isDeclScope(ED)); 2377 EnumScope->RemoveDecl(ED); 2378 IdResolver.RemoveDecl(ED); 2379 ED->getLexicalDeclContext()->removeDecl(ED); 2380 } 2381 } 2382 } 2383 } 2384 2385 // If the typedef types are not identical, reject them in all languages and 2386 // with any extensions enabled. 2387 if (isIncompatibleTypedef(Old, New)) 2388 return; 2389 2390 // The types match. Link up the redeclaration chain and merge attributes if 2391 // the old declaration was a typedef. 2392 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2393 New->setPreviousDecl(Typedef); 2394 mergeDeclAttributes(New, Old); 2395 } 2396 2397 if (getLangOpts().MicrosoftExt) 2398 return; 2399 2400 if (getLangOpts().CPlusPlus) { 2401 // C++ [dcl.typedef]p2: 2402 // In a given non-class scope, a typedef specifier can be used to 2403 // redefine the name of any type declared in that scope to refer 2404 // to the type to which it already refers. 2405 if (!isa<CXXRecordDecl>(CurContext)) 2406 return; 2407 2408 // C++0x [dcl.typedef]p4: 2409 // In a given class scope, a typedef specifier can be used to redefine 2410 // any class-name declared in that scope that is not also a typedef-name 2411 // to refer to the type to which it already refers. 2412 // 2413 // This wording came in via DR424, which was a correction to the 2414 // wording in DR56, which accidentally banned code like: 2415 // 2416 // struct S { 2417 // typedef struct A { } A; 2418 // }; 2419 // 2420 // in the C++03 standard. We implement the C++0x semantics, which 2421 // allow the above but disallow 2422 // 2423 // struct S { 2424 // typedef int I; 2425 // typedef int I; 2426 // }; 2427 // 2428 // since that was the intent of DR56. 2429 if (!isa<TypedefNameDecl>(Old)) 2430 return; 2431 2432 Diag(New->getLocation(), diag::err_redefinition) 2433 << New->getDeclName(); 2434 notePreviousDefinition(Old, New->getLocation()); 2435 return New->setInvalidDecl(); 2436 } 2437 2438 // Modules always permit redefinition of typedefs, as does C11. 2439 if (getLangOpts().Modules || getLangOpts().C11) 2440 return; 2441 2442 // If we have a redefinition of a typedef in C, emit a warning. This warning 2443 // is normally mapped to an error, but can be controlled with 2444 // -Wtypedef-redefinition. If either the original or the redefinition is 2445 // in a system header, don't emit this for compatibility with GCC. 2446 if (getDiagnostics().getSuppressSystemWarnings() && 2447 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2448 (Old->isImplicit() || 2449 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2450 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2451 return; 2452 2453 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2454 << New->getDeclName(); 2455 notePreviousDefinition(Old, New->getLocation()); 2456 } 2457 2458 /// DeclhasAttr - returns true if decl Declaration already has the target 2459 /// attribute. 2460 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2461 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2462 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2463 for (const auto *i : D->attrs()) 2464 if (i->getKind() == A->getKind()) { 2465 if (Ann) { 2466 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2467 return true; 2468 continue; 2469 } 2470 // FIXME: Don't hardcode this check 2471 if (OA && isa<OwnershipAttr>(i)) 2472 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2473 return true; 2474 } 2475 2476 return false; 2477 } 2478 2479 static bool isAttributeTargetADefinition(Decl *D) { 2480 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2481 return VD->isThisDeclarationADefinition(); 2482 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2483 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2484 return true; 2485 } 2486 2487 /// Merge alignment attributes from \p Old to \p New, taking into account the 2488 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2489 /// 2490 /// \return \c true if any attributes were added to \p New. 2491 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2492 // Look for alignas attributes on Old, and pick out whichever attribute 2493 // specifies the strictest alignment requirement. 2494 AlignedAttr *OldAlignasAttr = nullptr; 2495 AlignedAttr *OldStrictestAlignAttr = nullptr; 2496 unsigned OldAlign = 0; 2497 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2498 // FIXME: We have no way of representing inherited dependent alignments 2499 // in a case like: 2500 // template<int A, int B> struct alignas(A) X; 2501 // template<int A, int B> struct alignas(B) X {}; 2502 // For now, we just ignore any alignas attributes which are not on the 2503 // definition in such a case. 2504 if (I->isAlignmentDependent()) 2505 return false; 2506 2507 if (I->isAlignas()) 2508 OldAlignasAttr = I; 2509 2510 unsigned Align = I->getAlignment(S.Context); 2511 if (Align > OldAlign) { 2512 OldAlign = Align; 2513 OldStrictestAlignAttr = I; 2514 } 2515 } 2516 2517 // Look for alignas attributes on New. 2518 AlignedAttr *NewAlignasAttr = nullptr; 2519 unsigned NewAlign = 0; 2520 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2521 if (I->isAlignmentDependent()) 2522 return false; 2523 2524 if (I->isAlignas()) 2525 NewAlignasAttr = I; 2526 2527 unsigned Align = I->getAlignment(S.Context); 2528 if (Align > NewAlign) 2529 NewAlign = Align; 2530 } 2531 2532 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2533 // Both declarations have 'alignas' attributes. We require them to match. 2534 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2535 // fall short. (If two declarations both have alignas, they must both match 2536 // every definition, and so must match each other if there is a definition.) 2537 2538 // If either declaration only contains 'alignas(0)' specifiers, then it 2539 // specifies the natural alignment for the type. 2540 if (OldAlign == 0 || NewAlign == 0) { 2541 QualType Ty; 2542 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2543 Ty = VD->getType(); 2544 else 2545 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2546 2547 if (OldAlign == 0) 2548 OldAlign = S.Context.getTypeAlign(Ty); 2549 if (NewAlign == 0) 2550 NewAlign = S.Context.getTypeAlign(Ty); 2551 } 2552 2553 if (OldAlign != NewAlign) { 2554 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2555 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2556 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2557 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2558 } 2559 } 2560 2561 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2562 // C++11 [dcl.align]p6: 2563 // if any declaration of an entity has an alignment-specifier, 2564 // every defining declaration of that entity shall specify an 2565 // equivalent alignment. 2566 // C11 6.7.5/7: 2567 // If the definition of an object does not have an alignment 2568 // specifier, any other declaration of that object shall also 2569 // have no alignment specifier. 2570 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2571 << OldAlignasAttr; 2572 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2573 << OldAlignasAttr; 2574 } 2575 2576 bool AnyAdded = false; 2577 2578 // Ensure we have an attribute representing the strictest alignment. 2579 if (OldAlign > NewAlign) { 2580 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2581 Clone->setInherited(true); 2582 New->addAttr(Clone); 2583 AnyAdded = true; 2584 } 2585 2586 // Ensure we have an alignas attribute if the old declaration had one. 2587 if (OldAlignasAttr && !NewAlignasAttr && 2588 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2589 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2590 Clone->setInherited(true); 2591 New->addAttr(Clone); 2592 AnyAdded = true; 2593 } 2594 2595 return AnyAdded; 2596 } 2597 2598 #define WANT_DECL_MERGE_LOGIC 2599 #include "clang/Sema/AttrParsedAttrImpl.inc" 2600 #undef WANT_DECL_MERGE_LOGIC 2601 2602 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2603 const InheritableAttr *Attr, 2604 Sema::AvailabilityMergeKind AMK) { 2605 // Diagnose any mutual exclusions between the attribute that we want to add 2606 // and attributes that already exist on the declaration. 2607 if (!DiagnoseMutualExclusions(S, D, Attr)) 2608 return false; 2609 2610 // This function copies an attribute Attr from a previous declaration to the 2611 // new declaration D if the new declaration doesn't itself have that attribute 2612 // yet or if that attribute allows duplicates. 2613 // If you're adding a new attribute that requires logic different from 2614 // "use explicit attribute on decl if present, else use attribute from 2615 // previous decl", for example if the attribute needs to be consistent 2616 // between redeclarations, you need to call a custom merge function here. 2617 InheritableAttr *NewAttr = nullptr; 2618 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2619 NewAttr = S.mergeAvailabilityAttr( 2620 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2621 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2622 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2623 AA->getPriority()); 2624 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2625 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2626 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2627 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2628 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2629 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2630 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2631 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2632 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2633 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2634 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2635 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2636 FA->getFirstArg()); 2637 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2638 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2639 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2640 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2641 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2642 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2643 IA->getInheritanceModel()); 2644 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2645 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2646 &S.Context.Idents.get(AA->getSpelling())); 2647 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2648 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2649 isa<CUDAGlobalAttr>(Attr))) { 2650 // CUDA target attributes are part of function signature for 2651 // overloading purposes and must not be merged. 2652 return false; 2653 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2654 NewAttr = S.mergeMinSizeAttr(D, *MA); 2655 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2656 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2657 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2658 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2659 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2660 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2661 else if (isa<AlignedAttr>(Attr)) 2662 // AlignedAttrs are handled separately, because we need to handle all 2663 // such attributes on a declaration at the same time. 2664 NewAttr = nullptr; 2665 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2666 (AMK == Sema::AMK_Override || 2667 AMK == Sema::AMK_ProtocolImplementation || 2668 AMK == Sema::AMK_OptionalProtocolImplementation)) 2669 NewAttr = nullptr; 2670 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2671 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2672 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2673 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2674 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2675 NewAttr = S.mergeImportNameAttr(D, *INA); 2676 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2677 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2678 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2679 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2680 else if (const auto *BTFA = dyn_cast<BTFTagAttr>(Attr)) 2681 NewAttr = S.mergeBTFTagAttr(D, *BTFA); 2682 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2683 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2684 2685 if (NewAttr) { 2686 NewAttr->setInherited(true); 2687 D->addAttr(NewAttr); 2688 if (isa<MSInheritanceAttr>(NewAttr)) 2689 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2690 return true; 2691 } 2692 2693 return false; 2694 } 2695 2696 static const NamedDecl *getDefinition(const Decl *D) { 2697 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2698 return TD->getDefinition(); 2699 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2700 const VarDecl *Def = VD->getDefinition(); 2701 if (Def) 2702 return Def; 2703 return VD->getActingDefinition(); 2704 } 2705 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2706 const FunctionDecl *Def = nullptr; 2707 if (FD->isDefined(Def, true)) 2708 return Def; 2709 } 2710 return nullptr; 2711 } 2712 2713 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2714 for (const auto *Attribute : D->attrs()) 2715 if (Attribute->getKind() == Kind) 2716 return true; 2717 return false; 2718 } 2719 2720 /// checkNewAttributesAfterDef - If we already have a definition, check that 2721 /// there are no new attributes in this declaration. 2722 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2723 if (!New->hasAttrs()) 2724 return; 2725 2726 const NamedDecl *Def = getDefinition(Old); 2727 if (!Def || Def == New) 2728 return; 2729 2730 AttrVec &NewAttributes = New->getAttrs(); 2731 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2732 const Attr *NewAttribute = NewAttributes[I]; 2733 2734 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2735 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2736 Sema::SkipBodyInfo SkipBody; 2737 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2738 2739 // If we're skipping this definition, drop the "alias" attribute. 2740 if (SkipBody.ShouldSkip) { 2741 NewAttributes.erase(NewAttributes.begin() + I); 2742 --E; 2743 continue; 2744 } 2745 } else { 2746 VarDecl *VD = cast<VarDecl>(New); 2747 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2748 VarDecl::TentativeDefinition 2749 ? diag::err_alias_after_tentative 2750 : diag::err_redefinition; 2751 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2752 if (Diag == diag::err_redefinition) 2753 S.notePreviousDefinition(Def, VD->getLocation()); 2754 else 2755 S.Diag(Def->getLocation(), diag::note_previous_definition); 2756 VD->setInvalidDecl(); 2757 } 2758 ++I; 2759 continue; 2760 } 2761 2762 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2763 // Tentative definitions are only interesting for the alias check above. 2764 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2765 ++I; 2766 continue; 2767 } 2768 } 2769 2770 if (hasAttribute(Def, NewAttribute->getKind())) { 2771 ++I; 2772 continue; // regular attr merging will take care of validating this. 2773 } 2774 2775 if (isa<C11NoReturnAttr>(NewAttribute)) { 2776 // C's _Noreturn is allowed to be added to a function after it is defined. 2777 ++I; 2778 continue; 2779 } else if (isa<UuidAttr>(NewAttribute)) { 2780 // msvc will allow a subsequent definition to add an uuid to a class 2781 ++I; 2782 continue; 2783 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2784 if (AA->isAlignas()) { 2785 // C++11 [dcl.align]p6: 2786 // if any declaration of an entity has an alignment-specifier, 2787 // every defining declaration of that entity shall specify an 2788 // equivalent alignment. 2789 // C11 6.7.5/7: 2790 // If the definition of an object does not have an alignment 2791 // specifier, any other declaration of that object shall also 2792 // have no alignment specifier. 2793 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2794 << AA; 2795 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2796 << AA; 2797 NewAttributes.erase(NewAttributes.begin() + I); 2798 --E; 2799 continue; 2800 } 2801 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2802 // If there is a C definition followed by a redeclaration with this 2803 // attribute then there are two different definitions. In C++, prefer the 2804 // standard diagnostics. 2805 if (!S.getLangOpts().CPlusPlus) { 2806 S.Diag(NewAttribute->getLocation(), 2807 diag::err_loader_uninitialized_redeclaration); 2808 S.Diag(Def->getLocation(), diag::note_previous_definition); 2809 NewAttributes.erase(NewAttributes.begin() + I); 2810 --E; 2811 continue; 2812 } 2813 } else if (isa<SelectAnyAttr>(NewAttribute) && 2814 cast<VarDecl>(New)->isInline() && 2815 !cast<VarDecl>(New)->isInlineSpecified()) { 2816 // Don't warn about applying selectany to implicitly inline variables. 2817 // Older compilers and language modes would require the use of selectany 2818 // to make such variables inline, and it would have no effect if we 2819 // honored it. 2820 ++I; 2821 continue; 2822 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2823 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2824 // declarations after defintions. 2825 ++I; 2826 continue; 2827 } 2828 2829 S.Diag(NewAttribute->getLocation(), 2830 diag::warn_attribute_precede_definition); 2831 S.Diag(Def->getLocation(), diag::note_previous_definition); 2832 NewAttributes.erase(NewAttributes.begin() + I); 2833 --E; 2834 } 2835 } 2836 2837 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2838 const ConstInitAttr *CIAttr, 2839 bool AttrBeforeInit) { 2840 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2841 2842 // Figure out a good way to write this specifier on the old declaration. 2843 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2844 // enough of the attribute list spelling information to extract that without 2845 // heroics. 2846 std::string SuitableSpelling; 2847 if (S.getLangOpts().CPlusPlus20) 2848 SuitableSpelling = std::string( 2849 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2850 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2851 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2852 InsertLoc, {tok::l_square, tok::l_square, 2853 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2854 S.PP.getIdentifierInfo("require_constant_initialization"), 2855 tok::r_square, tok::r_square})); 2856 if (SuitableSpelling.empty()) 2857 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2858 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2859 S.PP.getIdentifierInfo("require_constant_initialization"), 2860 tok::r_paren, tok::r_paren})); 2861 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2862 SuitableSpelling = "constinit"; 2863 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2864 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2865 if (SuitableSpelling.empty()) 2866 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2867 SuitableSpelling += " "; 2868 2869 if (AttrBeforeInit) { 2870 // extern constinit int a; 2871 // int a = 0; // error (missing 'constinit'), accepted as extension 2872 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2873 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2874 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2875 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2876 } else { 2877 // int a = 0; 2878 // constinit extern int a; // error (missing 'constinit') 2879 S.Diag(CIAttr->getLocation(), 2880 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2881 : diag::warn_require_const_init_added_too_late) 2882 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2883 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2884 << CIAttr->isConstinit() 2885 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2886 } 2887 } 2888 2889 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2890 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2891 AvailabilityMergeKind AMK) { 2892 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2893 UsedAttr *NewAttr = OldAttr->clone(Context); 2894 NewAttr->setInherited(true); 2895 New->addAttr(NewAttr); 2896 } 2897 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2898 RetainAttr *NewAttr = OldAttr->clone(Context); 2899 NewAttr->setInherited(true); 2900 New->addAttr(NewAttr); 2901 } 2902 2903 if (!Old->hasAttrs() && !New->hasAttrs()) 2904 return; 2905 2906 // [dcl.constinit]p1: 2907 // If the [constinit] specifier is applied to any declaration of a 2908 // variable, it shall be applied to the initializing declaration. 2909 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2910 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2911 if (bool(OldConstInit) != bool(NewConstInit)) { 2912 const auto *OldVD = cast<VarDecl>(Old); 2913 auto *NewVD = cast<VarDecl>(New); 2914 2915 // Find the initializing declaration. Note that we might not have linked 2916 // the new declaration into the redeclaration chain yet. 2917 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2918 if (!InitDecl && 2919 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2920 InitDecl = NewVD; 2921 2922 if (InitDecl == NewVD) { 2923 // This is the initializing declaration. If it would inherit 'constinit', 2924 // that's ill-formed. (Note that we do not apply this to the attribute 2925 // form). 2926 if (OldConstInit && OldConstInit->isConstinit()) 2927 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2928 /*AttrBeforeInit=*/true); 2929 } else if (NewConstInit) { 2930 // This is the first time we've been told that this declaration should 2931 // have a constant initializer. If we already saw the initializing 2932 // declaration, this is too late. 2933 if (InitDecl && InitDecl != NewVD) { 2934 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2935 /*AttrBeforeInit=*/false); 2936 NewVD->dropAttr<ConstInitAttr>(); 2937 } 2938 } 2939 } 2940 2941 // Attributes declared post-definition are currently ignored. 2942 checkNewAttributesAfterDef(*this, New, Old); 2943 2944 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2945 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2946 if (!OldA->isEquivalent(NewA)) { 2947 // This redeclaration changes __asm__ label. 2948 Diag(New->getLocation(), diag::err_different_asm_label); 2949 Diag(OldA->getLocation(), diag::note_previous_declaration); 2950 } 2951 } else if (Old->isUsed()) { 2952 // This redeclaration adds an __asm__ label to a declaration that has 2953 // already been ODR-used. 2954 Diag(New->getLocation(), diag::err_late_asm_label_name) 2955 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2956 } 2957 } 2958 2959 // Re-declaration cannot add abi_tag's. 2960 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2961 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2962 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2963 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2964 NewTag) == OldAbiTagAttr->tags_end()) { 2965 Diag(NewAbiTagAttr->getLocation(), 2966 diag::err_new_abi_tag_on_redeclaration) 2967 << NewTag; 2968 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2969 } 2970 } 2971 } else { 2972 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2973 Diag(Old->getLocation(), diag::note_previous_declaration); 2974 } 2975 } 2976 2977 // This redeclaration adds a section attribute. 2978 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2979 if (auto *VD = dyn_cast<VarDecl>(New)) { 2980 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2981 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2982 Diag(Old->getLocation(), diag::note_previous_declaration); 2983 } 2984 } 2985 } 2986 2987 // Redeclaration adds code-seg attribute. 2988 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2989 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2990 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2991 Diag(New->getLocation(), diag::warn_mismatched_section) 2992 << 0 /*codeseg*/; 2993 Diag(Old->getLocation(), diag::note_previous_declaration); 2994 } 2995 2996 if (!Old->hasAttrs()) 2997 return; 2998 2999 bool foundAny = New->hasAttrs(); 3000 3001 // Ensure that any moving of objects within the allocated map is done before 3002 // we process them. 3003 if (!foundAny) New->setAttrs(AttrVec()); 3004 3005 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3006 // Ignore deprecated/unavailable/availability attributes if requested. 3007 AvailabilityMergeKind LocalAMK = AMK_None; 3008 if (isa<DeprecatedAttr>(I) || 3009 isa<UnavailableAttr>(I) || 3010 isa<AvailabilityAttr>(I)) { 3011 switch (AMK) { 3012 case AMK_None: 3013 continue; 3014 3015 case AMK_Redeclaration: 3016 case AMK_Override: 3017 case AMK_ProtocolImplementation: 3018 case AMK_OptionalProtocolImplementation: 3019 LocalAMK = AMK; 3020 break; 3021 } 3022 } 3023 3024 // Already handled. 3025 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3026 continue; 3027 3028 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3029 foundAny = true; 3030 } 3031 3032 if (mergeAlignedAttrs(*this, New, Old)) 3033 foundAny = true; 3034 3035 if (!foundAny) New->dropAttrs(); 3036 } 3037 3038 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3039 /// to the new one. 3040 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3041 const ParmVarDecl *oldDecl, 3042 Sema &S) { 3043 // C++11 [dcl.attr.depend]p2: 3044 // The first declaration of a function shall specify the 3045 // carries_dependency attribute for its declarator-id if any declaration 3046 // of the function specifies the carries_dependency attribute. 3047 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3048 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3049 S.Diag(CDA->getLocation(), 3050 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3051 // Find the first declaration of the parameter. 3052 // FIXME: Should we build redeclaration chains for function parameters? 3053 const FunctionDecl *FirstFD = 3054 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3055 const ParmVarDecl *FirstVD = 3056 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3057 S.Diag(FirstVD->getLocation(), 3058 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3059 } 3060 3061 if (!oldDecl->hasAttrs()) 3062 return; 3063 3064 bool foundAny = newDecl->hasAttrs(); 3065 3066 // Ensure that any moving of objects within the allocated map is 3067 // done before we process them. 3068 if (!foundAny) newDecl->setAttrs(AttrVec()); 3069 3070 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3071 if (!DeclHasAttr(newDecl, I)) { 3072 InheritableAttr *newAttr = 3073 cast<InheritableParamAttr>(I->clone(S.Context)); 3074 newAttr->setInherited(true); 3075 newDecl->addAttr(newAttr); 3076 foundAny = true; 3077 } 3078 } 3079 3080 if (!foundAny) newDecl->dropAttrs(); 3081 } 3082 3083 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3084 const ParmVarDecl *OldParam, 3085 Sema &S) { 3086 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3087 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3088 if (*Oldnullability != *Newnullability) { 3089 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3090 << DiagNullabilityKind( 3091 *Newnullability, 3092 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3093 != 0)) 3094 << DiagNullabilityKind( 3095 *Oldnullability, 3096 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3097 != 0)); 3098 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3099 } 3100 } else { 3101 QualType NewT = NewParam->getType(); 3102 NewT = S.Context.getAttributedType( 3103 AttributedType::getNullabilityAttrKind(*Oldnullability), 3104 NewT, NewT); 3105 NewParam->setType(NewT); 3106 } 3107 } 3108 } 3109 3110 namespace { 3111 3112 /// Used in MergeFunctionDecl to keep track of function parameters in 3113 /// C. 3114 struct GNUCompatibleParamWarning { 3115 ParmVarDecl *OldParm; 3116 ParmVarDecl *NewParm; 3117 QualType PromotedType; 3118 }; 3119 3120 } // end anonymous namespace 3121 3122 // Determine whether the previous declaration was a definition, implicit 3123 // declaration, or a declaration. 3124 template <typename T> 3125 static std::pair<diag::kind, SourceLocation> 3126 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3127 diag::kind PrevDiag; 3128 SourceLocation OldLocation = Old->getLocation(); 3129 if (Old->isThisDeclarationADefinition()) 3130 PrevDiag = diag::note_previous_definition; 3131 else if (Old->isImplicit()) { 3132 PrevDiag = diag::note_previous_implicit_declaration; 3133 if (OldLocation.isInvalid()) 3134 OldLocation = New->getLocation(); 3135 } else 3136 PrevDiag = diag::note_previous_declaration; 3137 return std::make_pair(PrevDiag, OldLocation); 3138 } 3139 3140 /// canRedefineFunction - checks if a function can be redefined. Currently, 3141 /// only extern inline functions can be redefined, and even then only in 3142 /// GNU89 mode. 3143 static bool canRedefineFunction(const FunctionDecl *FD, 3144 const LangOptions& LangOpts) { 3145 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3146 !LangOpts.CPlusPlus && 3147 FD->isInlineSpecified() && 3148 FD->getStorageClass() == SC_Extern); 3149 } 3150 3151 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3152 const AttributedType *AT = T->getAs<AttributedType>(); 3153 while (AT && !AT->isCallingConv()) 3154 AT = AT->getModifiedType()->getAs<AttributedType>(); 3155 return AT; 3156 } 3157 3158 template <typename T> 3159 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3160 const DeclContext *DC = Old->getDeclContext(); 3161 if (DC->isRecord()) 3162 return false; 3163 3164 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3165 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3166 return true; 3167 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3168 return true; 3169 return false; 3170 } 3171 3172 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3173 static bool isExternC(VarTemplateDecl *) { return false; } 3174 static bool isExternC(FunctionTemplateDecl *) { return false; } 3175 3176 /// Check whether a redeclaration of an entity introduced by a 3177 /// using-declaration is valid, given that we know it's not an overload 3178 /// (nor a hidden tag declaration). 3179 template<typename ExpectedDecl> 3180 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3181 ExpectedDecl *New) { 3182 // C++11 [basic.scope.declarative]p4: 3183 // Given a set of declarations in a single declarative region, each of 3184 // which specifies the same unqualified name, 3185 // -- they shall all refer to the same entity, or all refer to functions 3186 // and function templates; or 3187 // -- exactly one declaration shall declare a class name or enumeration 3188 // name that is not a typedef name and the other declarations shall all 3189 // refer to the same variable or enumerator, or all refer to functions 3190 // and function templates; in this case the class name or enumeration 3191 // name is hidden (3.3.10). 3192 3193 // C++11 [namespace.udecl]p14: 3194 // If a function declaration in namespace scope or block scope has the 3195 // same name and the same parameter-type-list as a function introduced 3196 // by a using-declaration, and the declarations do not declare the same 3197 // function, the program is ill-formed. 3198 3199 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3200 if (Old && 3201 !Old->getDeclContext()->getRedeclContext()->Equals( 3202 New->getDeclContext()->getRedeclContext()) && 3203 !(isExternC(Old) && isExternC(New))) 3204 Old = nullptr; 3205 3206 if (!Old) { 3207 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3208 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3209 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3210 return true; 3211 } 3212 return false; 3213 } 3214 3215 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3216 const FunctionDecl *B) { 3217 assert(A->getNumParams() == B->getNumParams()); 3218 3219 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3220 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3221 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3222 if (AttrA == AttrB) 3223 return true; 3224 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3225 AttrA->isDynamic() == AttrB->isDynamic(); 3226 }; 3227 3228 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3229 } 3230 3231 /// If necessary, adjust the semantic declaration context for a qualified 3232 /// declaration to name the correct inline namespace within the qualifier. 3233 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3234 DeclaratorDecl *OldD) { 3235 // The only case where we need to update the DeclContext is when 3236 // redeclaration lookup for a qualified name finds a declaration 3237 // in an inline namespace within the context named by the qualifier: 3238 // 3239 // inline namespace N { int f(); } 3240 // int ::f(); // Sema DC needs adjusting from :: to N::. 3241 // 3242 // For unqualified declarations, the semantic context *can* change 3243 // along the redeclaration chain (for local extern declarations, 3244 // extern "C" declarations, and friend declarations in particular). 3245 if (!NewD->getQualifier()) 3246 return; 3247 3248 // NewD is probably already in the right context. 3249 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3250 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3251 if (NamedDC->Equals(SemaDC)) 3252 return; 3253 3254 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3255 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3256 "unexpected context for redeclaration"); 3257 3258 auto *LexDC = NewD->getLexicalDeclContext(); 3259 auto FixSemaDC = [=](NamedDecl *D) { 3260 if (!D) 3261 return; 3262 D->setDeclContext(SemaDC); 3263 D->setLexicalDeclContext(LexDC); 3264 }; 3265 3266 FixSemaDC(NewD); 3267 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3268 FixSemaDC(FD->getDescribedFunctionTemplate()); 3269 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3270 FixSemaDC(VD->getDescribedVarTemplate()); 3271 } 3272 3273 /// MergeFunctionDecl - We just parsed a function 'New' from 3274 /// declarator D which has the same name and scope as a previous 3275 /// declaration 'Old'. Figure out how to resolve this situation, 3276 /// merging decls or emitting diagnostics as appropriate. 3277 /// 3278 /// In C++, New and Old must be declarations that are not 3279 /// overloaded. Use IsOverload to determine whether New and Old are 3280 /// overloaded, and to select the Old declaration that New should be 3281 /// merged with. 3282 /// 3283 /// Returns true if there was an error, false otherwise. 3284 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3285 Scope *S, bool MergeTypeWithOld) { 3286 // Verify the old decl was also a function. 3287 FunctionDecl *Old = OldD->getAsFunction(); 3288 if (!Old) { 3289 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3290 if (New->getFriendObjectKind()) { 3291 Diag(New->getLocation(), diag::err_using_decl_friend); 3292 Diag(Shadow->getTargetDecl()->getLocation(), 3293 diag::note_using_decl_target); 3294 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3295 << 0; 3296 return true; 3297 } 3298 3299 // Check whether the two declarations might declare the same function or 3300 // function template. 3301 if (FunctionTemplateDecl *NewTemplate = 3302 New->getDescribedFunctionTemplate()) { 3303 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3304 NewTemplate)) 3305 return true; 3306 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3307 ->getAsFunction(); 3308 } else { 3309 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3310 return true; 3311 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3312 } 3313 } else { 3314 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3315 << New->getDeclName(); 3316 notePreviousDefinition(OldD, New->getLocation()); 3317 return true; 3318 } 3319 } 3320 3321 // If the old declaration was found in an inline namespace and the new 3322 // declaration was qualified, update the DeclContext to match. 3323 adjustDeclContextForDeclaratorDecl(New, Old); 3324 3325 // If the old declaration is invalid, just give up here. 3326 if (Old->isInvalidDecl()) 3327 return true; 3328 3329 // Disallow redeclaration of some builtins. 3330 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3331 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3332 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3333 << Old << Old->getType(); 3334 return true; 3335 } 3336 3337 diag::kind PrevDiag; 3338 SourceLocation OldLocation; 3339 std::tie(PrevDiag, OldLocation) = 3340 getNoteDiagForInvalidRedeclaration(Old, New); 3341 3342 // Don't complain about this if we're in GNU89 mode and the old function 3343 // is an extern inline function. 3344 // Don't complain about specializations. They are not supposed to have 3345 // storage classes. 3346 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3347 New->getStorageClass() == SC_Static && 3348 Old->hasExternalFormalLinkage() && 3349 !New->getTemplateSpecializationInfo() && 3350 !canRedefineFunction(Old, getLangOpts())) { 3351 if (getLangOpts().MicrosoftExt) { 3352 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3353 Diag(OldLocation, PrevDiag); 3354 } else { 3355 Diag(New->getLocation(), diag::err_static_non_static) << New; 3356 Diag(OldLocation, PrevDiag); 3357 return true; 3358 } 3359 } 3360 3361 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3362 if (!Old->hasAttr<InternalLinkageAttr>()) { 3363 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3364 << ILA; 3365 Diag(Old->getLocation(), diag::note_previous_declaration); 3366 New->dropAttr<InternalLinkageAttr>(); 3367 } 3368 3369 if (auto *EA = New->getAttr<ErrorAttr>()) { 3370 if (!Old->hasAttr<ErrorAttr>()) { 3371 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3372 Diag(Old->getLocation(), diag::note_previous_declaration); 3373 New->dropAttr<ErrorAttr>(); 3374 } 3375 } 3376 3377 if (CheckRedeclarationModuleOwnership(New, Old)) 3378 return true; 3379 3380 if (!getLangOpts().CPlusPlus) { 3381 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3382 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3383 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3384 << New << OldOvl; 3385 3386 // Try our best to find a decl that actually has the overloadable 3387 // attribute for the note. In most cases (e.g. programs with only one 3388 // broken declaration/definition), this won't matter. 3389 // 3390 // FIXME: We could do this if we juggled some extra state in 3391 // OverloadableAttr, rather than just removing it. 3392 const Decl *DiagOld = Old; 3393 if (OldOvl) { 3394 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3395 const auto *A = D->getAttr<OverloadableAttr>(); 3396 return A && !A->isImplicit(); 3397 }); 3398 // If we've implicitly added *all* of the overloadable attrs to this 3399 // chain, emitting a "previous redecl" note is pointless. 3400 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3401 } 3402 3403 if (DiagOld) 3404 Diag(DiagOld->getLocation(), 3405 diag::note_attribute_overloadable_prev_overload) 3406 << OldOvl; 3407 3408 if (OldOvl) 3409 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3410 else 3411 New->dropAttr<OverloadableAttr>(); 3412 } 3413 } 3414 3415 // If a function is first declared with a calling convention, but is later 3416 // declared or defined without one, all following decls assume the calling 3417 // convention of the first. 3418 // 3419 // It's OK if a function is first declared without a calling convention, 3420 // but is later declared or defined with the default calling convention. 3421 // 3422 // To test if either decl has an explicit calling convention, we look for 3423 // AttributedType sugar nodes on the type as written. If they are missing or 3424 // were canonicalized away, we assume the calling convention was implicit. 3425 // 3426 // Note also that we DO NOT return at this point, because we still have 3427 // other tests to run. 3428 QualType OldQType = Context.getCanonicalType(Old->getType()); 3429 QualType NewQType = Context.getCanonicalType(New->getType()); 3430 const FunctionType *OldType = cast<FunctionType>(OldQType); 3431 const FunctionType *NewType = cast<FunctionType>(NewQType); 3432 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3433 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3434 bool RequiresAdjustment = false; 3435 3436 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3437 FunctionDecl *First = Old->getFirstDecl(); 3438 const FunctionType *FT = 3439 First->getType().getCanonicalType()->castAs<FunctionType>(); 3440 FunctionType::ExtInfo FI = FT->getExtInfo(); 3441 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3442 if (!NewCCExplicit) { 3443 // Inherit the CC from the previous declaration if it was specified 3444 // there but not here. 3445 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3446 RequiresAdjustment = true; 3447 } else if (Old->getBuiltinID()) { 3448 // Builtin attribute isn't propagated to the new one yet at this point, 3449 // so we check if the old one is a builtin. 3450 3451 // Calling Conventions on a Builtin aren't really useful and setting a 3452 // default calling convention and cdecl'ing some builtin redeclarations is 3453 // common, so warn and ignore the calling convention on the redeclaration. 3454 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3455 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3456 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3457 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3458 RequiresAdjustment = true; 3459 } else { 3460 // Calling conventions aren't compatible, so complain. 3461 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3462 Diag(New->getLocation(), diag::err_cconv_change) 3463 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3464 << !FirstCCExplicit 3465 << (!FirstCCExplicit ? "" : 3466 FunctionType::getNameForCallConv(FI.getCC())); 3467 3468 // Put the note on the first decl, since it is the one that matters. 3469 Diag(First->getLocation(), diag::note_previous_declaration); 3470 return true; 3471 } 3472 } 3473 3474 // FIXME: diagnose the other way around? 3475 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3476 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3477 RequiresAdjustment = true; 3478 } 3479 3480 // Merge regparm attribute. 3481 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3482 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3483 if (NewTypeInfo.getHasRegParm()) { 3484 Diag(New->getLocation(), diag::err_regparm_mismatch) 3485 << NewType->getRegParmType() 3486 << OldType->getRegParmType(); 3487 Diag(OldLocation, diag::note_previous_declaration); 3488 return true; 3489 } 3490 3491 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3492 RequiresAdjustment = true; 3493 } 3494 3495 // Merge ns_returns_retained attribute. 3496 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3497 if (NewTypeInfo.getProducesResult()) { 3498 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3499 << "'ns_returns_retained'"; 3500 Diag(OldLocation, diag::note_previous_declaration); 3501 return true; 3502 } 3503 3504 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3505 RequiresAdjustment = true; 3506 } 3507 3508 if (OldTypeInfo.getNoCallerSavedRegs() != 3509 NewTypeInfo.getNoCallerSavedRegs()) { 3510 if (NewTypeInfo.getNoCallerSavedRegs()) { 3511 AnyX86NoCallerSavedRegistersAttr *Attr = 3512 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3513 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3514 Diag(OldLocation, diag::note_previous_declaration); 3515 return true; 3516 } 3517 3518 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3519 RequiresAdjustment = true; 3520 } 3521 3522 if (RequiresAdjustment) { 3523 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3524 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3525 New->setType(QualType(AdjustedType, 0)); 3526 NewQType = Context.getCanonicalType(New->getType()); 3527 } 3528 3529 // If this redeclaration makes the function inline, we may need to add it to 3530 // UndefinedButUsed. 3531 if (!Old->isInlined() && New->isInlined() && 3532 !New->hasAttr<GNUInlineAttr>() && 3533 !getLangOpts().GNUInline && 3534 Old->isUsed(false) && 3535 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3536 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3537 SourceLocation())); 3538 3539 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3540 // about it. 3541 if (New->hasAttr<GNUInlineAttr>() && 3542 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3543 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3544 } 3545 3546 // If pass_object_size params don't match up perfectly, this isn't a valid 3547 // redeclaration. 3548 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3549 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3550 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3551 << New->getDeclName(); 3552 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3553 return true; 3554 } 3555 3556 if (getLangOpts().CPlusPlus) { 3557 // C++1z [over.load]p2 3558 // Certain function declarations cannot be overloaded: 3559 // -- Function declarations that differ only in the return type, 3560 // the exception specification, or both cannot be overloaded. 3561 3562 // Check the exception specifications match. This may recompute the type of 3563 // both Old and New if it resolved exception specifications, so grab the 3564 // types again after this. Because this updates the type, we do this before 3565 // any of the other checks below, which may update the "de facto" NewQType 3566 // but do not necessarily update the type of New. 3567 if (CheckEquivalentExceptionSpec(Old, New)) 3568 return true; 3569 OldQType = Context.getCanonicalType(Old->getType()); 3570 NewQType = Context.getCanonicalType(New->getType()); 3571 3572 // Go back to the type source info to compare the declared return types, 3573 // per C++1y [dcl.type.auto]p13: 3574 // Redeclarations or specializations of a function or function template 3575 // with a declared return type that uses a placeholder type shall also 3576 // use that placeholder, not a deduced type. 3577 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3578 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3579 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3580 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3581 OldDeclaredReturnType)) { 3582 QualType ResQT; 3583 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3584 OldDeclaredReturnType->isObjCObjectPointerType()) 3585 // FIXME: This does the wrong thing for a deduced return type. 3586 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3587 if (ResQT.isNull()) { 3588 if (New->isCXXClassMember() && New->isOutOfLine()) 3589 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3590 << New << New->getReturnTypeSourceRange(); 3591 else 3592 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3593 << New->getReturnTypeSourceRange(); 3594 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3595 << Old->getReturnTypeSourceRange(); 3596 return true; 3597 } 3598 else 3599 NewQType = ResQT; 3600 } 3601 3602 QualType OldReturnType = OldType->getReturnType(); 3603 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3604 if (OldReturnType != NewReturnType) { 3605 // If this function has a deduced return type and has already been 3606 // defined, copy the deduced value from the old declaration. 3607 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3608 if (OldAT && OldAT->isDeduced()) { 3609 New->setType( 3610 SubstAutoType(New->getType(), 3611 OldAT->isDependentType() ? Context.DependentTy 3612 : OldAT->getDeducedType())); 3613 NewQType = Context.getCanonicalType( 3614 SubstAutoType(NewQType, 3615 OldAT->isDependentType() ? Context.DependentTy 3616 : OldAT->getDeducedType())); 3617 } 3618 } 3619 3620 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3621 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3622 if (OldMethod && NewMethod) { 3623 // Preserve triviality. 3624 NewMethod->setTrivial(OldMethod->isTrivial()); 3625 3626 // MSVC allows explicit template specialization at class scope: 3627 // 2 CXXMethodDecls referring to the same function will be injected. 3628 // We don't want a redeclaration error. 3629 bool IsClassScopeExplicitSpecialization = 3630 OldMethod->isFunctionTemplateSpecialization() && 3631 NewMethod->isFunctionTemplateSpecialization(); 3632 bool isFriend = NewMethod->getFriendObjectKind(); 3633 3634 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3635 !IsClassScopeExplicitSpecialization) { 3636 // -- Member function declarations with the same name and the 3637 // same parameter types cannot be overloaded if any of them 3638 // is a static member function declaration. 3639 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3640 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3641 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3642 return true; 3643 } 3644 3645 // C++ [class.mem]p1: 3646 // [...] A member shall not be declared twice in the 3647 // member-specification, except that a nested class or member 3648 // class template can be declared and then later defined. 3649 if (!inTemplateInstantiation()) { 3650 unsigned NewDiag; 3651 if (isa<CXXConstructorDecl>(OldMethod)) 3652 NewDiag = diag::err_constructor_redeclared; 3653 else if (isa<CXXDestructorDecl>(NewMethod)) 3654 NewDiag = diag::err_destructor_redeclared; 3655 else if (isa<CXXConversionDecl>(NewMethod)) 3656 NewDiag = diag::err_conv_function_redeclared; 3657 else 3658 NewDiag = diag::err_member_redeclared; 3659 3660 Diag(New->getLocation(), NewDiag); 3661 } else { 3662 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3663 << New << New->getType(); 3664 } 3665 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3666 return true; 3667 3668 // Complain if this is an explicit declaration of a special 3669 // member that was initially declared implicitly. 3670 // 3671 // As an exception, it's okay to befriend such methods in order 3672 // to permit the implicit constructor/destructor/operator calls. 3673 } else if (OldMethod->isImplicit()) { 3674 if (isFriend) { 3675 NewMethod->setImplicit(); 3676 } else { 3677 Diag(NewMethod->getLocation(), 3678 diag::err_definition_of_implicitly_declared_member) 3679 << New << getSpecialMember(OldMethod); 3680 return true; 3681 } 3682 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3683 Diag(NewMethod->getLocation(), 3684 diag::err_definition_of_explicitly_defaulted_member) 3685 << getSpecialMember(OldMethod); 3686 return true; 3687 } 3688 } 3689 3690 // C++11 [dcl.attr.noreturn]p1: 3691 // The first declaration of a function shall specify the noreturn 3692 // attribute if any declaration of that function specifies the noreturn 3693 // attribute. 3694 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3695 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3696 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3697 << NRA; 3698 Diag(Old->getLocation(), diag::note_previous_declaration); 3699 } 3700 3701 // C++11 [dcl.attr.depend]p2: 3702 // The first declaration of a function shall specify the 3703 // carries_dependency attribute for its declarator-id if any declaration 3704 // of the function specifies the carries_dependency attribute. 3705 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3706 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3707 Diag(CDA->getLocation(), 3708 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3709 Diag(Old->getFirstDecl()->getLocation(), 3710 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3711 } 3712 3713 // (C++98 8.3.5p3): 3714 // All declarations for a function shall agree exactly in both the 3715 // return type and the parameter-type-list. 3716 // We also want to respect all the extended bits except noreturn. 3717 3718 // noreturn should now match unless the old type info didn't have it. 3719 QualType OldQTypeForComparison = OldQType; 3720 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3721 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3722 const FunctionType *OldTypeForComparison 3723 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3724 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3725 assert(OldQTypeForComparison.isCanonical()); 3726 } 3727 3728 if (haveIncompatibleLanguageLinkages(Old, New)) { 3729 // As a special case, retain the language linkage from previous 3730 // declarations of a friend function as an extension. 3731 // 3732 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3733 // and is useful because there's otherwise no way to specify language 3734 // linkage within class scope. 3735 // 3736 // Check cautiously as the friend object kind isn't yet complete. 3737 if (New->getFriendObjectKind() != Decl::FOK_None) { 3738 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3739 Diag(OldLocation, PrevDiag); 3740 } else { 3741 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3742 Diag(OldLocation, PrevDiag); 3743 return true; 3744 } 3745 } 3746 3747 // If the function types are compatible, merge the declarations. Ignore the 3748 // exception specifier because it was already checked above in 3749 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3750 // about incompatible types under -fms-compatibility. 3751 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3752 NewQType)) 3753 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3754 3755 // If the types are imprecise (due to dependent constructs in friends or 3756 // local extern declarations), it's OK if they differ. We'll check again 3757 // during instantiation. 3758 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3759 return false; 3760 3761 // Fall through for conflicting redeclarations and redefinitions. 3762 } 3763 3764 // C: Function types need to be compatible, not identical. This handles 3765 // duplicate function decls like "void f(int); void f(enum X);" properly. 3766 if (!getLangOpts().CPlusPlus && 3767 Context.typesAreCompatible(OldQType, NewQType)) { 3768 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3769 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3770 const FunctionProtoType *OldProto = nullptr; 3771 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3772 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3773 // The old declaration provided a function prototype, but the 3774 // new declaration does not. Merge in the prototype. 3775 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3776 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3777 NewQType = 3778 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3779 OldProto->getExtProtoInfo()); 3780 New->setType(NewQType); 3781 New->setHasInheritedPrototype(); 3782 3783 // Synthesize parameters with the same types. 3784 SmallVector<ParmVarDecl*, 16> Params; 3785 for (const auto &ParamType : OldProto->param_types()) { 3786 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3787 SourceLocation(), nullptr, 3788 ParamType, /*TInfo=*/nullptr, 3789 SC_None, nullptr); 3790 Param->setScopeInfo(0, Params.size()); 3791 Param->setImplicit(); 3792 Params.push_back(Param); 3793 } 3794 3795 New->setParams(Params); 3796 } 3797 3798 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3799 } 3800 3801 // Check if the function types are compatible when pointer size address 3802 // spaces are ignored. 3803 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3804 return false; 3805 3806 // GNU C permits a K&R definition to follow a prototype declaration 3807 // if the declared types of the parameters in the K&R definition 3808 // match the types in the prototype declaration, even when the 3809 // promoted types of the parameters from the K&R definition differ 3810 // from the types in the prototype. GCC then keeps the types from 3811 // the prototype. 3812 // 3813 // If a variadic prototype is followed by a non-variadic K&R definition, 3814 // the K&R definition becomes variadic. This is sort of an edge case, but 3815 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3816 // C99 6.9.1p8. 3817 if (!getLangOpts().CPlusPlus && 3818 Old->hasPrototype() && !New->hasPrototype() && 3819 New->getType()->getAs<FunctionProtoType>() && 3820 Old->getNumParams() == New->getNumParams()) { 3821 SmallVector<QualType, 16> ArgTypes; 3822 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3823 const FunctionProtoType *OldProto 3824 = Old->getType()->getAs<FunctionProtoType>(); 3825 const FunctionProtoType *NewProto 3826 = New->getType()->getAs<FunctionProtoType>(); 3827 3828 // Determine whether this is the GNU C extension. 3829 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3830 NewProto->getReturnType()); 3831 bool LooseCompatible = !MergedReturn.isNull(); 3832 for (unsigned Idx = 0, End = Old->getNumParams(); 3833 LooseCompatible && Idx != End; ++Idx) { 3834 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3835 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3836 if (Context.typesAreCompatible(OldParm->getType(), 3837 NewProto->getParamType(Idx))) { 3838 ArgTypes.push_back(NewParm->getType()); 3839 } else if (Context.typesAreCompatible(OldParm->getType(), 3840 NewParm->getType(), 3841 /*CompareUnqualified=*/true)) { 3842 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3843 NewProto->getParamType(Idx) }; 3844 Warnings.push_back(Warn); 3845 ArgTypes.push_back(NewParm->getType()); 3846 } else 3847 LooseCompatible = false; 3848 } 3849 3850 if (LooseCompatible) { 3851 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3852 Diag(Warnings[Warn].NewParm->getLocation(), 3853 diag::ext_param_promoted_not_compatible_with_prototype) 3854 << Warnings[Warn].PromotedType 3855 << Warnings[Warn].OldParm->getType(); 3856 if (Warnings[Warn].OldParm->getLocation().isValid()) 3857 Diag(Warnings[Warn].OldParm->getLocation(), 3858 diag::note_previous_declaration); 3859 } 3860 3861 if (MergeTypeWithOld) 3862 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3863 OldProto->getExtProtoInfo())); 3864 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3865 } 3866 3867 // Fall through to diagnose conflicting types. 3868 } 3869 3870 // A function that has already been declared has been redeclared or 3871 // defined with a different type; show an appropriate diagnostic. 3872 3873 // If the previous declaration was an implicitly-generated builtin 3874 // declaration, then at the very least we should use a specialized note. 3875 unsigned BuiltinID; 3876 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3877 // If it's actually a library-defined builtin function like 'malloc' 3878 // or 'printf', just warn about the incompatible redeclaration. 3879 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3880 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3881 Diag(OldLocation, diag::note_previous_builtin_declaration) 3882 << Old << Old->getType(); 3883 return false; 3884 } 3885 3886 PrevDiag = diag::note_previous_builtin_declaration; 3887 } 3888 3889 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3890 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3891 return true; 3892 } 3893 3894 /// Completes the merge of two function declarations that are 3895 /// known to be compatible. 3896 /// 3897 /// This routine handles the merging of attributes and other 3898 /// properties of function declarations from the old declaration to 3899 /// the new declaration, once we know that New is in fact a 3900 /// redeclaration of Old. 3901 /// 3902 /// \returns false 3903 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3904 Scope *S, bool MergeTypeWithOld) { 3905 // Merge the attributes 3906 mergeDeclAttributes(New, Old); 3907 3908 // Merge "pure" flag. 3909 if (Old->isPure()) 3910 New->setPure(); 3911 3912 // Merge "used" flag. 3913 if (Old->getMostRecentDecl()->isUsed(false)) 3914 New->setIsUsed(); 3915 3916 // Merge attributes from the parameters. These can mismatch with K&R 3917 // declarations. 3918 if (New->getNumParams() == Old->getNumParams()) 3919 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3920 ParmVarDecl *NewParam = New->getParamDecl(i); 3921 ParmVarDecl *OldParam = Old->getParamDecl(i); 3922 mergeParamDeclAttributes(NewParam, OldParam, *this); 3923 mergeParamDeclTypes(NewParam, OldParam, *this); 3924 } 3925 3926 if (getLangOpts().CPlusPlus) 3927 return MergeCXXFunctionDecl(New, Old, S); 3928 3929 // Merge the function types so the we get the composite types for the return 3930 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3931 // was visible. 3932 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3933 if (!Merged.isNull() && MergeTypeWithOld) 3934 New->setType(Merged); 3935 3936 return false; 3937 } 3938 3939 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3940 ObjCMethodDecl *oldMethod) { 3941 // Merge the attributes, including deprecated/unavailable 3942 AvailabilityMergeKind MergeKind = 3943 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3944 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 3945 : AMK_ProtocolImplementation) 3946 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3947 : AMK_Override; 3948 3949 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3950 3951 // Merge attributes from the parameters. 3952 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3953 oe = oldMethod->param_end(); 3954 for (ObjCMethodDecl::param_iterator 3955 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3956 ni != ne && oi != oe; ++ni, ++oi) 3957 mergeParamDeclAttributes(*ni, *oi, *this); 3958 3959 CheckObjCMethodOverride(newMethod, oldMethod); 3960 } 3961 3962 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3963 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3964 3965 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3966 ? diag::err_redefinition_different_type 3967 : diag::err_redeclaration_different_type) 3968 << New->getDeclName() << New->getType() << Old->getType(); 3969 3970 diag::kind PrevDiag; 3971 SourceLocation OldLocation; 3972 std::tie(PrevDiag, OldLocation) 3973 = getNoteDiagForInvalidRedeclaration(Old, New); 3974 S.Diag(OldLocation, PrevDiag); 3975 New->setInvalidDecl(); 3976 } 3977 3978 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3979 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3980 /// emitting diagnostics as appropriate. 3981 /// 3982 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3983 /// to here in AddInitializerToDecl. We can't check them before the initializer 3984 /// is attached. 3985 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3986 bool MergeTypeWithOld) { 3987 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3988 return; 3989 3990 QualType MergedT; 3991 if (getLangOpts().CPlusPlus) { 3992 if (New->getType()->isUndeducedType()) { 3993 // We don't know what the new type is until the initializer is attached. 3994 return; 3995 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3996 // These could still be something that needs exception specs checked. 3997 return MergeVarDeclExceptionSpecs(New, Old); 3998 } 3999 // C++ [basic.link]p10: 4000 // [...] the types specified by all declarations referring to a given 4001 // object or function shall be identical, except that declarations for an 4002 // array object can specify array types that differ by the presence or 4003 // absence of a major array bound (8.3.4). 4004 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4005 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4006 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4007 4008 // We are merging a variable declaration New into Old. If it has an array 4009 // bound, and that bound differs from Old's bound, we should diagnose the 4010 // mismatch. 4011 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4012 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4013 PrevVD = PrevVD->getPreviousDecl()) { 4014 QualType PrevVDTy = PrevVD->getType(); 4015 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4016 continue; 4017 4018 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4019 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4020 } 4021 } 4022 4023 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4024 if (Context.hasSameType(OldArray->getElementType(), 4025 NewArray->getElementType())) 4026 MergedT = New->getType(); 4027 } 4028 // FIXME: Check visibility. New is hidden but has a complete type. If New 4029 // has no array bound, it should not inherit one from Old, if Old is not 4030 // visible. 4031 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4032 if (Context.hasSameType(OldArray->getElementType(), 4033 NewArray->getElementType())) 4034 MergedT = Old->getType(); 4035 } 4036 } 4037 else if (New->getType()->isObjCObjectPointerType() && 4038 Old->getType()->isObjCObjectPointerType()) { 4039 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4040 Old->getType()); 4041 } 4042 } else { 4043 // C 6.2.7p2: 4044 // All declarations that refer to the same object or function shall have 4045 // compatible type. 4046 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4047 } 4048 if (MergedT.isNull()) { 4049 // It's OK if we couldn't merge types if either type is dependent, for a 4050 // block-scope variable. In other cases (static data members of class 4051 // templates, variable templates, ...), we require the types to be 4052 // equivalent. 4053 // FIXME: The C++ standard doesn't say anything about this. 4054 if ((New->getType()->isDependentType() || 4055 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4056 // If the old type was dependent, we can't merge with it, so the new type 4057 // becomes dependent for now. We'll reproduce the original type when we 4058 // instantiate the TypeSourceInfo for the variable. 4059 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4060 New->setType(Context.DependentTy); 4061 return; 4062 } 4063 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4064 } 4065 4066 // Don't actually update the type on the new declaration if the old 4067 // declaration was an extern declaration in a different scope. 4068 if (MergeTypeWithOld) 4069 New->setType(MergedT); 4070 } 4071 4072 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4073 LookupResult &Previous) { 4074 // C11 6.2.7p4: 4075 // For an identifier with internal or external linkage declared 4076 // in a scope in which a prior declaration of that identifier is 4077 // visible, if the prior declaration specifies internal or 4078 // external linkage, the type of the identifier at the later 4079 // declaration becomes the composite type. 4080 // 4081 // If the variable isn't visible, we do not merge with its type. 4082 if (Previous.isShadowed()) 4083 return false; 4084 4085 if (S.getLangOpts().CPlusPlus) { 4086 // C++11 [dcl.array]p3: 4087 // If there is a preceding declaration of the entity in the same 4088 // scope in which the bound was specified, an omitted array bound 4089 // is taken to be the same as in that earlier declaration. 4090 return NewVD->isPreviousDeclInSameBlockScope() || 4091 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4092 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4093 } else { 4094 // If the old declaration was function-local, don't merge with its 4095 // type unless we're in the same function. 4096 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4097 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4098 } 4099 } 4100 4101 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4102 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4103 /// situation, merging decls or emitting diagnostics as appropriate. 4104 /// 4105 /// Tentative definition rules (C99 6.9.2p2) are checked by 4106 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4107 /// definitions here, since the initializer hasn't been attached. 4108 /// 4109 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4110 // If the new decl is already invalid, don't do any other checking. 4111 if (New->isInvalidDecl()) 4112 return; 4113 4114 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4115 return; 4116 4117 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4118 4119 // Verify the old decl was also a variable or variable template. 4120 VarDecl *Old = nullptr; 4121 VarTemplateDecl *OldTemplate = nullptr; 4122 if (Previous.isSingleResult()) { 4123 if (NewTemplate) { 4124 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4125 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4126 4127 if (auto *Shadow = 4128 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4129 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4130 return New->setInvalidDecl(); 4131 } else { 4132 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4133 4134 if (auto *Shadow = 4135 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4136 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4137 return New->setInvalidDecl(); 4138 } 4139 } 4140 if (!Old) { 4141 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4142 << New->getDeclName(); 4143 notePreviousDefinition(Previous.getRepresentativeDecl(), 4144 New->getLocation()); 4145 return New->setInvalidDecl(); 4146 } 4147 4148 // If the old declaration was found in an inline namespace and the new 4149 // declaration was qualified, update the DeclContext to match. 4150 adjustDeclContextForDeclaratorDecl(New, Old); 4151 4152 // Ensure the template parameters are compatible. 4153 if (NewTemplate && 4154 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4155 OldTemplate->getTemplateParameters(), 4156 /*Complain=*/true, TPL_TemplateMatch)) 4157 return New->setInvalidDecl(); 4158 4159 // C++ [class.mem]p1: 4160 // A member shall not be declared twice in the member-specification [...] 4161 // 4162 // Here, we need only consider static data members. 4163 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4164 Diag(New->getLocation(), diag::err_duplicate_member) 4165 << New->getIdentifier(); 4166 Diag(Old->getLocation(), diag::note_previous_declaration); 4167 New->setInvalidDecl(); 4168 } 4169 4170 mergeDeclAttributes(New, Old); 4171 // Warn if an already-declared variable is made a weak_import in a subsequent 4172 // declaration 4173 if (New->hasAttr<WeakImportAttr>() && 4174 Old->getStorageClass() == SC_None && 4175 !Old->hasAttr<WeakImportAttr>()) { 4176 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4177 Diag(Old->getLocation(), diag::note_previous_declaration); 4178 // Remove weak_import attribute on new declaration. 4179 New->dropAttr<WeakImportAttr>(); 4180 } 4181 4182 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4183 if (!Old->hasAttr<InternalLinkageAttr>()) { 4184 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4185 << ILA; 4186 Diag(Old->getLocation(), diag::note_previous_declaration); 4187 New->dropAttr<InternalLinkageAttr>(); 4188 } 4189 4190 // Merge the types. 4191 VarDecl *MostRecent = Old->getMostRecentDecl(); 4192 if (MostRecent != Old) { 4193 MergeVarDeclTypes(New, MostRecent, 4194 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4195 if (New->isInvalidDecl()) 4196 return; 4197 } 4198 4199 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4200 if (New->isInvalidDecl()) 4201 return; 4202 4203 diag::kind PrevDiag; 4204 SourceLocation OldLocation; 4205 std::tie(PrevDiag, OldLocation) = 4206 getNoteDiagForInvalidRedeclaration(Old, New); 4207 4208 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4209 if (New->getStorageClass() == SC_Static && 4210 !New->isStaticDataMember() && 4211 Old->hasExternalFormalLinkage()) { 4212 if (getLangOpts().MicrosoftExt) { 4213 Diag(New->getLocation(), diag::ext_static_non_static) 4214 << New->getDeclName(); 4215 Diag(OldLocation, PrevDiag); 4216 } else { 4217 Diag(New->getLocation(), diag::err_static_non_static) 4218 << New->getDeclName(); 4219 Diag(OldLocation, PrevDiag); 4220 return New->setInvalidDecl(); 4221 } 4222 } 4223 // C99 6.2.2p4: 4224 // For an identifier declared with the storage-class specifier 4225 // extern in a scope in which a prior declaration of that 4226 // identifier is visible,23) if the prior declaration specifies 4227 // internal or external linkage, the linkage of the identifier at 4228 // the later declaration is the same as the linkage specified at 4229 // the prior declaration. If no prior declaration is visible, or 4230 // if the prior declaration specifies no linkage, then the 4231 // identifier has external linkage. 4232 if (New->hasExternalStorage() && Old->hasLinkage()) 4233 /* Okay */; 4234 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4235 !New->isStaticDataMember() && 4236 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4237 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4238 Diag(OldLocation, PrevDiag); 4239 return New->setInvalidDecl(); 4240 } 4241 4242 // Check if extern is followed by non-extern and vice-versa. 4243 if (New->hasExternalStorage() && 4244 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4245 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4246 Diag(OldLocation, PrevDiag); 4247 return New->setInvalidDecl(); 4248 } 4249 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4250 !New->hasExternalStorage()) { 4251 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4252 Diag(OldLocation, PrevDiag); 4253 return New->setInvalidDecl(); 4254 } 4255 4256 if (CheckRedeclarationModuleOwnership(New, Old)) 4257 return; 4258 4259 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4260 4261 // FIXME: The test for external storage here seems wrong? We still 4262 // need to check for mismatches. 4263 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4264 // Don't complain about out-of-line definitions of static members. 4265 !(Old->getLexicalDeclContext()->isRecord() && 4266 !New->getLexicalDeclContext()->isRecord())) { 4267 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4268 Diag(OldLocation, PrevDiag); 4269 return New->setInvalidDecl(); 4270 } 4271 4272 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4273 if (VarDecl *Def = Old->getDefinition()) { 4274 // C++1z [dcl.fcn.spec]p4: 4275 // If the definition of a variable appears in a translation unit before 4276 // its first declaration as inline, the program is ill-formed. 4277 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4278 Diag(Def->getLocation(), diag::note_previous_definition); 4279 } 4280 } 4281 4282 // If this redeclaration makes the variable inline, we may need to add it to 4283 // UndefinedButUsed. 4284 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4285 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4286 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4287 SourceLocation())); 4288 4289 if (New->getTLSKind() != Old->getTLSKind()) { 4290 if (!Old->getTLSKind()) { 4291 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4292 Diag(OldLocation, PrevDiag); 4293 } else if (!New->getTLSKind()) { 4294 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4295 Diag(OldLocation, PrevDiag); 4296 } else { 4297 // Do not allow redeclaration to change the variable between requiring 4298 // static and dynamic initialization. 4299 // FIXME: GCC allows this, but uses the TLS keyword on the first 4300 // declaration to determine the kind. Do we need to be compatible here? 4301 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4302 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4303 Diag(OldLocation, PrevDiag); 4304 } 4305 } 4306 4307 // C++ doesn't have tentative definitions, so go right ahead and check here. 4308 if (getLangOpts().CPlusPlus && 4309 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4310 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4311 Old->getCanonicalDecl()->isConstexpr()) { 4312 // This definition won't be a definition any more once it's been merged. 4313 Diag(New->getLocation(), 4314 diag::warn_deprecated_redundant_constexpr_static_def); 4315 } else if (VarDecl *Def = Old->getDefinition()) { 4316 if (checkVarDeclRedefinition(Def, New)) 4317 return; 4318 } 4319 } 4320 4321 if (haveIncompatibleLanguageLinkages(Old, New)) { 4322 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4323 Diag(OldLocation, PrevDiag); 4324 New->setInvalidDecl(); 4325 return; 4326 } 4327 4328 // Merge "used" flag. 4329 if (Old->getMostRecentDecl()->isUsed(false)) 4330 New->setIsUsed(); 4331 4332 // Keep a chain of previous declarations. 4333 New->setPreviousDecl(Old); 4334 if (NewTemplate) 4335 NewTemplate->setPreviousDecl(OldTemplate); 4336 4337 // Inherit access appropriately. 4338 New->setAccess(Old->getAccess()); 4339 if (NewTemplate) 4340 NewTemplate->setAccess(New->getAccess()); 4341 4342 if (Old->isInline()) 4343 New->setImplicitlyInline(); 4344 } 4345 4346 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4347 SourceManager &SrcMgr = getSourceManager(); 4348 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4349 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4350 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4351 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4352 auto &HSI = PP.getHeaderSearchInfo(); 4353 StringRef HdrFilename = 4354 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4355 4356 auto noteFromModuleOrInclude = [&](Module *Mod, 4357 SourceLocation IncLoc) -> bool { 4358 // Redefinition errors with modules are common with non modular mapped 4359 // headers, example: a non-modular header H in module A that also gets 4360 // included directly in a TU. Pointing twice to the same header/definition 4361 // is confusing, try to get better diagnostics when modules is on. 4362 if (IncLoc.isValid()) { 4363 if (Mod) { 4364 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4365 << HdrFilename.str() << Mod->getFullModuleName(); 4366 if (!Mod->DefinitionLoc.isInvalid()) 4367 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4368 << Mod->getFullModuleName(); 4369 } else { 4370 Diag(IncLoc, diag::note_redefinition_include_same_file) 4371 << HdrFilename.str(); 4372 } 4373 return true; 4374 } 4375 4376 return false; 4377 }; 4378 4379 // Is it the same file and same offset? Provide more information on why 4380 // this leads to a redefinition error. 4381 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4382 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4383 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4384 bool EmittedDiag = 4385 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4386 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4387 4388 // If the header has no guards, emit a note suggesting one. 4389 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4390 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4391 4392 if (EmittedDiag) 4393 return; 4394 } 4395 4396 // Redefinition coming from different files or couldn't do better above. 4397 if (Old->getLocation().isValid()) 4398 Diag(Old->getLocation(), diag::note_previous_definition); 4399 } 4400 4401 /// We've just determined that \p Old and \p New both appear to be definitions 4402 /// of the same variable. Either diagnose or fix the problem. 4403 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4404 if (!hasVisibleDefinition(Old) && 4405 (New->getFormalLinkage() == InternalLinkage || 4406 New->isInline() || 4407 New->getDescribedVarTemplate() || 4408 New->getNumTemplateParameterLists() || 4409 New->getDeclContext()->isDependentContext())) { 4410 // The previous definition is hidden, and multiple definitions are 4411 // permitted (in separate TUs). Demote this to a declaration. 4412 New->demoteThisDefinitionToDeclaration(); 4413 4414 // Make the canonical definition visible. 4415 if (auto *OldTD = Old->getDescribedVarTemplate()) 4416 makeMergedDefinitionVisible(OldTD); 4417 makeMergedDefinitionVisible(Old); 4418 return false; 4419 } else { 4420 Diag(New->getLocation(), diag::err_redefinition) << New; 4421 notePreviousDefinition(Old, New->getLocation()); 4422 New->setInvalidDecl(); 4423 return true; 4424 } 4425 } 4426 4427 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4428 /// no declarator (e.g. "struct foo;") is parsed. 4429 Decl * 4430 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4431 RecordDecl *&AnonRecord) { 4432 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4433 AnonRecord); 4434 } 4435 4436 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4437 // disambiguate entities defined in different scopes. 4438 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4439 // compatibility. 4440 // We will pick our mangling number depending on which version of MSVC is being 4441 // targeted. 4442 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4443 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4444 ? S->getMSCurManglingNumber() 4445 : S->getMSLastManglingNumber(); 4446 } 4447 4448 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4449 if (!Context.getLangOpts().CPlusPlus) 4450 return; 4451 4452 if (isa<CXXRecordDecl>(Tag->getParent())) { 4453 // If this tag is the direct child of a class, number it if 4454 // it is anonymous. 4455 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4456 return; 4457 MangleNumberingContext &MCtx = 4458 Context.getManglingNumberContext(Tag->getParent()); 4459 Context.setManglingNumber( 4460 Tag, MCtx.getManglingNumber( 4461 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4462 return; 4463 } 4464 4465 // If this tag isn't a direct child of a class, number it if it is local. 4466 MangleNumberingContext *MCtx; 4467 Decl *ManglingContextDecl; 4468 std::tie(MCtx, ManglingContextDecl) = 4469 getCurrentMangleNumberContext(Tag->getDeclContext()); 4470 if (MCtx) { 4471 Context.setManglingNumber( 4472 Tag, MCtx->getManglingNumber( 4473 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4474 } 4475 } 4476 4477 namespace { 4478 struct NonCLikeKind { 4479 enum { 4480 None, 4481 BaseClass, 4482 DefaultMemberInit, 4483 Lambda, 4484 Friend, 4485 OtherMember, 4486 Invalid, 4487 } Kind = None; 4488 SourceRange Range; 4489 4490 explicit operator bool() { return Kind != None; } 4491 }; 4492 } 4493 4494 /// Determine whether a class is C-like, according to the rules of C++ 4495 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4496 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4497 if (RD->isInvalidDecl()) 4498 return {NonCLikeKind::Invalid, {}}; 4499 4500 // C++ [dcl.typedef]p9: [P1766R1] 4501 // An unnamed class with a typedef name for linkage purposes shall not 4502 // 4503 // -- have any base classes 4504 if (RD->getNumBases()) 4505 return {NonCLikeKind::BaseClass, 4506 SourceRange(RD->bases_begin()->getBeginLoc(), 4507 RD->bases_end()[-1].getEndLoc())}; 4508 bool Invalid = false; 4509 for (Decl *D : RD->decls()) { 4510 // Don't complain about things we already diagnosed. 4511 if (D->isInvalidDecl()) { 4512 Invalid = true; 4513 continue; 4514 } 4515 4516 // -- have any [...] default member initializers 4517 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4518 if (FD->hasInClassInitializer()) { 4519 auto *Init = FD->getInClassInitializer(); 4520 return {NonCLikeKind::DefaultMemberInit, 4521 Init ? Init->getSourceRange() : D->getSourceRange()}; 4522 } 4523 continue; 4524 } 4525 4526 // FIXME: We don't allow friend declarations. This violates the wording of 4527 // P1766, but not the intent. 4528 if (isa<FriendDecl>(D)) 4529 return {NonCLikeKind::Friend, D->getSourceRange()}; 4530 4531 // -- declare any members other than non-static data members, member 4532 // enumerations, or member classes, 4533 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4534 isa<EnumDecl>(D)) 4535 continue; 4536 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4537 if (!MemberRD) { 4538 if (D->isImplicit()) 4539 continue; 4540 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4541 } 4542 4543 // -- contain a lambda-expression, 4544 if (MemberRD->isLambda()) 4545 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4546 4547 // and all member classes shall also satisfy these requirements 4548 // (recursively). 4549 if (MemberRD->isThisDeclarationADefinition()) { 4550 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4551 return Kind; 4552 } 4553 } 4554 4555 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4556 } 4557 4558 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4559 TypedefNameDecl *NewTD) { 4560 if (TagFromDeclSpec->isInvalidDecl()) 4561 return; 4562 4563 // Do nothing if the tag already has a name for linkage purposes. 4564 if (TagFromDeclSpec->hasNameForLinkage()) 4565 return; 4566 4567 // A well-formed anonymous tag must always be a TUK_Definition. 4568 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4569 4570 // The type must match the tag exactly; no qualifiers allowed. 4571 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4572 Context.getTagDeclType(TagFromDeclSpec))) { 4573 if (getLangOpts().CPlusPlus) 4574 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4575 return; 4576 } 4577 4578 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4579 // An unnamed class with a typedef name for linkage purposes shall [be 4580 // C-like]. 4581 // 4582 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4583 // shouldn't happen, but there are constructs that the language rule doesn't 4584 // disallow for which we can't reasonably avoid computing linkage early. 4585 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4586 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4587 : NonCLikeKind(); 4588 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4589 if (NonCLike || ChangesLinkage) { 4590 if (NonCLike.Kind == NonCLikeKind::Invalid) 4591 return; 4592 4593 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4594 if (ChangesLinkage) { 4595 // If the linkage changes, we can't accept this as an extension. 4596 if (NonCLike.Kind == NonCLikeKind::None) 4597 DiagID = diag::err_typedef_changes_linkage; 4598 else 4599 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4600 } 4601 4602 SourceLocation FixitLoc = 4603 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4604 llvm::SmallString<40> TextToInsert; 4605 TextToInsert += ' '; 4606 TextToInsert += NewTD->getIdentifier()->getName(); 4607 4608 Diag(FixitLoc, DiagID) 4609 << isa<TypeAliasDecl>(NewTD) 4610 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4611 if (NonCLike.Kind != NonCLikeKind::None) { 4612 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4613 << NonCLike.Kind - 1 << NonCLike.Range; 4614 } 4615 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4616 << NewTD << isa<TypeAliasDecl>(NewTD); 4617 4618 if (ChangesLinkage) 4619 return; 4620 } 4621 4622 // Otherwise, set this as the anon-decl typedef for the tag. 4623 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4624 } 4625 4626 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4627 switch (T) { 4628 case DeclSpec::TST_class: 4629 return 0; 4630 case DeclSpec::TST_struct: 4631 return 1; 4632 case DeclSpec::TST_interface: 4633 return 2; 4634 case DeclSpec::TST_union: 4635 return 3; 4636 case DeclSpec::TST_enum: 4637 return 4; 4638 default: 4639 llvm_unreachable("unexpected type specifier"); 4640 } 4641 } 4642 4643 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4644 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4645 /// parameters to cope with template friend declarations. 4646 Decl * 4647 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4648 MultiTemplateParamsArg TemplateParams, 4649 bool IsExplicitInstantiation, 4650 RecordDecl *&AnonRecord) { 4651 Decl *TagD = nullptr; 4652 TagDecl *Tag = nullptr; 4653 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4654 DS.getTypeSpecType() == DeclSpec::TST_struct || 4655 DS.getTypeSpecType() == DeclSpec::TST_interface || 4656 DS.getTypeSpecType() == DeclSpec::TST_union || 4657 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4658 TagD = DS.getRepAsDecl(); 4659 4660 if (!TagD) // We probably had an error 4661 return nullptr; 4662 4663 // Note that the above type specs guarantee that the 4664 // type rep is a Decl, whereas in many of the others 4665 // it's a Type. 4666 if (isa<TagDecl>(TagD)) 4667 Tag = cast<TagDecl>(TagD); 4668 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4669 Tag = CTD->getTemplatedDecl(); 4670 } 4671 4672 if (Tag) { 4673 handleTagNumbering(Tag, S); 4674 Tag->setFreeStanding(); 4675 if (Tag->isInvalidDecl()) 4676 return Tag; 4677 } 4678 4679 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4680 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4681 // or incomplete types shall not be restrict-qualified." 4682 if (TypeQuals & DeclSpec::TQ_restrict) 4683 Diag(DS.getRestrictSpecLoc(), 4684 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4685 << DS.getSourceRange(); 4686 } 4687 4688 if (DS.isInlineSpecified()) 4689 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4690 << getLangOpts().CPlusPlus17; 4691 4692 if (DS.hasConstexprSpecifier()) { 4693 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4694 // and definitions of functions and variables. 4695 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4696 // the declaration of a function or function template 4697 if (Tag) 4698 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4699 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4700 << static_cast<int>(DS.getConstexprSpecifier()); 4701 else 4702 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4703 << static_cast<int>(DS.getConstexprSpecifier()); 4704 // Don't emit warnings after this error. 4705 return TagD; 4706 } 4707 4708 DiagnoseFunctionSpecifiers(DS); 4709 4710 if (DS.isFriendSpecified()) { 4711 // If we're dealing with a decl but not a TagDecl, assume that 4712 // whatever routines created it handled the friendship aspect. 4713 if (TagD && !Tag) 4714 return nullptr; 4715 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4716 } 4717 4718 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4719 bool IsExplicitSpecialization = 4720 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4721 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4722 !IsExplicitInstantiation && !IsExplicitSpecialization && 4723 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4724 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4725 // nested-name-specifier unless it is an explicit instantiation 4726 // or an explicit specialization. 4727 // 4728 // FIXME: We allow class template partial specializations here too, per the 4729 // obvious intent of DR1819. 4730 // 4731 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4732 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4733 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4734 return nullptr; 4735 } 4736 4737 // Track whether this decl-specifier declares anything. 4738 bool DeclaresAnything = true; 4739 4740 // Handle anonymous struct definitions. 4741 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4742 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4743 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4744 if (getLangOpts().CPlusPlus || 4745 Record->getDeclContext()->isRecord()) { 4746 // If CurContext is a DeclContext that can contain statements, 4747 // RecursiveASTVisitor won't visit the decls that 4748 // BuildAnonymousStructOrUnion() will put into CurContext. 4749 // Also store them here so that they can be part of the 4750 // DeclStmt that gets created in this case. 4751 // FIXME: Also return the IndirectFieldDecls created by 4752 // BuildAnonymousStructOr union, for the same reason? 4753 if (CurContext->isFunctionOrMethod()) 4754 AnonRecord = Record; 4755 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4756 Context.getPrintingPolicy()); 4757 } 4758 4759 DeclaresAnything = false; 4760 } 4761 } 4762 4763 // C11 6.7.2.1p2: 4764 // A struct-declaration that does not declare an anonymous structure or 4765 // anonymous union shall contain a struct-declarator-list. 4766 // 4767 // This rule also existed in C89 and C99; the grammar for struct-declaration 4768 // did not permit a struct-declaration without a struct-declarator-list. 4769 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4770 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4771 // Check for Microsoft C extension: anonymous struct/union member. 4772 // Handle 2 kinds of anonymous struct/union: 4773 // struct STRUCT; 4774 // union UNION; 4775 // and 4776 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4777 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4778 if ((Tag && Tag->getDeclName()) || 4779 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4780 RecordDecl *Record = nullptr; 4781 if (Tag) 4782 Record = dyn_cast<RecordDecl>(Tag); 4783 else if (const RecordType *RT = 4784 DS.getRepAsType().get()->getAsStructureType()) 4785 Record = RT->getDecl(); 4786 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4787 Record = UT->getDecl(); 4788 4789 if (Record && getLangOpts().MicrosoftExt) { 4790 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4791 << Record->isUnion() << DS.getSourceRange(); 4792 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4793 } 4794 4795 DeclaresAnything = false; 4796 } 4797 } 4798 4799 // Skip all the checks below if we have a type error. 4800 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4801 (TagD && TagD->isInvalidDecl())) 4802 return TagD; 4803 4804 if (getLangOpts().CPlusPlus && 4805 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4806 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4807 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4808 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4809 DeclaresAnything = false; 4810 4811 if (!DS.isMissingDeclaratorOk()) { 4812 // Customize diagnostic for a typedef missing a name. 4813 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4814 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4815 << DS.getSourceRange(); 4816 else 4817 DeclaresAnything = false; 4818 } 4819 4820 if (DS.isModulePrivateSpecified() && 4821 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4822 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4823 << Tag->getTagKind() 4824 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4825 4826 ActOnDocumentableDecl(TagD); 4827 4828 // C 6.7/2: 4829 // A declaration [...] shall declare at least a declarator [...], a tag, 4830 // or the members of an enumeration. 4831 // C++ [dcl.dcl]p3: 4832 // [If there are no declarators], and except for the declaration of an 4833 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4834 // names into the program, or shall redeclare a name introduced by a 4835 // previous declaration. 4836 if (!DeclaresAnything) { 4837 // In C, we allow this as a (popular) extension / bug. Don't bother 4838 // producing further diagnostics for redundant qualifiers after this. 4839 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4840 ? diag::err_no_declarators 4841 : diag::ext_no_declarators) 4842 << DS.getSourceRange(); 4843 return TagD; 4844 } 4845 4846 // C++ [dcl.stc]p1: 4847 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4848 // init-declarator-list of the declaration shall not be empty. 4849 // C++ [dcl.fct.spec]p1: 4850 // If a cv-qualifier appears in a decl-specifier-seq, the 4851 // init-declarator-list of the declaration shall not be empty. 4852 // 4853 // Spurious qualifiers here appear to be valid in C. 4854 unsigned DiagID = diag::warn_standalone_specifier; 4855 if (getLangOpts().CPlusPlus) 4856 DiagID = diag::ext_standalone_specifier; 4857 4858 // Note that a linkage-specification sets a storage class, but 4859 // 'extern "C" struct foo;' is actually valid and not theoretically 4860 // useless. 4861 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4862 if (SCS == DeclSpec::SCS_mutable) 4863 // Since mutable is not a viable storage class specifier in C, there is 4864 // no reason to treat it as an extension. Instead, diagnose as an error. 4865 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4866 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4867 Diag(DS.getStorageClassSpecLoc(), DiagID) 4868 << DeclSpec::getSpecifierName(SCS); 4869 } 4870 4871 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4872 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4873 << DeclSpec::getSpecifierName(TSCS); 4874 if (DS.getTypeQualifiers()) { 4875 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4876 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4877 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4878 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4879 // Restrict is covered above. 4880 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4881 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4882 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4883 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4884 } 4885 4886 // Warn about ignored type attributes, for example: 4887 // __attribute__((aligned)) struct A; 4888 // Attributes should be placed after tag to apply to type declaration. 4889 if (!DS.getAttributes().empty()) { 4890 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4891 if (TypeSpecType == DeclSpec::TST_class || 4892 TypeSpecType == DeclSpec::TST_struct || 4893 TypeSpecType == DeclSpec::TST_interface || 4894 TypeSpecType == DeclSpec::TST_union || 4895 TypeSpecType == DeclSpec::TST_enum) { 4896 for (const ParsedAttr &AL : DS.getAttributes()) 4897 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4898 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4899 } 4900 } 4901 4902 return TagD; 4903 } 4904 4905 /// We are trying to inject an anonymous member into the given scope; 4906 /// check if there's an existing declaration that can't be overloaded. 4907 /// 4908 /// \return true if this is a forbidden redeclaration 4909 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4910 Scope *S, 4911 DeclContext *Owner, 4912 DeclarationName Name, 4913 SourceLocation NameLoc, 4914 bool IsUnion) { 4915 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4916 Sema::ForVisibleRedeclaration); 4917 if (!SemaRef.LookupName(R, S)) return false; 4918 4919 // Pick a representative declaration. 4920 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4921 assert(PrevDecl && "Expected a non-null Decl"); 4922 4923 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4924 return false; 4925 4926 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4927 << IsUnion << Name; 4928 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4929 4930 return true; 4931 } 4932 4933 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4934 /// anonymous struct or union AnonRecord into the owning context Owner 4935 /// and scope S. This routine will be invoked just after we realize 4936 /// that an unnamed union or struct is actually an anonymous union or 4937 /// struct, e.g., 4938 /// 4939 /// @code 4940 /// union { 4941 /// int i; 4942 /// float f; 4943 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4944 /// // f into the surrounding scope.x 4945 /// @endcode 4946 /// 4947 /// This routine is recursive, injecting the names of nested anonymous 4948 /// structs/unions into the owning context and scope as well. 4949 static bool 4950 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4951 RecordDecl *AnonRecord, AccessSpecifier AS, 4952 SmallVectorImpl<NamedDecl *> &Chaining) { 4953 bool Invalid = false; 4954 4955 // Look every FieldDecl and IndirectFieldDecl with a name. 4956 for (auto *D : AnonRecord->decls()) { 4957 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4958 cast<NamedDecl>(D)->getDeclName()) { 4959 ValueDecl *VD = cast<ValueDecl>(D); 4960 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4961 VD->getLocation(), 4962 AnonRecord->isUnion())) { 4963 // C++ [class.union]p2: 4964 // The names of the members of an anonymous union shall be 4965 // distinct from the names of any other entity in the 4966 // scope in which the anonymous union is declared. 4967 Invalid = true; 4968 } else { 4969 // C++ [class.union]p2: 4970 // For the purpose of name lookup, after the anonymous union 4971 // definition, the members of the anonymous union are 4972 // considered to have been defined in the scope in which the 4973 // anonymous union is declared. 4974 unsigned OldChainingSize = Chaining.size(); 4975 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4976 Chaining.append(IF->chain_begin(), IF->chain_end()); 4977 else 4978 Chaining.push_back(VD); 4979 4980 assert(Chaining.size() >= 2); 4981 NamedDecl **NamedChain = 4982 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4983 for (unsigned i = 0; i < Chaining.size(); i++) 4984 NamedChain[i] = Chaining[i]; 4985 4986 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4987 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4988 VD->getType(), {NamedChain, Chaining.size()}); 4989 4990 for (const auto *Attr : VD->attrs()) 4991 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4992 4993 IndirectField->setAccess(AS); 4994 IndirectField->setImplicit(); 4995 SemaRef.PushOnScopeChains(IndirectField, S); 4996 4997 // That includes picking up the appropriate access specifier. 4998 if (AS != AS_none) IndirectField->setAccess(AS); 4999 5000 Chaining.resize(OldChainingSize); 5001 } 5002 } 5003 } 5004 5005 return Invalid; 5006 } 5007 5008 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5009 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5010 /// illegal input values are mapped to SC_None. 5011 static StorageClass 5012 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5013 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5014 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5015 "Parser allowed 'typedef' as storage class VarDecl."); 5016 switch (StorageClassSpec) { 5017 case DeclSpec::SCS_unspecified: return SC_None; 5018 case DeclSpec::SCS_extern: 5019 if (DS.isExternInLinkageSpec()) 5020 return SC_None; 5021 return SC_Extern; 5022 case DeclSpec::SCS_static: return SC_Static; 5023 case DeclSpec::SCS_auto: return SC_Auto; 5024 case DeclSpec::SCS_register: return SC_Register; 5025 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5026 // Illegal SCSs map to None: error reporting is up to the caller. 5027 case DeclSpec::SCS_mutable: // Fall through. 5028 case DeclSpec::SCS_typedef: return SC_None; 5029 } 5030 llvm_unreachable("unknown storage class specifier"); 5031 } 5032 5033 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5034 assert(Record->hasInClassInitializer()); 5035 5036 for (const auto *I : Record->decls()) { 5037 const auto *FD = dyn_cast<FieldDecl>(I); 5038 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5039 FD = IFD->getAnonField(); 5040 if (FD && FD->hasInClassInitializer()) 5041 return FD->getLocation(); 5042 } 5043 5044 llvm_unreachable("couldn't find in-class initializer"); 5045 } 5046 5047 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5048 SourceLocation DefaultInitLoc) { 5049 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5050 return; 5051 5052 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5053 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5054 } 5055 5056 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5057 CXXRecordDecl *AnonUnion) { 5058 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5059 return; 5060 5061 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5062 } 5063 5064 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5065 /// anonymous structure or union. Anonymous unions are a C++ feature 5066 /// (C++ [class.union]) and a C11 feature; anonymous structures 5067 /// are a C11 feature and GNU C++ extension. 5068 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5069 AccessSpecifier AS, 5070 RecordDecl *Record, 5071 const PrintingPolicy &Policy) { 5072 DeclContext *Owner = Record->getDeclContext(); 5073 5074 // Diagnose whether this anonymous struct/union is an extension. 5075 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5076 Diag(Record->getLocation(), diag::ext_anonymous_union); 5077 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5078 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5079 else if (!Record->isUnion() && !getLangOpts().C11) 5080 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5081 5082 // C and C++ require different kinds of checks for anonymous 5083 // structs/unions. 5084 bool Invalid = false; 5085 if (getLangOpts().CPlusPlus) { 5086 const char *PrevSpec = nullptr; 5087 if (Record->isUnion()) { 5088 // C++ [class.union]p6: 5089 // C++17 [class.union.anon]p2: 5090 // Anonymous unions declared in a named namespace or in the 5091 // global namespace shall be declared static. 5092 unsigned DiagID; 5093 DeclContext *OwnerScope = Owner->getRedeclContext(); 5094 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5095 (OwnerScope->isTranslationUnit() || 5096 (OwnerScope->isNamespace() && 5097 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5098 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5099 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5100 5101 // Recover by adding 'static'. 5102 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5103 PrevSpec, DiagID, Policy); 5104 } 5105 // C++ [class.union]p6: 5106 // A storage class is not allowed in a declaration of an 5107 // anonymous union in a class scope. 5108 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5109 isa<RecordDecl>(Owner)) { 5110 Diag(DS.getStorageClassSpecLoc(), 5111 diag::err_anonymous_union_with_storage_spec) 5112 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5113 5114 // Recover by removing the storage specifier. 5115 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5116 SourceLocation(), 5117 PrevSpec, DiagID, Context.getPrintingPolicy()); 5118 } 5119 } 5120 5121 // Ignore const/volatile/restrict qualifiers. 5122 if (DS.getTypeQualifiers()) { 5123 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5124 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5125 << Record->isUnion() << "const" 5126 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5127 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5128 Diag(DS.getVolatileSpecLoc(), 5129 diag::ext_anonymous_struct_union_qualified) 5130 << Record->isUnion() << "volatile" 5131 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5132 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5133 Diag(DS.getRestrictSpecLoc(), 5134 diag::ext_anonymous_struct_union_qualified) 5135 << Record->isUnion() << "restrict" 5136 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5137 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5138 Diag(DS.getAtomicSpecLoc(), 5139 diag::ext_anonymous_struct_union_qualified) 5140 << Record->isUnion() << "_Atomic" 5141 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5142 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5143 Diag(DS.getUnalignedSpecLoc(), 5144 diag::ext_anonymous_struct_union_qualified) 5145 << Record->isUnion() << "__unaligned" 5146 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5147 5148 DS.ClearTypeQualifiers(); 5149 } 5150 5151 // C++ [class.union]p2: 5152 // The member-specification of an anonymous union shall only 5153 // define non-static data members. [Note: nested types and 5154 // functions cannot be declared within an anonymous union. ] 5155 for (auto *Mem : Record->decls()) { 5156 // Ignore invalid declarations; we already diagnosed them. 5157 if (Mem->isInvalidDecl()) 5158 continue; 5159 5160 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5161 // C++ [class.union]p3: 5162 // An anonymous union shall not have private or protected 5163 // members (clause 11). 5164 assert(FD->getAccess() != AS_none); 5165 if (FD->getAccess() != AS_public) { 5166 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5167 << Record->isUnion() << (FD->getAccess() == AS_protected); 5168 Invalid = true; 5169 } 5170 5171 // C++ [class.union]p1 5172 // An object of a class with a non-trivial constructor, a non-trivial 5173 // copy constructor, a non-trivial destructor, or a non-trivial copy 5174 // assignment operator cannot be a member of a union, nor can an 5175 // array of such objects. 5176 if (CheckNontrivialField(FD)) 5177 Invalid = true; 5178 } else if (Mem->isImplicit()) { 5179 // Any implicit members are fine. 5180 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5181 // This is a type that showed up in an 5182 // elaborated-type-specifier inside the anonymous struct or 5183 // union, but which actually declares a type outside of the 5184 // anonymous struct or union. It's okay. 5185 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5186 if (!MemRecord->isAnonymousStructOrUnion() && 5187 MemRecord->getDeclName()) { 5188 // Visual C++ allows type definition in anonymous struct or union. 5189 if (getLangOpts().MicrosoftExt) 5190 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5191 << Record->isUnion(); 5192 else { 5193 // This is a nested type declaration. 5194 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5195 << Record->isUnion(); 5196 Invalid = true; 5197 } 5198 } else { 5199 // This is an anonymous type definition within another anonymous type. 5200 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5201 // not part of standard C++. 5202 Diag(MemRecord->getLocation(), 5203 diag::ext_anonymous_record_with_anonymous_type) 5204 << Record->isUnion(); 5205 } 5206 } else if (isa<AccessSpecDecl>(Mem)) { 5207 // Any access specifier is fine. 5208 } else if (isa<StaticAssertDecl>(Mem)) { 5209 // In C++1z, static_assert declarations are also fine. 5210 } else { 5211 // We have something that isn't a non-static data 5212 // member. Complain about it. 5213 unsigned DK = diag::err_anonymous_record_bad_member; 5214 if (isa<TypeDecl>(Mem)) 5215 DK = diag::err_anonymous_record_with_type; 5216 else if (isa<FunctionDecl>(Mem)) 5217 DK = diag::err_anonymous_record_with_function; 5218 else if (isa<VarDecl>(Mem)) 5219 DK = diag::err_anonymous_record_with_static; 5220 5221 // Visual C++ allows type definition in anonymous struct or union. 5222 if (getLangOpts().MicrosoftExt && 5223 DK == diag::err_anonymous_record_with_type) 5224 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5225 << Record->isUnion(); 5226 else { 5227 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5228 Invalid = true; 5229 } 5230 } 5231 } 5232 5233 // C++11 [class.union]p8 (DR1460): 5234 // At most one variant member of a union may have a 5235 // brace-or-equal-initializer. 5236 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5237 Owner->isRecord()) 5238 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5239 cast<CXXRecordDecl>(Record)); 5240 } 5241 5242 if (!Record->isUnion() && !Owner->isRecord()) { 5243 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5244 << getLangOpts().CPlusPlus; 5245 Invalid = true; 5246 } 5247 5248 // C++ [dcl.dcl]p3: 5249 // [If there are no declarators], and except for the declaration of an 5250 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5251 // names into the program 5252 // C++ [class.mem]p2: 5253 // each such member-declaration shall either declare at least one member 5254 // name of the class or declare at least one unnamed bit-field 5255 // 5256 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5257 if (getLangOpts().CPlusPlus && Record->field_empty()) 5258 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5259 5260 // Mock up a declarator. 5261 Declarator Dc(DS, DeclaratorContext::Member); 5262 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5263 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5264 5265 // Create a declaration for this anonymous struct/union. 5266 NamedDecl *Anon = nullptr; 5267 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5268 Anon = FieldDecl::Create( 5269 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5270 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5271 /*BitWidth=*/nullptr, /*Mutable=*/false, 5272 /*InitStyle=*/ICIS_NoInit); 5273 Anon->setAccess(AS); 5274 ProcessDeclAttributes(S, Anon, Dc); 5275 5276 if (getLangOpts().CPlusPlus) 5277 FieldCollector->Add(cast<FieldDecl>(Anon)); 5278 } else { 5279 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5280 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5281 if (SCSpec == DeclSpec::SCS_mutable) { 5282 // mutable can only appear on non-static class members, so it's always 5283 // an error here 5284 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5285 Invalid = true; 5286 SC = SC_None; 5287 } 5288 5289 assert(DS.getAttributes().empty() && "No attribute expected"); 5290 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5291 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5292 Context.getTypeDeclType(Record), TInfo, SC); 5293 5294 // Default-initialize the implicit variable. This initialization will be 5295 // trivial in almost all cases, except if a union member has an in-class 5296 // initializer: 5297 // union { int n = 0; }; 5298 if (!Invalid) 5299 ActOnUninitializedDecl(Anon); 5300 } 5301 Anon->setImplicit(); 5302 5303 // Mark this as an anonymous struct/union type. 5304 Record->setAnonymousStructOrUnion(true); 5305 5306 // Add the anonymous struct/union object to the current 5307 // context. We'll be referencing this object when we refer to one of 5308 // its members. 5309 Owner->addDecl(Anon); 5310 5311 // Inject the members of the anonymous struct/union into the owning 5312 // context and into the identifier resolver chain for name lookup 5313 // purposes. 5314 SmallVector<NamedDecl*, 2> Chain; 5315 Chain.push_back(Anon); 5316 5317 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5318 Invalid = true; 5319 5320 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5321 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5322 MangleNumberingContext *MCtx; 5323 Decl *ManglingContextDecl; 5324 std::tie(MCtx, ManglingContextDecl) = 5325 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5326 if (MCtx) { 5327 Context.setManglingNumber( 5328 NewVD, MCtx->getManglingNumber( 5329 NewVD, getMSManglingNumber(getLangOpts(), S))); 5330 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5331 } 5332 } 5333 } 5334 5335 if (Invalid) 5336 Anon->setInvalidDecl(); 5337 5338 return Anon; 5339 } 5340 5341 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5342 /// Microsoft C anonymous structure. 5343 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5344 /// Example: 5345 /// 5346 /// struct A { int a; }; 5347 /// struct B { struct A; int b; }; 5348 /// 5349 /// void foo() { 5350 /// B var; 5351 /// var.a = 3; 5352 /// } 5353 /// 5354 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5355 RecordDecl *Record) { 5356 assert(Record && "expected a record!"); 5357 5358 // Mock up a declarator. 5359 Declarator Dc(DS, DeclaratorContext::TypeName); 5360 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5361 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5362 5363 auto *ParentDecl = cast<RecordDecl>(CurContext); 5364 QualType RecTy = Context.getTypeDeclType(Record); 5365 5366 // Create a declaration for this anonymous struct. 5367 NamedDecl *Anon = 5368 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5369 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5370 /*BitWidth=*/nullptr, /*Mutable=*/false, 5371 /*InitStyle=*/ICIS_NoInit); 5372 Anon->setImplicit(); 5373 5374 // Add the anonymous struct object to the current context. 5375 CurContext->addDecl(Anon); 5376 5377 // Inject the members of the anonymous struct into the current 5378 // context and into the identifier resolver chain for name lookup 5379 // purposes. 5380 SmallVector<NamedDecl*, 2> Chain; 5381 Chain.push_back(Anon); 5382 5383 RecordDecl *RecordDef = Record->getDefinition(); 5384 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5385 diag::err_field_incomplete_or_sizeless) || 5386 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5387 AS_none, Chain)) { 5388 Anon->setInvalidDecl(); 5389 ParentDecl->setInvalidDecl(); 5390 } 5391 5392 return Anon; 5393 } 5394 5395 /// GetNameForDeclarator - Determine the full declaration name for the 5396 /// given Declarator. 5397 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5398 return GetNameFromUnqualifiedId(D.getName()); 5399 } 5400 5401 /// Retrieves the declaration name from a parsed unqualified-id. 5402 DeclarationNameInfo 5403 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5404 DeclarationNameInfo NameInfo; 5405 NameInfo.setLoc(Name.StartLocation); 5406 5407 switch (Name.getKind()) { 5408 5409 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5410 case UnqualifiedIdKind::IK_Identifier: 5411 NameInfo.setName(Name.Identifier); 5412 return NameInfo; 5413 5414 case UnqualifiedIdKind::IK_DeductionGuideName: { 5415 // C++ [temp.deduct.guide]p3: 5416 // The simple-template-id shall name a class template specialization. 5417 // The template-name shall be the same identifier as the template-name 5418 // of the simple-template-id. 5419 // These together intend to imply that the template-name shall name a 5420 // class template. 5421 // FIXME: template<typename T> struct X {}; 5422 // template<typename T> using Y = X<T>; 5423 // Y(int) -> Y<int>; 5424 // satisfies these rules but does not name a class template. 5425 TemplateName TN = Name.TemplateName.get().get(); 5426 auto *Template = TN.getAsTemplateDecl(); 5427 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5428 Diag(Name.StartLocation, 5429 diag::err_deduction_guide_name_not_class_template) 5430 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5431 if (Template) 5432 Diag(Template->getLocation(), diag::note_template_decl_here); 5433 return DeclarationNameInfo(); 5434 } 5435 5436 NameInfo.setName( 5437 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5438 return NameInfo; 5439 } 5440 5441 case UnqualifiedIdKind::IK_OperatorFunctionId: 5442 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5443 Name.OperatorFunctionId.Operator)); 5444 NameInfo.setCXXOperatorNameRange(SourceRange( 5445 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5446 return NameInfo; 5447 5448 case UnqualifiedIdKind::IK_LiteralOperatorId: 5449 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5450 Name.Identifier)); 5451 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5452 return NameInfo; 5453 5454 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5455 TypeSourceInfo *TInfo; 5456 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5457 if (Ty.isNull()) 5458 return DeclarationNameInfo(); 5459 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5460 Context.getCanonicalType(Ty))); 5461 NameInfo.setNamedTypeInfo(TInfo); 5462 return NameInfo; 5463 } 5464 5465 case UnqualifiedIdKind::IK_ConstructorName: { 5466 TypeSourceInfo *TInfo; 5467 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5468 if (Ty.isNull()) 5469 return DeclarationNameInfo(); 5470 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5471 Context.getCanonicalType(Ty))); 5472 NameInfo.setNamedTypeInfo(TInfo); 5473 return NameInfo; 5474 } 5475 5476 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5477 // In well-formed code, we can only have a constructor 5478 // template-id that refers to the current context, so go there 5479 // to find the actual type being constructed. 5480 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5481 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5482 return DeclarationNameInfo(); 5483 5484 // Determine the type of the class being constructed. 5485 QualType CurClassType = Context.getTypeDeclType(CurClass); 5486 5487 // FIXME: Check two things: that the template-id names the same type as 5488 // CurClassType, and that the template-id does not occur when the name 5489 // was qualified. 5490 5491 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5492 Context.getCanonicalType(CurClassType))); 5493 // FIXME: should we retrieve TypeSourceInfo? 5494 NameInfo.setNamedTypeInfo(nullptr); 5495 return NameInfo; 5496 } 5497 5498 case UnqualifiedIdKind::IK_DestructorName: { 5499 TypeSourceInfo *TInfo; 5500 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5501 if (Ty.isNull()) 5502 return DeclarationNameInfo(); 5503 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5504 Context.getCanonicalType(Ty))); 5505 NameInfo.setNamedTypeInfo(TInfo); 5506 return NameInfo; 5507 } 5508 5509 case UnqualifiedIdKind::IK_TemplateId: { 5510 TemplateName TName = Name.TemplateId->Template.get(); 5511 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5512 return Context.getNameForTemplate(TName, TNameLoc); 5513 } 5514 5515 } // switch (Name.getKind()) 5516 5517 llvm_unreachable("Unknown name kind"); 5518 } 5519 5520 static QualType getCoreType(QualType Ty) { 5521 do { 5522 if (Ty->isPointerType() || Ty->isReferenceType()) 5523 Ty = Ty->getPointeeType(); 5524 else if (Ty->isArrayType()) 5525 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5526 else 5527 return Ty.withoutLocalFastQualifiers(); 5528 } while (true); 5529 } 5530 5531 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5532 /// and Definition have "nearly" matching parameters. This heuristic is 5533 /// used to improve diagnostics in the case where an out-of-line function 5534 /// definition doesn't match any declaration within the class or namespace. 5535 /// Also sets Params to the list of indices to the parameters that differ 5536 /// between the declaration and the definition. If hasSimilarParameters 5537 /// returns true and Params is empty, then all of the parameters match. 5538 static bool hasSimilarParameters(ASTContext &Context, 5539 FunctionDecl *Declaration, 5540 FunctionDecl *Definition, 5541 SmallVectorImpl<unsigned> &Params) { 5542 Params.clear(); 5543 if (Declaration->param_size() != Definition->param_size()) 5544 return false; 5545 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5546 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5547 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5548 5549 // The parameter types are identical 5550 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5551 continue; 5552 5553 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5554 QualType DefParamBaseTy = getCoreType(DefParamTy); 5555 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5556 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5557 5558 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5559 (DeclTyName && DeclTyName == DefTyName)) 5560 Params.push_back(Idx); 5561 else // The two parameters aren't even close 5562 return false; 5563 } 5564 5565 return true; 5566 } 5567 5568 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5569 /// declarator needs to be rebuilt in the current instantiation. 5570 /// Any bits of declarator which appear before the name are valid for 5571 /// consideration here. That's specifically the type in the decl spec 5572 /// and the base type in any member-pointer chunks. 5573 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5574 DeclarationName Name) { 5575 // The types we specifically need to rebuild are: 5576 // - typenames, typeofs, and decltypes 5577 // - types which will become injected class names 5578 // Of course, we also need to rebuild any type referencing such a 5579 // type. It's safest to just say "dependent", but we call out a 5580 // few cases here. 5581 5582 DeclSpec &DS = D.getMutableDeclSpec(); 5583 switch (DS.getTypeSpecType()) { 5584 case DeclSpec::TST_typename: 5585 case DeclSpec::TST_typeofType: 5586 case DeclSpec::TST_underlyingType: 5587 case DeclSpec::TST_atomic: { 5588 // Grab the type from the parser. 5589 TypeSourceInfo *TSI = nullptr; 5590 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5591 if (T.isNull() || !T->isInstantiationDependentType()) break; 5592 5593 // Make sure there's a type source info. This isn't really much 5594 // of a waste; most dependent types should have type source info 5595 // attached already. 5596 if (!TSI) 5597 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5598 5599 // Rebuild the type in the current instantiation. 5600 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5601 if (!TSI) return true; 5602 5603 // Store the new type back in the decl spec. 5604 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5605 DS.UpdateTypeRep(LocType); 5606 break; 5607 } 5608 5609 case DeclSpec::TST_decltype: 5610 case DeclSpec::TST_typeofExpr: { 5611 Expr *E = DS.getRepAsExpr(); 5612 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5613 if (Result.isInvalid()) return true; 5614 DS.UpdateExprRep(Result.get()); 5615 break; 5616 } 5617 5618 default: 5619 // Nothing to do for these decl specs. 5620 break; 5621 } 5622 5623 // It doesn't matter what order we do this in. 5624 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5625 DeclaratorChunk &Chunk = D.getTypeObject(I); 5626 5627 // The only type information in the declarator which can come 5628 // before the declaration name is the base type of a member 5629 // pointer. 5630 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5631 continue; 5632 5633 // Rebuild the scope specifier in-place. 5634 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5635 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5636 return true; 5637 } 5638 5639 return false; 5640 } 5641 5642 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5643 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5644 // of system decl. 5645 if (D->getPreviousDecl() || D->isImplicit()) 5646 return; 5647 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5648 if (Status != ReservedIdentifierStatus::NotReserved && 5649 !Context.getSourceManager().isInSystemHeader(D->getLocation())) 5650 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5651 << D << static_cast<int>(Status); 5652 } 5653 5654 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5655 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5656 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5657 5658 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5659 Dcl && Dcl->getDeclContext()->isFileContext()) 5660 Dcl->setTopLevelDeclInObjCContainer(); 5661 5662 return Dcl; 5663 } 5664 5665 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5666 /// If T is the name of a class, then each of the following shall have a 5667 /// name different from T: 5668 /// - every static data member of class T; 5669 /// - every member function of class T 5670 /// - every member of class T that is itself a type; 5671 /// \returns true if the declaration name violates these rules. 5672 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5673 DeclarationNameInfo NameInfo) { 5674 DeclarationName Name = NameInfo.getName(); 5675 5676 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5677 while (Record && Record->isAnonymousStructOrUnion()) 5678 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5679 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5680 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5681 return true; 5682 } 5683 5684 return false; 5685 } 5686 5687 /// Diagnose a declaration whose declarator-id has the given 5688 /// nested-name-specifier. 5689 /// 5690 /// \param SS The nested-name-specifier of the declarator-id. 5691 /// 5692 /// \param DC The declaration context to which the nested-name-specifier 5693 /// resolves. 5694 /// 5695 /// \param Name The name of the entity being declared. 5696 /// 5697 /// \param Loc The location of the name of the entity being declared. 5698 /// 5699 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5700 /// we're declaring an explicit / partial specialization / instantiation. 5701 /// 5702 /// \returns true if we cannot safely recover from this error, false otherwise. 5703 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5704 DeclarationName Name, 5705 SourceLocation Loc, bool IsTemplateId) { 5706 DeclContext *Cur = CurContext; 5707 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5708 Cur = Cur->getParent(); 5709 5710 // If the user provided a superfluous scope specifier that refers back to the 5711 // class in which the entity is already declared, diagnose and ignore it. 5712 // 5713 // class X { 5714 // void X::f(); 5715 // }; 5716 // 5717 // Note, it was once ill-formed to give redundant qualification in all 5718 // contexts, but that rule was removed by DR482. 5719 if (Cur->Equals(DC)) { 5720 if (Cur->isRecord()) { 5721 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5722 : diag::err_member_extra_qualification) 5723 << Name << FixItHint::CreateRemoval(SS.getRange()); 5724 SS.clear(); 5725 } else { 5726 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5727 } 5728 return false; 5729 } 5730 5731 // Check whether the qualifying scope encloses the scope of the original 5732 // declaration. For a template-id, we perform the checks in 5733 // CheckTemplateSpecializationScope. 5734 if (!Cur->Encloses(DC) && !IsTemplateId) { 5735 if (Cur->isRecord()) 5736 Diag(Loc, diag::err_member_qualification) 5737 << Name << SS.getRange(); 5738 else if (isa<TranslationUnitDecl>(DC)) 5739 Diag(Loc, diag::err_invalid_declarator_global_scope) 5740 << Name << SS.getRange(); 5741 else if (isa<FunctionDecl>(Cur)) 5742 Diag(Loc, diag::err_invalid_declarator_in_function) 5743 << Name << SS.getRange(); 5744 else if (isa<BlockDecl>(Cur)) 5745 Diag(Loc, diag::err_invalid_declarator_in_block) 5746 << Name << SS.getRange(); 5747 else 5748 Diag(Loc, diag::err_invalid_declarator_scope) 5749 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5750 5751 return true; 5752 } 5753 5754 if (Cur->isRecord()) { 5755 // Cannot qualify members within a class. 5756 Diag(Loc, diag::err_member_qualification) 5757 << Name << SS.getRange(); 5758 SS.clear(); 5759 5760 // C++ constructors and destructors with incorrect scopes can break 5761 // our AST invariants by having the wrong underlying types. If 5762 // that's the case, then drop this declaration entirely. 5763 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5764 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5765 !Context.hasSameType(Name.getCXXNameType(), 5766 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5767 return true; 5768 5769 return false; 5770 } 5771 5772 // C++11 [dcl.meaning]p1: 5773 // [...] "The nested-name-specifier of the qualified declarator-id shall 5774 // not begin with a decltype-specifer" 5775 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5776 while (SpecLoc.getPrefix()) 5777 SpecLoc = SpecLoc.getPrefix(); 5778 if (dyn_cast_or_null<DecltypeType>( 5779 SpecLoc.getNestedNameSpecifier()->getAsType())) 5780 Diag(Loc, diag::err_decltype_in_declarator) 5781 << SpecLoc.getTypeLoc().getSourceRange(); 5782 5783 return false; 5784 } 5785 5786 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5787 MultiTemplateParamsArg TemplateParamLists) { 5788 // TODO: consider using NameInfo for diagnostic. 5789 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5790 DeclarationName Name = NameInfo.getName(); 5791 5792 // All of these full declarators require an identifier. If it doesn't have 5793 // one, the ParsedFreeStandingDeclSpec action should be used. 5794 if (D.isDecompositionDeclarator()) { 5795 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5796 } else if (!Name) { 5797 if (!D.isInvalidType()) // Reject this if we think it is valid. 5798 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5799 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5800 return nullptr; 5801 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5802 return nullptr; 5803 5804 // The scope passed in may not be a decl scope. Zip up the scope tree until 5805 // we find one that is. 5806 while ((S->getFlags() & Scope::DeclScope) == 0 || 5807 (S->getFlags() & Scope::TemplateParamScope) != 0) 5808 S = S->getParent(); 5809 5810 DeclContext *DC = CurContext; 5811 if (D.getCXXScopeSpec().isInvalid()) 5812 D.setInvalidType(); 5813 else if (D.getCXXScopeSpec().isSet()) { 5814 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5815 UPPC_DeclarationQualifier)) 5816 return nullptr; 5817 5818 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5819 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5820 if (!DC || isa<EnumDecl>(DC)) { 5821 // If we could not compute the declaration context, it's because the 5822 // declaration context is dependent but does not refer to a class, 5823 // class template, or class template partial specialization. Complain 5824 // and return early, to avoid the coming semantic disaster. 5825 Diag(D.getIdentifierLoc(), 5826 diag::err_template_qualified_declarator_no_match) 5827 << D.getCXXScopeSpec().getScopeRep() 5828 << D.getCXXScopeSpec().getRange(); 5829 return nullptr; 5830 } 5831 bool IsDependentContext = DC->isDependentContext(); 5832 5833 if (!IsDependentContext && 5834 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5835 return nullptr; 5836 5837 // If a class is incomplete, do not parse entities inside it. 5838 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5839 Diag(D.getIdentifierLoc(), 5840 diag::err_member_def_undefined_record) 5841 << Name << DC << D.getCXXScopeSpec().getRange(); 5842 return nullptr; 5843 } 5844 if (!D.getDeclSpec().isFriendSpecified()) { 5845 if (diagnoseQualifiedDeclaration( 5846 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5847 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5848 if (DC->isRecord()) 5849 return nullptr; 5850 5851 D.setInvalidType(); 5852 } 5853 } 5854 5855 // Check whether we need to rebuild the type of the given 5856 // declaration in the current instantiation. 5857 if (EnteringContext && IsDependentContext && 5858 TemplateParamLists.size() != 0) { 5859 ContextRAII SavedContext(*this, DC); 5860 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5861 D.setInvalidType(); 5862 } 5863 } 5864 5865 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5866 QualType R = TInfo->getType(); 5867 5868 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5869 UPPC_DeclarationType)) 5870 D.setInvalidType(); 5871 5872 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5873 forRedeclarationInCurContext()); 5874 5875 // See if this is a redefinition of a variable in the same scope. 5876 if (!D.getCXXScopeSpec().isSet()) { 5877 bool IsLinkageLookup = false; 5878 bool CreateBuiltins = false; 5879 5880 // If the declaration we're planning to build will be a function 5881 // or object with linkage, then look for another declaration with 5882 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5883 // 5884 // If the declaration we're planning to build will be declared with 5885 // external linkage in the translation unit, create any builtin with 5886 // the same name. 5887 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5888 /* Do nothing*/; 5889 else if (CurContext->isFunctionOrMethod() && 5890 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5891 R->isFunctionType())) { 5892 IsLinkageLookup = true; 5893 CreateBuiltins = 5894 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5895 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5896 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5897 CreateBuiltins = true; 5898 5899 if (IsLinkageLookup) { 5900 Previous.clear(LookupRedeclarationWithLinkage); 5901 Previous.setRedeclarationKind(ForExternalRedeclaration); 5902 } 5903 5904 LookupName(Previous, S, CreateBuiltins); 5905 } else { // Something like "int foo::x;" 5906 LookupQualifiedName(Previous, DC); 5907 5908 // C++ [dcl.meaning]p1: 5909 // When the declarator-id is qualified, the declaration shall refer to a 5910 // previously declared member of the class or namespace to which the 5911 // qualifier refers (or, in the case of a namespace, of an element of the 5912 // inline namespace set of that namespace (7.3.1)) or to a specialization 5913 // thereof; [...] 5914 // 5915 // Note that we already checked the context above, and that we do not have 5916 // enough information to make sure that Previous contains the declaration 5917 // we want to match. For example, given: 5918 // 5919 // class X { 5920 // void f(); 5921 // void f(float); 5922 // }; 5923 // 5924 // void X::f(int) { } // ill-formed 5925 // 5926 // In this case, Previous will point to the overload set 5927 // containing the two f's declared in X, but neither of them 5928 // matches. 5929 5930 // C++ [dcl.meaning]p1: 5931 // [...] the member shall not merely have been introduced by a 5932 // using-declaration in the scope of the class or namespace nominated by 5933 // the nested-name-specifier of the declarator-id. 5934 RemoveUsingDecls(Previous); 5935 } 5936 5937 if (Previous.isSingleResult() && 5938 Previous.getFoundDecl()->isTemplateParameter()) { 5939 // Maybe we will complain about the shadowed template parameter. 5940 if (!D.isInvalidType()) 5941 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5942 Previous.getFoundDecl()); 5943 5944 // Just pretend that we didn't see the previous declaration. 5945 Previous.clear(); 5946 } 5947 5948 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5949 // Forget that the previous declaration is the injected-class-name. 5950 Previous.clear(); 5951 5952 // In C++, the previous declaration we find might be a tag type 5953 // (class or enum). In this case, the new declaration will hide the 5954 // tag type. Note that this applies to functions, function templates, and 5955 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5956 if (Previous.isSingleTagDecl() && 5957 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5958 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5959 Previous.clear(); 5960 5961 // Check that there are no default arguments other than in the parameters 5962 // of a function declaration (C++ only). 5963 if (getLangOpts().CPlusPlus) 5964 CheckExtraCXXDefaultArguments(D); 5965 5966 NamedDecl *New; 5967 5968 bool AddToScope = true; 5969 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5970 if (TemplateParamLists.size()) { 5971 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5972 return nullptr; 5973 } 5974 5975 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5976 } else if (R->isFunctionType()) { 5977 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5978 TemplateParamLists, 5979 AddToScope); 5980 } else { 5981 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5982 AddToScope); 5983 } 5984 5985 if (!New) 5986 return nullptr; 5987 5988 // If this has an identifier and is not a function template specialization, 5989 // add it to the scope stack. 5990 if (New->getDeclName() && AddToScope) 5991 PushOnScopeChains(New, S); 5992 5993 if (isInOpenMPDeclareTargetContext()) 5994 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5995 5996 return New; 5997 } 5998 5999 /// Helper method to turn variable array types into constant array 6000 /// types in certain situations which would otherwise be errors (for 6001 /// GCC compatibility). 6002 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6003 ASTContext &Context, 6004 bool &SizeIsNegative, 6005 llvm::APSInt &Oversized) { 6006 // This method tries to turn a variable array into a constant 6007 // array even when the size isn't an ICE. This is necessary 6008 // for compatibility with code that depends on gcc's buggy 6009 // constant expression folding, like struct {char x[(int)(char*)2];} 6010 SizeIsNegative = false; 6011 Oversized = 0; 6012 6013 if (T->isDependentType()) 6014 return QualType(); 6015 6016 QualifierCollector Qs; 6017 const Type *Ty = Qs.strip(T); 6018 6019 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6020 QualType Pointee = PTy->getPointeeType(); 6021 QualType FixedType = 6022 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6023 Oversized); 6024 if (FixedType.isNull()) return FixedType; 6025 FixedType = Context.getPointerType(FixedType); 6026 return Qs.apply(Context, FixedType); 6027 } 6028 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6029 QualType Inner = PTy->getInnerType(); 6030 QualType FixedType = 6031 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6032 Oversized); 6033 if (FixedType.isNull()) return FixedType; 6034 FixedType = Context.getParenType(FixedType); 6035 return Qs.apply(Context, FixedType); 6036 } 6037 6038 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6039 if (!VLATy) 6040 return QualType(); 6041 6042 QualType ElemTy = VLATy->getElementType(); 6043 if (ElemTy->isVariablyModifiedType()) { 6044 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6045 SizeIsNegative, Oversized); 6046 if (ElemTy.isNull()) 6047 return QualType(); 6048 } 6049 6050 Expr::EvalResult Result; 6051 if (!VLATy->getSizeExpr() || 6052 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6053 return QualType(); 6054 6055 llvm::APSInt Res = Result.Val.getInt(); 6056 6057 // Check whether the array size is negative. 6058 if (Res.isSigned() && Res.isNegative()) { 6059 SizeIsNegative = true; 6060 return QualType(); 6061 } 6062 6063 // Check whether the array is too large to be addressed. 6064 unsigned ActiveSizeBits = 6065 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6066 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6067 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6068 : Res.getActiveBits(); 6069 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6070 Oversized = Res; 6071 return QualType(); 6072 } 6073 6074 QualType FoldedArrayType = Context.getConstantArrayType( 6075 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6076 return Qs.apply(Context, FoldedArrayType); 6077 } 6078 6079 static void 6080 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6081 SrcTL = SrcTL.getUnqualifiedLoc(); 6082 DstTL = DstTL.getUnqualifiedLoc(); 6083 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6084 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6085 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6086 DstPTL.getPointeeLoc()); 6087 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6088 return; 6089 } 6090 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6091 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6092 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6093 DstPTL.getInnerLoc()); 6094 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6095 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6096 return; 6097 } 6098 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6099 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6100 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6101 TypeLoc DstElemTL = DstATL.getElementLoc(); 6102 if (VariableArrayTypeLoc SrcElemATL = 6103 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6104 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6105 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6106 } else { 6107 DstElemTL.initializeFullCopy(SrcElemTL); 6108 } 6109 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6110 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6111 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6112 } 6113 6114 /// Helper method to turn variable array types into constant array 6115 /// types in certain situations which would otherwise be errors (for 6116 /// GCC compatibility). 6117 static TypeSourceInfo* 6118 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6119 ASTContext &Context, 6120 bool &SizeIsNegative, 6121 llvm::APSInt &Oversized) { 6122 QualType FixedTy 6123 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6124 SizeIsNegative, Oversized); 6125 if (FixedTy.isNull()) 6126 return nullptr; 6127 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6128 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6129 FixedTInfo->getTypeLoc()); 6130 return FixedTInfo; 6131 } 6132 6133 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6134 /// true if we were successful. 6135 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6136 QualType &T, SourceLocation Loc, 6137 unsigned FailedFoldDiagID) { 6138 bool SizeIsNegative; 6139 llvm::APSInt Oversized; 6140 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6141 TInfo, Context, SizeIsNegative, Oversized); 6142 if (FixedTInfo) { 6143 Diag(Loc, diag::ext_vla_folded_to_constant); 6144 TInfo = FixedTInfo; 6145 T = FixedTInfo->getType(); 6146 return true; 6147 } 6148 6149 if (SizeIsNegative) 6150 Diag(Loc, diag::err_typecheck_negative_array_size); 6151 else if (Oversized.getBoolValue()) 6152 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6153 else if (FailedFoldDiagID) 6154 Diag(Loc, FailedFoldDiagID); 6155 return false; 6156 } 6157 6158 /// Register the given locally-scoped extern "C" declaration so 6159 /// that it can be found later for redeclarations. We include any extern "C" 6160 /// declaration that is not visible in the translation unit here, not just 6161 /// function-scope declarations. 6162 void 6163 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6164 if (!getLangOpts().CPlusPlus && 6165 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6166 // Don't need to track declarations in the TU in C. 6167 return; 6168 6169 // Note that we have a locally-scoped external with this name. 6170 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6171 } 6172 6173 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6174 // FIXME: We can have multiple results via __attribute__((overloadable)). 6175 auto Result = Context.getExternCContextDecl()->lookup(Name); 6176 return Result.empty() ? nullptr : *Result.begin(); 6177 } 6178 6179 /// Diagnose function specifiers on a declaration of an identifier that 6180 /// does not identify a function. 6181 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6182 // FIXME: We should probably indicate the identifier in question to avoid 6183 // confusion for constructs like "virtual int a(), b;" 6184 if (DS.isVirtualSpecified()) 6185 Diag(DS.getVirtualSpecLoc(), 6186 diag::err_virtual_non_function); 6187 6188 if (DS.hasExplicitSpecifier()) 6189 Diag(DS.getExplicitSpecLoc(), 6190 diag::err_explicit_non_function); 6191 6192 if (DS.isNoreturnSpecified()) 6193 Diag(DS.getNoreturnSpecLoc(), 6194 diag::err_noreturn_non_function); 6195 } 6196 6197 NamedDecl* 6198 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6199 TypeSourceInfo *TInfo, LookupResult &Previous) { 6200 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6201 if (D.getCXXScopeSpec().isSet()) { 6202 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6203 << D.getCXXScopeSpec().getRange(); 6204 D.setInvalidType(); 6205 // Pretend we didn't see the scope specifier. 6206 DC = CurContext; 6207 Previous.clear(); 6208 } 6209 6210 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6211 6212 if (D.getDeclSpec().isInlineSpecified()) 6213 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6214 << getLangOpts().CPlusPlus17; 6215 if (D.getDeclSpec().hasConstexprSpecifier()) 6216 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6217 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6218 6219 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6220 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6221 Diag(D.getName().StartLocation, 6222 diag::err_deduction_guide_invalid_specifier) 6223 << "typedef"; 6224 else 6225 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6226 << D.getName().getSourceRange(); 6227 return nullptr; 6228 } 6229 6230 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6231 if (!NewTD) return nullptr; 6232 6233 // Handle attributes prior to checking for duplicates in MergeVarDecl 6234 ProcessDeclAttributes(S, NewTD, D); 6235 6236 CheckTypedefForVariablyModifiedType(S, NewTD); 6237 6238 bool Redeclaration = D.isRedeclaration(); 6239 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6240 D.setRedeclaration(Redeclaration); 6241 return ND; 6242 } 6243 6244 void 6245 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6246 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6247 // then it shall have block scope. 6248 // Note that variably modified types must be fixed before merging the decl so 6249 // that redeclarations will match. 6250 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6251 QualType T = TInfo->getType(); 6252 if (T->isVariablyModifiedType()) { 6253 setFunctionHasBranchProtectedScope(); 6254 6255 if (S->getFnParent() == nullptr) { 6256 bool SizeIsNegative; 6257 llvm::APSInt Oversized; 6258 TypeSourceInfo *FixedTInfo = 6259 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6260 SizeIsNegative, 6261 Oversized); 6262 if (FixedTInfo) { 6263 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6264 NewTD->setTypeSourceInfo(FixedTInfo); 6265 } else { 6266 if (SizeIsNegative) 6267 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6268 else if (T->isVariableArrayType()) 6269 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6270 else if (Oversized.getBoolValue()) 6271 Diag(NewTD->getLocation(), diag::err_array_too_large) 6272 << toString(Oversized, 10); 6273 else 6274 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6275 NewTD->setInvalidDecl(); 6276 } 6277 } 6278 } 6279 } 6280 6281 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6282 /// declares a typedef-name, either using the 'typedef' type specifier or via 6283 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6284 NamedDecl* 6285 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6286 LookupResult &Previous, bool &Redeclaration) { 6287 6288 // Find the shadowed declaration before filtering for scope. 6289 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6290 6291 // Merge the decl with the existing one if appropriate. If the decl is 6292 // in an outer scope, it isn't the same thing. 6293 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6294 /*AllowInlineNamespace*/false); 6295 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6296 if (!Previous.empty()) { 6297 Redeclaration = true; 6298 MergeTypedefNameDecl(S, NewTD, Previous); 6299 } else { 6300 inferGslPointerAttribute(NewTD); 6301 } 6302 6303 if (ShadowedDecl && !Redeclaration) 6304 CheckShadow(NewTD, ShadowedDecl, Previous); 6305 6306 // If this is the C FILE type, notify the AST context. 6307 if (IdentifierInfo *II = NewTD->getIdentifier()) 6308 if (!NewTD->isInvalidDecl() && 6309 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6310 if (II->isStr("FILE")) 6311 Context.setFILEDecl(NewTD); 6312 else if (II->isStr("jmp_buf")) 6313 Context.setjmp_bufDecl(NewTD); 6314 else if (II->isStr("sigjmp_buf")) 6315 Context.setsigjmp_bufDecl(NewTD); 6316 else if (II->isStr("ucontext_t")) 6317 Context.setucontext_tDecl(NewTD); 6318 } 6319 6320 return NewTD; 6321 } 6322 6323 /// Determines whether the given declaration is an out-of-scope 6324 /// previous declaration. 6325 /// 6326 /// This routine should be invoked when name lookup has found a 6327 /// previous declaration (PrevDecl) that is not in the scope where a 6328 /// new declaration by the same name is being introduced. If the new 6329 /// declaration occurs in a local scope, previous declarations with 6330 /// linkage may still be considered previous declarations (C99 6331 /// 6.2.2p4-5, C++ [basic.link]p6). 6332 /// 6333 /// \param PrevDecl the previous declaration found by name 6334 /// lookup 6335 /// 6336 /// \param DC the context in which the new declaration is being 6337 /// declared. 6338 /// 6339 /// \returns true if PrevDecl is an out-of-scope previous declaration 6340 /// for a new delcaration with the same name. 6341 static bool 6342 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6343 ASTContext &Context) { 6344 if (!PrevDecl) 6345 return false; 6346 6347 if (!PrevDecl->hasLinkage()) 6348 return false; 6349 6350 if (Context.getLangOpts().CPlusPlus) { 6351 // C++ [basic.link]p6: 6352 // If there is a visible declaration of an entity with linkage 6353 // having the same name and type, ignoring entities declared 6354 // outside the innermost enclosing namespace scope, the block 6355 // scope declaration declares that same entity and receives the 6356 // linkage of the previous declaration. 6357 DeclContext *OuterContext = DC->getRedeclContext(); 6358 if (!OuterContext->isFunctionOrMethod()) 6359 // This rule only applies to block-scope declarations. 6360 return false; 6361 6362 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6363 if (PrevOuterContext->isRecord()) 6364 // We found a member function: ignore it. 6365 return false; 6366 6367 // Find the innermost enclosing namespace for the new and 6368 // previous declarations. 6369 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6370 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6371 6372 // The previous declaration is in a different namespace, so it 6373 // isn't the same function. 6374 if (!OuterContext->Equals(PrevOuterContext)) 6375 return false; 6376 } 6377 6378 return true; 6379 } 6380 6381 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6382 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6383 if (!SS.isSet()) return; 6384 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6385 } 6386 6387 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6388 QualType type = decl->getType(); 6389 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6390 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6391 // Various kinds of declaration aren't allowed to be __autoreleasing. 6392 unsigned kind = -1U; 6393 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6394 if (var->hasAttr<BlocksAttr>()) 6395 kind = 0; // __block 6396 else if (!var->hasLocalStorage()) 6397 kind = 1; // global 6398 } else if (isa<ObjCIvarDecl>(decl)) { 6399 kind = 3; // ivar 6400 } else if (isa<FieldDecl>(decl)) { 6401 kind = 2; // field 6402 } 6403 6404 if (kind != -1U) { 6405 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6406 << kind; 6407 } 6408 } else if (lifetime == Qualifiers::OCL_None) { 6409 // Try to infer lifetime. 6410 if (!type->isObjCLifetimeType()) 6411 return false; 6412 6413 lifetime = type->getObjCARCImplicitLifetime(); 6414 type = Context.getLifetimeQualifiedType(type, lifetime); 6415 decl->setType(type); 6416 } 6417 6418 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6419 // Thread-local variables cannot have lifetime. 6420 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6421 var->getTLSKind()) { 6422 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6423 << var->getType(); 6424 return true; 6425 } 6426 } 6427 6428 return false; 6429 } 6430 6431 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6432 if (Decl->getType().hasAddressSpace()) 6433 return; 6434 if (Decl->getType()->isDependentType()) 6435 return; 6436 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6437 QualType Type = Var->getType(); 6438 if (Type->isSamplerT() || Type->isVoidType()) 6439 return; 6440 LangAS ImplAS = LangAS::opencl_private; 6441 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6442 // __opencl_c_program_scope_global_variables feature, the address space 6443 // for a variable at program scope or a static or extern variable inside 6444 // a function are inferred to be __global. 6445 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6446 Var->hasGlobalStorage()) 6447 ImplAS = LangAS::opencl_global; 6448 // If the original type from a decayed type is an array type and that array 6449 // type has no address space yet, deduce it now. 6450 if (auto DT = dyn_cast<DecayedType>(Type)) { 6451 auto OrigTy = DT->getOriginalType(); 6452 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6453 // Add the address space to the original array type and then propagate 6454 // that to the element type through `getAsArrayType`. 6455 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6456 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6457 // Re-generate the decayed type. 6458 Type = Context.getDecayedType(OrigTy); 6459 } 6460 } 6461 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6462 // Apply any qualifiers (including address space) from the array type to 6463 // the element type. This implements C99 6.7.3p8: "If the specification of 6464 // an array type includes any type qualifiers, the element type is so 6465 // qualified, not the array type." 6466 if (Type->isArrayType()) 6467 Type = QualType(Context.getAsArrayType(Type), 0); 6468 Decl->setType(Type); 6469 } 6470 } 6471 6472 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6473 // Ensure that an auto decl is deduced otherwise the checks below might cache 6474 // the wrong linkage. 6475 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6476 6477 // 'weak' only applies to declarations with external linkage. 6478 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6479 if (!ND.isExternallyVisible()) { 6480 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6481 ND.dropAttr<WeakAttr>(); 6482 } 6483 } 6484 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6485 if (ND.isExternallyVisible()) { 6486 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6487 ND.dropAttr<WeakRefAttr>(); 6488 ND.dropAttr<AliasAttr>(); 6489 } 6490 } 6491 6492 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6493 if (VD->hasInit()) { 6494 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6495 assert(VD->isThisDeclarationADefinition() && 6496 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6497 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6498 VD->dropAttr<AliasAttr>(); 6499 } 6500 } 6501 } 6502 6503 // 'selectany' only applies to externally visible variable declarations. 6504 // It does not apply to functions. 6505 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6506 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6507 S.Diag(Attr->getLocation(), 6508 diag::err_attribute_selectany_non_extern_data); 6509 ND.dropAttr<SelectAnyAttr>(); 6510 } 6511 } 6512 6513 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6514 auto *VD = dyn_cast<VarDecl>(&ND); 6515 bool IsAnonymousNS = false; 6516 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6517 if (VD) { 6518 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6519 while (NS && !IsAnonymousNS) { 6520 IsAnonymousNS = NS->isAnonymousNamespace(); 6521 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6522 } 6523 } 6524 // dll attributes require external linkage. Static locals may have external 6525 // linkage but still cannot be explicitly imported or exported. 6526 // In Microsoft mode, a variable defined in anonymous namespace must have 6527 // external linkage in order to be exported. 6528 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6529 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6530 (!AnonNSInMicrosoftMode && 6531 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6532 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6533 << &ND << Attr; 6534 ND.setInvalidDecl(); 6535 } 6536 } 6537 6538 // Check the attributes on the function type, if any. 6539 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6540 // Don't declare this variable in the second operand of the for-statement; 6541 // GCC miscompiles that by ending its lifetime before evaluating the 6542 // third operand. See gcc.gnu.org/PR86769. 6543 AttributedTypeLoc ATL; 6544 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6545 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6546 TL = ATL.getModifiedLoc()) { 6547 // The [[lifetimebound]] attribute can be applied to the implicit object 6548 // parameter of a non-static member function (other than a ctor or dtor) 6549 // by applying it to the function type. 6550 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6551 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6552 if (!MD || MD->isStatic()) { 6553 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6554 << !MD << A->getRange(); 6555 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6556 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6557 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6558 } 6559 } 6560 } 6561 } 6562 } 6563 6564 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6565 NamedDecl *NewDecl, 6566 bool IsSpecialization, 6567 bool IsDefinition) { 6568 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6569 return; 6570 6571 bool IsTemplate = false; 6572 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6573 OldDecl = OldTD->getTemplatedDecl(); 6574 IsTemplate = true; 6575 if (!IsSpecialization) 6576 IsDefinition = false; 6577 } 6578 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6579 NewDecl = NewTD->getTemplatedDecl(); 6580 IsTemplate = true; 6581 } 6582 6583 if (!OldDecl || !NewDecl) 6584 return; 6585 6586 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6587 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6588 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6589 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6590 6591 // dllimport and dllexport are inheritable attributes so we have to exclude 6592 // inherited attribute instances. 6593 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6594 (NewExportAttr && !NewExportAttr->isInherited()); 6595 6596 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6597 // the only exception being explicit specializations. 6598 // Implicitly generated declarations are also excluded for now because there 6599 // is no other way to switch these to use dllimport or dllexport. 6600 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6601 6602 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6603 // Allow with a warning for free functions and global variables. 6604 bool JustWarn = false; 6605 if (!OldDecl->isCXXClassMember()) { 6606 auto *VD = dyn_cast<VarDecl>(OldDecl); 6607 if (VD && !VD->getDescribedVarTemplate()) 6608 JustWarn = true; 6609 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6610 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6611 JustWarn = true; 6612 } 6613 6614 // We cannot change a declaration that's been used because IR has already 6615 // been emitted. Dllimported functions will still work though (modulo 6616 // address equality) as they can use the thunk. 6617 if (OldDecl->isUsed()) 6618 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6619 JustWarn = false; 6620 6621 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6622 : diag::err_attribute_dll_redeclaration; 6623 S.Diag(NewDecl->getLocation(), DiagID) 6624 << NewDecl 6625 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6626 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6627 if (!JustWarn) { 6628 NewDecl->setInvalidDecl(); 6629 return; 6630 } 6631 } 6632 6633 // A redeclaration is not allowed to drop a dllimport attribute, the only 6634 // exceptions being inline function definitions (except for function 6635 // templates), local extern declarations, qualified friend declarations or 6636 // special MSVC extension: in the last case, the declaration is treated as if 6637 // it were marked dllexport. 6638 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6639 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6640 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6641 // Ignore static data because out-of-line definitions are diagnosed 6642 // separately. 6643 IsStaticDataMember = VD->isStaticDataMember(); 6644 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6645 VarDecl::DeclarationOnly; 6646 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6647 IsInline = FD->isInlined(); 6648 IsQualifiedFriend = FD->getQualifier() && 6649 FD->getFriendObjectKind() == Decl::FOK_Declared; 6650 } 6651 6652 if (OldImportAttr && !HasNewAttr && 6653 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6654 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6655 if (IsMicrosoftABI && IsDefinition) { 6656 S.Diag(NewDecl->getLocation(), 6657 diag::warn_redeclaration_without_import_attribute) 6658 << NewDecl; 6659 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6660 NewDecl->dropAttr<DLLImportAttr>(); 6661 NewDecl->addAttr( 6662 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6663 } else { 6664 S.Diag(NewDecl->getLocation(), 6665 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6666 << NewDecl << OldImportAttr; 6667 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6668 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6669 OldDecl->dropAttr<DLLImportAttr>(); 6670 NewDecl->dropAttr<DLLImportAttr>(); 6671 } 6672 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6673 // In MinGW, seeing a function declared inline drops the dllimport 6674 // attribute. 6675 OldDecl->dropAttr<DLLImportAttr>(); 6676 NewDecl->dropAttr<DLLImportAttr>(); 6677 S.Diag(NewDecl->getLocation(), 6678 diag::warn_dllimport_dropped_from_inline_function) 6679 << NewDecl << OldImportAttr; 6680 } 6681 6682 // A specialization of a class template member function is processed here 6683 // since it's a redeclaration. If the parent class is dllexport, the 6684 // specialization inherits that attribute. This doesn't happen automatically 6685 // since the parent class isn't instantiated until later. 6686 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6687 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6688 !NewImportAttr && !NewExportAttr) { 6689 if (const DLLExportAttr *ParentExportAttr = 6690 MD->getParent()->getAttr<DLLExportAttr>()) { 6691 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6692 NewAttr->setInherited(true); 6693 NewDecl->addAttr(NewAttr); 6694 } 6695 } 6696 } 6697 } 6698 6699 /// Given that we are within the definition of the given function, 6700 /// will that definition behave like C99's 'inline', where the 6701 /// definition is discarded except for optimization purposes? 6702 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6703 // Try to avoid calling GetGVALinkageForFunction. 6704 6705 // All cases of this require the 'inline' keyword. 6706 if (!FD->isInlined()) return false; 6707 6708 // This is only possible in C++ with the gnu_inline attribute. 6709 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6710 return false; 6711 6712 // Okay, go ahead and call the relatively-more-expensive function. 6713 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6714 } 6715 6716 /// Determine whether a variable is extern "C" prior to attaching 6717 /// an initializer. We can't just call isExternC() here, because that 6718 /// will also compute and cache whether the declaration is externally 6719 /// visible, which might change when we attach the initializer. 6720 /// 6721 /// This can only be used if the declaration is known to not be a 6722 /// redeclaration of an internal linkage declaration. 6723 /// 6724 /// For instance: 6725 /// 6726 /// auto x = []{}; 6727 /// 6728 /// Attaching the initializer here makes this declaration not externally 6729 /// visible, because its type has internal linkage. 6730 /// 6731 /// FIXME: This is a hack. 6732 template<typename T> 6733 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6734 if (S.getLangOpts().CPlusPlus) { 6735 // In C++, the overloadable attribute negates the effects of extern "C". 6736 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6737 return false; 6738 6739 // So do CUDA's host/device attributes. 6740 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6741 D->template hasAttr<CUDAHostAttr>())) 6742 return false; 6743 } 6744 return D->isExternC(); 6745 } 6746 6747 static bool shouldConsiderLinkage(const VarDecl *VD) { 6748 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6749 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6750 isa<OMPDeclareMapperDecl>(DC)) 6751 return VD->hasExternalStorage(); 6752 if (DC->isFileContext()) 6753 return true; 6754 if (DC->isRecord()) 6755 return false; 6756 if (isa<RequiresExprBodyDecl>(DC)) 6757 return false; 6758 llvm_unreachable("Unexpected context"); 6759 } 6760 6761 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6762 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6763 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6764 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6765 return true; 6766 if (DC->isRecord()) 6767 return false; 6768 llvm_unreachable("Unexpected context"); 6769 } 6770 6771 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6772 ParsedAttr::Kind Kind) { 6773 // Check decl attributes on the DeclSpec. 6774 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6775 return true; 6776 6777 // Walk the declarator structure, checking decl attributes that were in a type 6778 // position to the decl itself. 6779 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6780 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6781 return true; 6782 } 6783 6784 // Finally, check attributes on the decl itself. 6785 return PD.getAttributes().hasAttribute(Kind); 6786 } 6787 6788 /// Adjust the \c DeclContext for a function or variable that might be a 6789 /// function-local external declaration. 6790 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6791 if (!DC->isFunctionOrMethod()) 6792 return false; 6793 6794 // If this is a local extern function or variable declared within a function 6795 // template, don't add it into the enclosing namespace scope until it is 6796 // instantiated; it might have a dependent type right now. 6797 if (DC->isDependentContext()) 6798 return true; 6799 6800 // C++11 [basic.link]p7: 6801 // When a block scope declaration of an entity with linkage is not found to 6802 // refer to some other declaration, then that entity is a member of the 6803 // innermost enclosing namespace. 6804 // 6805 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6806 // semantically-enclosing namespace, not a lexically-enclosing one. 6807 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6808 DC = DC->getParent(); 6809 return true; 6810 } 6811 6812 /// Returns true if given declaration has external C language linkage. 6813 static bool isDeclExternC(const Decl *D) { 6814 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6815 return FD->isExternC(); 6816 if (const auto *VD = dyn_cast<VarDecl>(D)) 6817 return VD->isExternC(); 6818 6819 llvm_unreachable("Unknown type of decl!"); 6820 } 6821 6822 /// Returns true if there hasn't been any invalid type diagnosed. 6823 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6824 DeclContext *DC = NewVD->getDeclContext(); 6825 QualType R = NewVD->getType(); 6826 6827 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6828 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6829 // argument. 6830 if (R->isImageType() || R->isPipeType()) { 6831 Se.Diag(NewVD->getLocation(), 6832 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6833 << R; 6834 NewVD->setInvalidDecl(); 6835 return false; 6836 } 6837 6838 // OpenCL v1.2 s6.9.r: 6839 // The event type cannot be used to declare a program scope variable. 6840 // OpenCL v2.0 s6.9.q: 6841 // The clk_event_t and reserve_id_t types cannot be declared in program 6842 // scope. 6843 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6844 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6845 Se.Diag(NewVD->getLocation(), 6846 diag::err_invalid_type_for_program_scope_var) 6847 << R; 6848 NewVD->setInvalidDecl(); 6849 return false; 6850 } 6851 } 6852 6853 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6854 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6855 Se.getLangOpts())) { 6856 QualType NR = R.getCanonicalType(); 6857 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6858 NR->isReferenceType()) { 6859 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6860 NR->isFunctionReferenceType()) { 6861 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6862 << NR->isReferenceType(); 6863 NewVD->setInvalidDecl(); 6864 return false; 6865 } 6866 NR = NR->getPointeeType(); 6867 } 6868 } 6869 6870 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6871 Se.getLangOpts())) { 6872 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6873 // half array type (unless the cl_khr_fp16 extension is enabled). 6874 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6875 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6876 NewVD->setInvalidDecl(); 6877 return false; 6878 } 6879 } 6880 6881 // OpenCL v1.2 s6.9.r: 6882 // The event type cannot be used with the __local, __constant and __global 6883 // address space qualifiers. 6884 if (R->isEventT()) { 6885 if (R.getAddressSpace() != LangAS::opencl_private) { 6886 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6887 NewVD->setInvalidDecl(); 6888 return false; 6889 } 6890 } 6891 6892 if (R->isSamplerT()) { 6893 // OpenCL v1.2 s6.9.b p4: 6894 // The sampler type cannot be used with the __local and __global address 6895 // space qualifiers. 6896 if (R.getAddressSpace() == LangAS::opencl_local || 6897 R.getAddressSpace() == LangAS::opencl_global) { 6898 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 6899 NewVD->setInvalidDecl(); 6900 } 6901 6902 // OpenCL v1.2 s6.12.14.1: 6903 // A global sampler must be declared with either the constant address 6904 // space qualifier or with the const qualifier. 6905 if (DC->isTranslationUnit() && 6906 !(R.getAddressSpace() == LangAS::opencl_constant || 6907 R.isConstQualified())) { 6908 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 6909 NewVD->setInvalidDecl(); 6910 } 6911 if (NewVD->isInvalidDecl()) 6912 return false; 6913 } 6914 6915 return true; 6916 } 6917 6918 template <typename AttrTy> 6919 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 6920 const TypedefNameDecl *TND = TT->getDecl(); 6921 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 6922 AttrTy *Clone = Attribute->clone(S.Context); 6923 Clone->setInherited(true); 6924 D->addAttr(Clone); 6925 } 6926 } 6927 6928 NamedDecl *Sema::ActOnVariableDeclarator( 6929 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6930 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6931 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6932 QualType R = TInfo->getType(); 6933 DeclarationName Name = GetNameForDeclarator(D).getName(); 6934 6935 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6936 6937 if (D.isDecompositionDeclarator()) { 6938 // Take the name of the first declarator as our name for diagnostic 6939 // purposes. 6940 auto &Decomp = D.getDecompositionDeclarator(); 6941 if (!Decomp.bindings().empty()) { 6942 II = Decomp.bindings()[0].Name; 6943 Name = II; 6944 } 6945 } else if (!II) { 6946 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6947 return nullptr; 6948 } 6949 6950 6951 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6952 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6953 6954 // dllimport globals without explicit storage class are treated as extern. We 6955 // have to change the storage class this early to get the right DeclContext. 6956 if (SC == SC_None && !DC->isRecord() && 6957 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6958 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6959 SC = SC_Extern; 6960 6961 DeclContext *OriginalDC = DC; 6962 bool IsLocalExternDecl = SC == SC_Extern && 6963 adjustContextForLocalExternDecl(DC); 6964 6965 if (SCSpec == DeclSpec::SCS_mutable) { 6966 // mutable can only appear on non-static class members, so it's always 6967 // an error here 6968 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6969 D.setInvalidType(); 6970 SC = SC_None; 6971 } 6972 6973 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6974 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6975 D.getDeclSpec().getStorageClassSpecLoc())) { 6976 // In C++11, the 'register' storage class specifier is deprecated. 6977 // Suppress the warning in system macros, it's used in macros in some 6978 // popular C system headers, such as in glibc's htonl() macro. 6979 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6980 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6981 : diag::warn_deprecated_register) 6982 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6983 } 6984 6985 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6986 6987 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6988 // C99 6.9p2: The storage-class specifiers auto and register shall not 6989 // appear in the declaration specifiers in an external declaration. 6990 // Global Register+Asm is a GNU extension we support. 6991 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6992 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6993 D.setInvalidType(); 6994 } 6995 } 6996 6997 // If this variable has a VLA type and an initializer, try to 6998 // fold to a constant-sized type. This is otherwise invalid. 6999 if (D.hasInitializer() && R->isVariableArrayType()) 7000 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7001 /*DiagID=*/0); 7002 7003 bool IsMemberSpecialization = false; 7004 bool IsVariableTemplateSpecialization = false; 7005 bool IsPartialSpecialization = false; 7006 bool IsVariableTemplate = false; 7007 VarDecl *NewVD = nullptr; 7008 VarTemplateDecl *NewTemplate = nullptr; 7009 TemplateParameterList *TemplateParams = nullptr; 7010 if (!getLangOpts().CPlusPlus) { 7011 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7012 II, R, TInfo, SC); 7013 7014 if (R->getContainedDeducedType()) 7015 ParsingInitForAutoVars.insert(NewVD); 7016 7017 if (D.isInvalidType()) 7018 NewVD->setInvalidDecl(); 7019 7020 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7021 NewVD->hasLocalStorage()) 7022 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7023 NTCUC_AutoVar, NTCUK_Destruct); 7024 } else { 7025 bool Invalid = false; 7026 7027 if (DC->isRecord() && !CurContext->isRecord()) { 7028 // This is an out-of-line definition of a static data member. 7029 switch (SC) { 7030 case SC_None: 7031 break; 7032 case SC_Static: 7033 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7034 diag::err_static_out_of_line) 7035 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7036 break; 7037 case SC_Auto: 7038 case SC_Register: 7039 case SC_Extern: 7040 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7041 // to names of variables declared in a block or to function parameters. 7042 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7043 // of class members 7044 7045 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7046 diag::err_storage_class_for_static_member) 7047 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7048 break; 7049 case SC_PrivateExtern: 7050 llvm_unreachable("C storage class in c++!"); 7051 } 7052 } 7053 7054 if (SC == SC_Static && CurContext->isRecord()) { 7055 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7056 // Walk up the enclosing DeclContexts to check for any that are 7057 // incompatible with static data members. 7058 const DeclContext *FunctionOrMethod = nullptr; 7059 const CXXRecordDecl *AnonStruct = nullptr; 7060 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7061 if (Ctxt->isFunctionOrMethod()) { 7062 FunctionOrMethod = Ctxt; 7063 break; 7064 } 7065 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7066 if (ParentDecl && !ParentDecl->getDeclName()) { 7067 AnonStruct = ParentDecl; 7068 break; 7069 } 7070 } 7071 if (FunctionOrMethod) { 7072 // C++ [class.static.data]p5: A local class shall not have static data 7073 // members. 7074 Diag(D.getIdentifierLoc(), 7075 diag::err_static_data_member_not_allowed_in_local_class) 7076 << Name << RD->getDeclName() << RD->getTagKind(); 7077 } else if (AnonStruct) { 7078 // C++ [class.static.data]p4: Unnamed classes and classes contained 7079 // directly or indirectly within unnamed classes shall not contain 7080 // static data members. 7081 Diag(D.getIdentifierLoc(), 7082 diag::err_static_data_member_not_allowed_in_anon_struct) 7083 << Name << AnonStruct->getTagKind(); 7084 Invalid = true; 7085 } else if (RD->isUnion()) { 7086 // C++98 [class.union]p1: If a union contains a static data member, 7087 // the program is ill-formed. C++11 drops this restriction. 7088 Diag(D.getIdentifierLoc(), 7089 getLangOpts().CPlusPlus11 7090 ? diag::warn_cxx98_compat_static_data_member_in_union 7091 : diag::ext_static_data_member_in_union) << Name; 7092 } 7093 } 7094 } 7095 7096 // Match up the template parameter lists with the scope specifier, then 7097 // determine whether we have a template or a template specialization. 7098 bool InvalidScope = false; 7099 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7100 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7101 D.getCXXScopeSpec(), 7102 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7103 ? D.getName().TemplateId 7104 : nullptr, 7105 TemplateParamLists, 7106 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7107 Invalid |= InvalidScope; 7108 7109 if (TemplateParams) { 7110 if (!TemplateParams->size() && 7111 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7112 // There is an extraneous 'template<>' for this variable. Complain 7113 // about it, but allow the declaration of the variable. 7114 Diag(TemplateParams->getTemplateLoc(), 7115 diag::err_template_variable_noparams) 7116 << II 7117 << SourceRange(TemplateParams->getTemplateLoc(), 7118 TemplateParams->getRAngleLoc()); 7119 TemplateParams = nullptr; 7120 } else { 7121 // Check that we can declare a template here. 7122 if (CheckTemplateDeclScope(S, TemplateParams)) 7123 return nullptr; 7124 7125 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7126 // This is an explicit specialization or a partial specialization. 7127 IsVariableTemplateSpecialization = true; 7128 IsPartialSpecialization = TemplateParams->size() > 0; 7129 } else { // if (TemplateParams->size() > 0) 7130 // This is a template declaration. 7131 IsVariableTemplate = true; 7132 7133 // Only C++1y supports variable templates (N3651). 7134 Diag(D.getIdentifierLoc(), 7135 getLangOpts().CPlusPlus14 7136 ? diag::warn_cxx11_compat_variable_template 7137 : diag::ext_variable_template); 7138 } 7139 } 7140 } else { 7141 // Check that we can declare a member specialization here. 7142 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7143 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7144 return nullptr; 7145 assert((Invalid || 7146 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7147 "should have a 'template<>' for this decl"); 7148 } 7149 7150 if (IsVariableTemplateSpecialization) { 7151 SourceLocation TemplateKWLoc = 7152 TemplateParamLists.size() > 0 7153 ? TemplateParamLists[0]->getTemplateLoc() 7154 : SourceLocation(); 7155 DeclResult Res = ActOnVarTemplateSpecialization( 7156 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7157 IsPartialSpecialization); 7158 if (Res.isInvalid()) 7159 return nullptr; 7160 NewVD = cast<VarDecl>(Res.get()); 7161 AddToScope = false; 7162 } else if (D.isDecompositionDeclarator()) { 7163 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7164 D.getIdentifierLoc(), R, TInfo, SC, 7165 Bindings); 7166 } else 7167 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7168 D.getIdentifierLoc(), II, R, TInfo, SC); 7169 7170 // If this is supposed to be a variable template, create it as such. 7171 if (IsVariableTemplate) { 7172 NewTemplate = 7173 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7174 TemplateParams, NewVD); 7175 NewVD->setDescribedVarTemplate(NewTemplate); 7176 } 7177 7178 // If this decl has an auto type in need of deduction, make a note of the 7179 // Decl so we can diagnose uses of it in its own initializer. 7180 if (R->getContainedDeducedType()) 7181 ParsingInitForAutoVars.insert(NewVD); 7182 7183 if (D.isInvalidType() || Invalid) { 7184 NewVD->setInvalidDecl(); 7185 if (NewTemplate) 7186 NewTemplate->setInvalidDecl(); 7187 } 7188 7189 SetNestedNameSpecifier(*this, NewVD, D); 7190 7191 // If we have any template parameter lists that don't directly belong to 7192 // the variable (matching the scope specifier), store them. 7193 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7194 if (TemplateParamLists.size() > VDTemplateParamLists) 7195 NewVD->setTemplateParameterListsInfo( 7196 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7197 } 7198 7199 if (D.getDeclSpec().isInlineSpecified()) { 7200 if (!getLangOpts().CPlusPlus) { 7201 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7202 << 0; 7203 } else if (CurContext->isFunctionOrMethod()) { 7204 // 'inline' is not allowed on block scope variable declaration. 7205 Diag(D.getDeclSpec().getInlineSpecLoc(), 7206 diag::err_inline_declaration_block_scope) << Name 7207 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7208 } else { 7209 Diag(D.getDeclSpec().getInlineSpecLoc(), 7210 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7211 : diag::ext_inline_variable); 7212 NewVD->setInlineSpecified(); 7213 } 7214 } 7215 7216 // Set the lexical context. If the declarator has a C++ scope specifier, the 7217 // lexical context will be different from the semantic context. 7218 NewVD->setLexicalDeclContext(CurContext); 7219 if (NewTemplate) 7220 NewTemplate->setLexicalDeclContext(CurContext); 7221 7222 if (IsLocalExternDecl) { 7223 if (D.isDecompositionDeclarator()) 7224 for (auto *B : Bindings) 7225 B->setLocalExternDecl(); 7226 else 7227 NewVD->setLocalExternDecl(); 7228 } 7229 7230 bool EmitTLSUnsupportedError = false; 7231 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7232 // C++11 [dcl.stc]p4: 7233 // When thread_local is applied to a variable of block scope the 7234 // storage-class-specifier static is implied if it does not appear 7235 // explicitly. 7236 // Core issue: 'static' is not implied if the variable is declared 7237 // 'extern'. 7238 if (NewVD->hasLocalStorage() && 7239 (SCSpec != DeclSpec::SCS_unspecified || 7240 TSCS != DeclSpec::TSCS_thread_local || 7241 !DC->isFunctionOrMethod())) 7242 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7243 diag::err_thread_non_global) 7244 << DeclSpec::getSpecifierName(TSCS); 7245 else if (!Context.getTargetInfo().isTLSSupported()) { 7246 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7247 getLangOpts().SYCLIsDevice) { 7248 // Postpone error emission until we've collected attributes required to 7249 // figure out whether it's a host or device variable and whether the 7250 // error should be ignored. 7251 EmitTLSUnsupportedError = true; 7252 // We still need to mark the variable as TLS so it shows up in AST with 7253 // proper storage class for other tools to use even if we're not going 7254 // to emit any code for it. 7255 NewVD->setTSCSpec(TSCS); 7256 } else 7257 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7258 diag::err_thread_unsupported); 7259 } else 7260 NewVD->setTSCSpec(TSCS); 7261 } 7262 7263 switch (D.getDeclSpec().getConstexprSpecifier()) { 7264 case ConstexprSpecKind::Unspecified: 7265 break; 7266 7267 case ConstexprSpecKind::Consteval: 7268 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7269 diag::err_constexpr_wrong_decl_kind) 7270 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7271 LLVM_FALLTHROUGH; 7272 7273 case ConstexprSpecKind::Constexpr: 7274 NewVD->setConstexpr(true); 7275 // C++1z [dcl.spec.constexpr]p1: 7276 // A static data member declared with the constexpr specifier is 7277 // implicitly an inline variable. 7278 if (NewVD->isStaticDataMember() && 7279 (getLangOpts().CPlusPlus17 || 7280 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7281 NewVD->setImplicitlyInline(); 7282 break; 7283 7284 case ConstexprSpecKind::Constinit: 7285 if (!NewVD->hasGlobalStorage()) 7286 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7287 diag::err_constinit_local_variable); 7288 else 7289 NewVD->addAttr(ConstInitAttr::Create( 7290 Context, D.getDeclSpec().getConstexprSpecLoc(), 7291 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7292 break; 7293 } 7294 7295 // C99 6.7.4p3 7296 // An inline definition of a function with external linkage shall 7297 // not contain a definition of a modifiable object with static or 7298 // thread storage duration... 7299 // We only apply this when the function is required to be defined 7300 // elsewhere, i.e. when the function is not 'extern inline'. Note 7301 // that a local variable with thread storage duration still has to 7302 // be marked 'static'. Also note that it's possible to get these 7303 // semantics in C++ using __attribute__((gnu_inline)). 7304 if (SC == SC_Static && S->getFnParent() != nullptr && 7305 !NewVD->getType().isConstQualified()) { 7306 FunctionDecl *CurFD = getCurFunctionDecl(); 7307 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7308 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7309 diag::warn_static_local_in_extern_inline); 7310 MaybeSuggestAddingStaticToDecl(CurFD); 7311 } 7312 } 7313 7314 if (D.getDeclSpec().isModulePrivateSpecified()) { 7315 if (IsVariableTemplateSpecialization) 7316 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7317 << (IsPartialSpecialization ? 1 : 0) 7318 << FixItHint::CreateRemoval( 7319 D.getDeclSpec().getModulePrivateSpecLoc()); 7320 else if (IsMemberSpecialization) 7321 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7322 << 2 7323 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7324 else if (NewVD->hasLocalStorage()) 7325 Diag(NewVD->getLocation(), diag::err_module_private_local) 7326 << 0 << NewVD 7327 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7328 << FixItHint::CreateRemoval( 7329 D.getDeclSpec().getModulePrivateSpecLoc()); 7330 else { 7331 NewVD->setModulePrivate(); 7332 if (NewTemplate) 7333 NewTemplate->setModulePrivate(); 7334 for (auto *B : Bindings) 7335 B->setModulePrivate(); 7336 } 7337 } 7338 7339 if (getLangOpts().OpenCL) { 7340 deduceOpenCLAddressSpace(NewVD); 7341 7342 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7343 if (TSC != TSCS_unspecified) { 7344 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7345 diag::err_opencl_unknown_type_specifier) 7346 << getLangOpts().getOpenCLVersionString() 7347 << DeclSpec::getSpecifierName(TSC) << 1; 7348 NewVD->setInvalidDecl(); 7349 } 7350 } 7351 7352 // Handle attributes prior to checking for duplicates in MergeVarDecl 7353 ProcessDeclAttributes(S, NewVD, D); 7354 7355 // FIXME: This is probably the wrong location to be doing this and we should 7356 // probably be doing this for more attributes (especially for function 7357 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7358 // the code to copy attributes would be generated by TableGen. 7359 if (R->isFunctionPointerType()) 7360 if (const auto *TT = R->getAs<TypedefType>()) 7361 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7362 7363 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7364 getLangOpts().SYCLIsDevice) { 7365 if (EmitTLSUnsupportedError && 7366 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7367 (getLangOpts().OpenMPIsDevice && 7368 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7369 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7370 diag::err_thread_unsupported); 7371 7372 if (EmitTLSUnsupportedError && 7373 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7374 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7375 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7376 // storage [duration]." 7377 if (SC == SC_None && S->getFnParent() != nullptr && 7378 (NewVD->hasAttr<CUDASharedAttr>() || 7379 NewVD->hasAttr<CUDAConstantAttr>())) { 7380 NewVD->setStorageClass(SC_Static); 7381 } 7382 } 7383 7384 // Ensure that dllimport globals without explicit storage class are treated as 7385 // extern. The storage class is set above using parsed attributes. Now we can 7386 // check the VarDecl itself. 7387 assert(!NewVD->hasAttr<DLLImportAttr>() || 7388 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7389 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7390 7391 // In auto-retain/release, infer strong retension for variables of 7392 // retainable type. 7393 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7394 NewVD->setInvalidDecl(); 7395 7396 // Handle GNU asm-label extension (encoded as an attribute). 7397 if (Expr *E = (Expr*)D.getAsmLabel()) { 7398 // The parser guarantees this is a string. 7399 StringLiteral *SE = cast<StringLiteral>(E); 7400 StringRef Label = SE->getString(); 7401 if (S->getFnParent() != nullptr) { 7402 switch (SC) { 7403 case SC_None: 7404 case SC_Auto: 7405 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7406 break; 7407 case SC_Register: 7408 // Local Named register 7409 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7410 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7411 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7412 break; 7413 case SC_Static: 7414 case SC_Extern: 7415 case SC_PrivateExtern: 7416 break; 7417 } 7418 } else if (SC == SC_Register) { 7419 // Global Named register 7420 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7421 const auto &TI = Context.getTargetInfo(); 7422 bool HasSizeMismatch; 7423 7424 if (!TI.isValidGCCRegisterName(Label)) 7425 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7426 else if (!TI.validateGlobalRegisterVariable(Label, 7427 Context.getTypeSize(R), 7428 HasSizeMismatch)) 7429 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7430 else if (HasSizeMismatch) 7431 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7432 } 7433 7434 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7435 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7436 NewVD->setInvalidDecl(true); 7437 } 7438 } 7439 7440 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7441 /*IsLiteralLabel=*/true, 7442 SE->getStrTokenLoc(0))); 7443 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7444 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7445 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7446 if (I != ExtnameUndeclaredIdentifiers.end()) { 7447 if (isDeclExternC(NewVD)) { 7448 NewVD->addAttr(I->second); 7449 ExtnameUndeclaredIdentifiers.erase(I); 7450 } else 7451 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7452 << /*Variable*/1 << NewVD; 7453 } 7454 } 7455 7456 // Find the shadowed declaration before filtering for scope. 7457 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7458 ? getShadowedDeclaration(NewVD, Previous) 7459 : nullptr; 7460 7461 // Don't consider existing declarations that are in a different 7462 // scope and are out-of-semantic-context declarations (if the new 7463 // declaration has linkage). 7464 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7465 D.getCXXScopeSpec().isNotEmpty() || 7466 IsMemberSpecialization || 7467 IsVariableTemplateSpecialization); 7468 7469 // Check whether the previous declaration is in the same block scope. This 7470 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7471 if (getLangOpts().CPlusPlus && 7472 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7473 NewVD->setPreviousDeclInSameBlockScope( 7474 Previous.isSingleResult() && !Previous.isShadowed() && 7475 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7476 7477 if (!getLangOpts().CPlusPlus) { 7478 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7479 } else { 7480 // If this is an explicit specialization of a static data member, check it. 7481 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7482 CheckMemberSpecialization(NewVD, Previous)) 7483 NewVD->setInvalidDecl(); 7484 7485 // Merge the decl with the existing one if appropriate. 7486 if (!Previous.empty()) { 7487 if (Previous.isSingleResult() && 7488 isa<FieldDecl>(Previous.getFoundDecl()) && 7489 D.getCXXScopeSpec().isSet()) { 7490 // The user tried to define a non-static data member 7491 // out-of-line (C++ [dcl.meaning]p1). 7492 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7493 << D.getCXXScopeSpec().getRange(); 7494 Previous.clear(); 7495 NewVD->setInvalidDecl(); 7496 } 7497 } else if (D.getCXXScopeSpec().isSet()) { 7498 // No previous declaration in the qualifying scope. 7499 Diag(D.getIdentifierLoc(), diag::err_no_member) 7500 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7501 << D.getCXXScopeSpec().getRange(); 7502 NewVD->setInvalidDecl(); 7503 } 7504 7505 if (!IsVariableTemplateSpecialization) 7506 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7507 7508 if (NewTemplate) { 7509 VarTemplateDecl *PrevVarTemplate = 7510 NewVD->getPreviousDecl() 7511 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7512 : nullptr; 7513 7514 // Check the template parameter list of this declaration, possibly 7515 // merging in the template parameter list from the previous variable 7516 // template declaration. 7517 if (CheckTemplateParameterList( 7518 TemplateParams, 7519 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7520 : nullptr, 7521 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7522 DC->isDependentContext()) 7523 ? TPC_ClassTemplateMember 7524 : TPC_VarTemplate)) 7525 NewVD->setInvalidDecl(); 7526 7527 // If we are providing an explicit specialization of a static variable 7528 // template, make a note of that. 7529 if (PrevVarTemplate && 7530 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7531 PrevVarTemplate->setMemberSpecialization(); 7532 } 7533 } 7534 7535 // Diagnose shadowed variables iff this isn't a redeclaration. 7536 if (ShadowedDecl && !D.isRedeclaration()) 7537 CheckShadow(NewVD, ShadowedDecl, Previous); 7538 7539 ProcessPragmaWeak(S, NewVD); 7540 7541 // If this is the first declaration of an extern C variable, update 7542 // the map of such variables. 7543 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7544 isIncompleteDeclExternC(*this, NewVD)) 7545 RegisterLocallyScopedExternCDecl(NewVD, S); 7546 7547 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7548 MangleNumberingContext *MCtx; 7549 Decl *ManglingContextDecl; 7550 std::tie(MCtx, ManglingContextDecl) = 7551 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7552 if (MCtx) { 7553 Context.setManglingNumber( 7554 NewVD, MCtx->getManglingNumber( 7555 NewVD, getMSManglingNumber(getLangOpts(), S))); 7556 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7557 } 7558 } 7559 7560 // Special handling of variable named 'main'. 7561 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7562 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7563 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7564 7565 // C++ [basic.start.main]p3 7566 // A program that declares a variable main at global scope is ill-formed. 7567 if (getLangOpts().CPlusPlus) 7568 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7569 7570 // In C, and external-linkage variable named main results in undefined 7571 // behavior. 7572 else if (NewVD->hasExternalFormalLinkage()) 7573 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7574 } 7575 7576 if (D.isRedeclaration() && !Previous.empty()) { 7577 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7578 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7579 D.isFunctionDefinition()); 7580 } 7581 7582 if (NewTemplate) { 7583 if (NewVD->isInvalidDecl()) 7584 NewTemplate->setInvalidDecl(); 7585 ActOnDocumentableDecl(NewTemplate); 7586 return NewTemplate; 7587 } 7588 7589 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7590 CompleteMemberSpecialization(NewVD, Previous); 7591 7592 return NewVD; 7593 } 7594 7595 /// Enum describing the %select options in diag::warn_decl_shadow. 7596 enum ShadowedDeclKind { 7597 SDK_Local, 7598 SDK_Global, 7599 SDK_StaticMember, 7600 SDK_Field, 7601 SDK_Typedef, 7602 SDK_Using, 7603 SDK_StructuredBinding 7604 }; 7605 7606 /// Determine what kind of declaration we're shadowing. 7607 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7608 const DeclContext *OldDC) { 7609 if (isa<TypeAliasDecl>(ShadowedDecl)) 7610 return SDK_Using; 7611 else if (isa<TypedefDecl>(ShadowedDecl)) 7612 return SDK_Typedef; 7613 else if (isa<BindingDecl>(ShadowedDecl)) 7614 return SDK_StructuredBinding; 7615 else if (isa<RecordDecl>(OldDC)) 7616 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7617 7618 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7619 } 7620 7621 /// Return the location of the capture if the given lambda captures the given 7622 /// variable \p VD, or an invalid source location otherwise. 7623 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7624 const VarDecl *VD) { 7625 for (const Capture &Capture : LSI->Captures) { 7626 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7627 return Capture.getLocation(); 7628 } 7629 return SourceLocation(); 7630 } 7631 7632 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7633 const LookupResult &R) { 7634 // Only diagnose if we're shadowing an unambiguous field or variable. 7635 if (R.getResultKind() != LookupResult::Found) 7636 return false; 7637 7638 // Return false if warning is ignored. 7639 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7640 } 7641 7642 /// Return the declaration shadowed by the given variable \p D, or null 7643 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7644 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7645 const LookupResult &R) { 7646 if (!shouldWarnIfShadowedDecl(Diags, R)) 7647 return nullptr; 7648 7649 // Don't diagnose declarations at file scope. 7650 if (D->hasGlobalStorage()) 7651 return nullptr; 7652 7653 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7654 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7655 : nullptr; 7656 } 7657 7658 /// Return the declaration shadowed by the given typedef \p D, or null 7659 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7660 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7661 const LookupResult &R) { 7662 // Don't warn if typedef declaration is part of a class 7663 if (D->getDeclContext()->isRecord()) 7664 return nullptr; 7665 7666 if (!shouldWarnIfShadowedDecl(Diags, R)) 7667 return nullptr; 7668 7669 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7670 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7671 } 7672 7673 /// Return the declaration shadowed by the given variable \p D, or null 7674 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7675 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7676 const LookupResult &R) { 7677 if (!shouldWarnIfShadowedDecl(Diags, R)) 7678 return nullptr; 7679 7680 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7681 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7682 : nullptr; 7683 } 7684 7685 /// Diagnose variable or built-in function shadowing. Implements 7686 /// -Wshadow. 7687 /// 7688 /// This method is called whenever a VarDecl is added to a "useful" 7689 /// scope. 7690 /// 7691 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7692 /// \param R the lookup of the name 7693 /// 7694 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7695 const LookupResult &R) { 7696 DeclContext *NewDC = D->getDeclContext(); 7697 7698 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7699 // Fields are not shadowed by variables in C++ static methods. 7700 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7701 if (MD->isStatic()) 7702 return; 7703 7704 // Fields shadowed by constructor parameters are a special case. Usually 7705 // the constructor initializes the field with the parameter. 7706 if (isa<CXXConstructorDecl>(NewDC)) 7707 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7708 // Remember that this was shadowed so we can either warn about its 7709 // modification or its existence depending on warning settings. 7710 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7711 return; 7712 } 7713 } 7714 7715 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7716 if (shadowedVar->isExternC()) { 7717 // For shadowing external vars, make sure that we point to the global 7718 // declaration, not a locally scoped extern declaration. 7719 for (auto I : shadowedVar->redecls()) 7720 if (I->isFileVarDecl()) { 7721 ShadowedDecl = I; 7722 break; 7723 } 7724 } 7725 7726 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7727 7728 unsigned WarningDiag = diag::warn_decl_shadow; 7729 SourceLocation CaptureLoc; 7730 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7731 isa<CXXMethodDecl>(NewDC)) { 7732 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7733 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7734 if (RD->getLambdaCaptureDefault() == LCD_None) { 7735 // Try to avoid warnings for lambdas with an explicit capture list. 7736 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7737 // Warn only when the lambda captures the shadowed decl explicitly. 7738 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7739 if (CaptureLoc.isInvalid()) 7740 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7741 } else { 7742 // Remember that this was shadowed so we can avoid the warning if the 7743 // shadowed decl isn't captured and the warning settings allow it. 7744 cast<LambdaScopeInfo>(getCurFunction()) 7745 ->ShadowingDecls.push_back( 7746 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7747 return; 7748 } 7749 } 7750 7751 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7752 // A variable can't shadow a local variable in an enclosing scope, if 7753 // they are separated by a non-capturing declaration context. 7754 for (DeclContext *ParentDC = NewDC; 7755 ParentDC && !ParentDC->Equals(OldDC); 7756 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7757 // Only block literals, captured statements, and lambda expressions 7758 // can capture; other scopes don't. 7759 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7760 !isLambdaCallOperator(ParentDC)) { 7761 return; 7762 } 7763 } 7764 } 7765 } 7766 } 7767 7768 // Only warn about certain kinds of shadowing for class members. 7769 if (NewDC && NewDC->isRecord()) { 7770 // In particular, don't warn about shadowing non-class members. 7771 if (!OldDC->isRecord()) 7772 return; 7773 7774 // TODO: should we warn about static data members shadowing 7775 // static data members from base classes? 7776 7777 // TODO: don't diagnose for inaccessible shadowed members. 7778 // This is hard to do perfectly because we might friend the 7779 // shadowing context, but that's just a false negative. 7780 } 7781 7782 7783 DeclarationName Name = R.getLookupName(); 7784 7785 // Emit warning and note. 7786 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7787 return; 7788 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7789 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7790 if (!CaptureLoc.isInvalid()) 7791 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7792 << Name << /*explicitly*/ 1; 7793 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7794 } 7795 7796 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7797 /// when these variables are captured by the lambda. 7798 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7799 for (const auto &Shadow : LSI->ShadowingDecls) { 7800 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7801 // Try to avoid the warning when the shadowed decl isn't captured. 7802 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7803 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7804 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7805 ? diag::warn_decl_shadow_uncaptured_local 7806 : diag::warn_decl_shadow) 7807 << Shadow.VD->getDeclName() 7808 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7809 if (!CaptureLoc.isInvalid()) 7810 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7811 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7812 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7813 } 7814 } 7815 7816 /// Check -Wshadow without the advantage of a previous lookup. 7817 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7818 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7819 return; 7820 7821 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7822 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7823 LookupName(R, S); 7824 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7825 CheckShadow(D, ShadowedDecl, R); 7826 } 7827 7828 /// Check if 'E', which is an expression that is about to be modified, refers 7829 /// to a constructor parameter that shadows a field. 7830 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7831 // Quickly ignore expressions that can't be shadowing ctor parameters. 7832 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7833 return; 7834 E = E->IgnoreParenImpCasts(); 7835 auto *DRE = dyn_cast<DeclRefExpr>(E); 7836 if (!DRE) 7837 return; 7838 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7839 auto I = ShadowingDecls.find(D); 7840 if (I == ShadowingDecls.end()) 7841 return; 7842 const NamedDecl *ShadowedDecl = I->second; 7843 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7844 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7845 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7846 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7847 7848 // Avoid issuing multiple warnings about the same decl. 7849 ShadowingDecls.erase(I); 7850 } 7851 7852 /// Check for conflict between this global or extern "C" declaration and 7853 /// previous global or extern "C" declarations. This is only used in C++. 7854 template<typename T> 7855 static bool checkGlobalOrExternCConflict( 7856 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7857 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7858 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7859 7860 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7861 // The common case: this global doesn't conflict with any extern "C" 7862 // declaration. 7863 return false; 7864 } 7865 7866 if (Prev) { 7867 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7868 // Both the old and new declarations have C language linkage. This is a 7869 // redeclaration. 7870 Previous.clear(); 7871 Previous.addDecl(Prev); 7872 return true; 7873 } 7874 7875 // This is a global, non-extern "C" declaration, and there is a previous 7876 // non-global extern "C" declaration. Diagnose if this is a variable 7877 // declaration. 7878 if (!isa<VarDecl>(ND)) 7879 return false; 7880 } else { 7881 // The declaration is extern "C". Check for any declaration in the 7882 // translation unit which might conflict. 7883 if (IsGlobal) { 7884 // We have already performed the lookup into the translation unit. 7885 IsGlobal = false; 7886 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7887 I != E; ++I) { 7888 if (isa<VarDecl>(*I)) { 7889 Prev = *I; 7890 break; 7891 } 7892 } 7893 } else { 7894 DeclContext::lookup_result R = 7895 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7896 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7897 I != E; ++I) { 7898 if (isa<VarDecl>(*I)) { 7899 Prev = *I; 7900 break; 7901 } 7902 // FIXME: If we have any other entity with this name in global scope, 7903 // the declaration is ill-formed, but that is a defect: it breaks the 7904 // 'stat' hack, for instance. Only variables can have mangled name 7905 // clashes with extern "C" declarations, so only they deserve a 7906 // diagnostic. 7907 } 7908 } 7909 7910 if (!Prev) 7911 return false; 7912 } 7913 7914 // Use the first declaration's location to ensure we point at something which 7915 // is lexically inside an extern "C" linkage-spec. 7916 assert(Prev && "should have found a previous declaration to diagnose"); 7917 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7918 Prev = FD->getFirstDecl(); 7919 else 7920 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7921 7922 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7923 << IsGlobal << ND; 7924 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7925 << IsGlobal; 7926 return false; 7927 } 7928 7929 /// Apply special rules for handling extern "C" declarations. Returns \c true 7930 /// if we have found that this is a redeclaration of some prior entity. 7931 /// 7932 /// Per C++ [dcl.link]p6: 7933 /// Two declarations [for a function or variable] with C language linkage 7934 /// with the same name that appear in different scopes refer to the same 7935 /// [entity]. An entity with C language linkage shall not be declared with 7936 /// the same name as an entity in global scope. 7937 template<typename T> 7938 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7939 LookupResult &Previous) { 7940 if (!S.getLangOpts().CPlusPlus) { 7941 // In C, when declaring a global variable, look for a corresponding 'extern' 7942 // variable declared in function scope. We don't need this in C++, because 7943 // we find local extern decls in the surrounding file-scope DeclContext. 7944 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7945 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7946 Previous.clear(); 7947 Previous.addDecl(Prev); 7948 return true; 7949 } 7950 } 7951 return false; 7952 } 7953 7954 // A declaration in the translation unit can conflict with an extern "C" 7955 // declaration. 7956 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7957 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7958 7959 // An extern "C" declaration can conflict with a declaration in the 7960 // translation unit or can be a redeclaration of an extern "C" declaration 7961 // in another scope. 7962 if (isIncompleteDeclExternC(S,ND)) 7963 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7964 7965 // Neither global nor extern "C": nothing to do. 7966 return false; 7967 } 7968 7969 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7970 // If the decl is already known invalid, don't check it. 7971 if (NewVD->isInvalidDecl()) 7972 return; 7973 7974 QualType T = NewVD->getType(); 7975 7976 // Defer checking an 'auto' type until its initializer is attached. 7977 if (T->isUndeducedType()) 7978 return; 7979 7980 if (NewVD->hasAttrs()) 7981 CheckAlignasUnderalignment(NewVD); 7982 7983 if (T->isObjCObjectType()) { 7984 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7985 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7986 T = Context.getObjCObjectPointerType(T); 7987 NewVD->setType(T); 7988 } 7989 7990 // Emit an error if an address space was applied to decl with local storage. 7991 // This includes arrays of objects with address space qualifiers, but not 7992 // automatic variables that point to other address spaces. 7993 // ISO/IEC TR 18037 S5.1.2 7994 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7995 T.getAddressSpace() != LangAS::Default) { 7996 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7997 NewVD->setInvalidDecl(); 7998 return; 7999 } 8000 8001 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8002 // scope. 8003 if (getLangOpts().OpenCLVersion == 120 && 8004 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8005 getLangOpts()) && 8006 NewVD->isStaticLocal()) { 8007 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8008 NewVD->setInvalidDecl(); 8009 return; 8010 } 8011 8012 if (getLangOpts().OpenCL) { 8013 if (!diagnoseOpenCLTypes(*this, NewVD)) 8014 return; 8015 8016 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8017 if (NewVD->hasAttr<BlocksAttr>()) { 8018 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8019 return; 8020 } 8021 8022 if (T->isBlockPointerType()) { 8023 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8024 // can't use 'extern' storage class. 8025 if (!T.isConstQualified()) { 8026 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8027 << 0 /*const*/; 8028 NewVD->setInvalidDecl(); 8029 return; 8030 } 8031 if (NewVD->hasExternalStorage()) { 8032 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8033 NewVD->setInvalidDecl(); 8034 return; 8035 } 8036 } 8037 8038 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8039 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8040 NewVD->hasExternalStorage()) { 8041 if (!T->isSamplerT() && !T->isDependentType() && 8042 !(T.getAddressSpace() == LangAS::opencl_constant || 8043 (T.getAddressSpace() == LangAS::opencl_global && 8044 getOpenCLOptions().areProgramScopeVariablesSupported( 8045 getLangOpts())))) { 8046 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8047 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8048 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8049 << Scope << "global or constant"; 8050 else 8051 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8052 << Scope << "constant"; 8053 NewVD->setInvalidDecl(); 8054 return; 8055 } 8056 } else { 8057 if (T.getAddressSpace() == LangAS::opencl_global) { 8058 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8059 << 1 /*is any function*/ << "global"; 8060 NewVD->setInvalidDecl(); 8061 return; 8062 } 8063 if (T.getAddressSpace() == LangAS::opencl_constant || 8064 T.getAddressSpace() == LangAS::opencl_local) { 8065 FunctionDecl *FD = getCurFunctionDecl(); 8066 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8067 // in functions. 8068 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8069 if (T.getAddressSpace() == LangAS::opencl_constant) 8070 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8071 << 0 /*non-kernel only*/ << "constant"; 8072 else 8073 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8074 << 0 /*non-kernel only*/ << "local"; 8075 NewVD->setInvalidDecl(); 8076 return; 8077 } 8078 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8079 // in the outermost scope of a kernel function. 8080 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8081 if (!getCurScope()->isFunctionScope()) { 8082 if (T.getAddressSpace() == LangAS::opencl_constant) 8083 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8084 << "constant"; 8085 else 8086 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8087 << "local"; 8088 NewVD->setInvalidDecl(); 8089 return; 8090 } 8091 } 8092 } else if (T.getAddressSpace() != LangAS::opencl_private && 8093 // If we are parsing a template we didn't deduce an addr 8094 // space yet. 8095 T.getAddressSpace() != LangAS::Default) { 8096 // Do not allow other address spaces on automatic variable. 8097 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8098 NewVD->setInvalidDecl(); 8099 return; 8100 } 8101 } 8102 } 8103 8104 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8105 && !NewVD->hasAttr<BlocksAttr>()) { 8106 if (getLangOpts().getGC() != LangOptions::NonGC) 8107 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8108 else { 8109 assert(!getLangOpts().ObjCAutoRefCount); 8110 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8111 } 8112 } 8113 8114 bool isVM = T->isVariablyModifiedType(); 8115 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8116 NewVD->hasAttr<BlocksAttr>()) 8117 setFunctionHasBranchProtectedScope(); 8118 8119 if ((isVM && NewVD->hasLinkage()) || 8120 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8121 bool SizeIsNegative; 8122 llvm::APSInt Oversized; 8123 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8124 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8125 QualType FixedT; 8126 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8127 FixedT = FixedTInfo->getType(); 8128 else if (FixedTInfo) { 8129 // Type and type-as-written are canonically different. We need to fix up 8130 // both types separately. 8131 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8132 Oversized); 8133 } 8134 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8135 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8136 // FIXME: This won't give the correct result for 8137 // int a[10][n]; 8138 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8139 8140 if (NewVD->isFileVarDecl()) 8141 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8142 << SizeRange; 8143 else if (NewVD->isStaticLocal()) 8144 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8145 << SizeRange; 8146 else 8147 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8148 << SizeRange; 8149 NewVD->setInvalidDecl(); 8150 return; 8151 } 8152 8153 if (!FixedTInfo) { 8154 if (NewVD->isFileVarDecl()) 8155 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8156 else 8157 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8158 NewVD->setInvalidDecl(); 8159 return; 8160 } 8161 8162 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8163 NewVD->setType(FixedT); 8164 NewVD->setTypeSourceInfo(FixedTInfo); 8165 } 8166 8167 if (T->isVoidType()) { 8168 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8169 // of objects and functions. 8170 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8171 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8172 << T; 8173 NewVD->setInvalidDecl(); 8174 return; 8175 } 8176 } 8177 8178 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8179 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8180 NewVD->setInvalidDecl(); 8181 return; 8182 } 8183 8184 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8185 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8186 NewVD->setInvalidDecl(); 8187 return; 8188 } 8189 8190 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8191 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8192 NewVD->setInvalidDecl(); 8193 return; 8194 } 8195 8196 if (NewVD->isConstexpr() && !T->isDependentType() && 8197 RequireLiteralType(NewVD->getLocation(), T, 8198 diag::err_constexpr_var_non_literal)) { 8199 NewVD->setInvalidDecl(); 8200 return; 8201 } 8202 8203 // PPC MMA non-pointer types are not allowed as non-local variable types. 8204 if (Context.getTargetInfo().getTriple().isPPC64() && 8205 !NewVD->isLocalVarDecl() && 8206 CheckPPCMMAType(T, NewVD->getLocation())) { 8207 NewVD->setInvalidDecl(); 8208 return; 8209 } 8210 } 8211 8212 /// Perform semantic checking on a newly-created variable 8213 /// declaration. 8214 /// 8215 /// This routine performs all of the type-checking required for a 8216 /// variable declaration once it has been built. It is used both to 8217 /// check variables after they have been parsed and their declarators 8218 /// have been translated into a declaration, and to check variables 8219 /// that have been instantiated from a template. 8220 /// 8221 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8222 /// 8223 /// Returns true if the variable declaration is a redeclaration. 8224 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8225 CheckVariableDeclarationType(NewVD); 8226 8227 // If the decl is already known invalid, don't check it. 8228 if (NewVD->isInvalidDecl()) 8229 return false; 8230 8231 // If we did not find anything by this name, look for a non-visible 8232 // extern "C" declaration with the same name. 8233 if (Previous.empty() && 8234 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8235 Previous.setShadowed(); 8236 8237 if (!Previous.empty()) { 8238 MergeVarDecl(NewVD, Previous); 8239 return true; 8240 } 8241 return false; 8242 } 8243 8244 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8245 /// and if so, check that it's a valid override and remember it. 8246 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8247 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8248 8249 // Look for methods in base classes that this method might override. 8250 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8251 /*DetectVirtual=*/false); 8252 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8253 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8254 DeclarationName Name = MD->getDeclName(); 8255 8256 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8257 // We really want to find the base class destructor here. 8258 QualType T = Context.getTypeDeclType(BaseRecord); 8259 CanQualType CT = Context.getCanonicalType(T); 8260 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8261 } 8262 8263 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8264 CXXMethodDecl *BaseMD = 8265 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8266 if (!BaseMD || !BaseMD->isVirtual() || 8267 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8268 /*ConsiderCudaAttrs=*/true, 8269 // C++2a [class.virtual]p2 does not consider requires 8270 // clauses when overriding. 8271 /*ConsiderRequiresClauses=*/false)) 8272 continue; 8273 8274 if (Overridden.insert(BaseMD).second) { 8275 MD->addOverriddenMethod(BaseMD); 8276 CheckOverridingFunctionReturnType(MD, BaseMD); 8277 CheckOverridingFunctionAttributes(MD, BaseMD); 8278 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8279 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8280 } 8281 8282 // A method can only override one function from each base class. We 8283 // don't track indirectly overridden methods from bases of bases. 8284 return true; 8285 } 8286 8287 return false; 8288 }; 8289 8290 DC->lookupInBases(VisitBase, Paths); 8291 return !Overridden.empty(); 8292 } 8293 8294 namespace { 8295 // Struct for holding all of the extra arguments needed by 8296 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8297 struct ActOnFDArgs { 8298 Scope *S; 8299 Declarator &D; 8300 MultiTemplateParamsArg TemplateParamLists; 8301 bool AddToScope; 8302 }; 8303 } // end anonymous namespace 8304 8305 namespace { 8306 8307 // Callback to only accept typo corrections that have a non-zero edit distance. 8308 // Also only accept corrections that have the same parent decl. 8309 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8310 public: 8311 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8312 CXXRecordDecl *Parent) 8313 : Context(Context), OriginalFD(TypoFD), 8314 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8315 8316 bool ValidateCandidate(const TypoCorrection &candidate) override { 8317 if (candidate.getEditDistance() == 0) 8318 return false; 8319 8320 SmallVector<unsigned, 1> MismatchedParams; 8321 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8322 CDeclEnd = candidate.end(); 8323 CDecl != CDeclEnd; ++CDecl) { 8324 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8325 8326 if (FD && !FD->hasBody() && 8327 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8328 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8329 CXXRecordDecl *Parent = MD->getParent(); 8330 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8331 return true; 8332 } else if (!ExpectedParent) { 8333 return true; 8334 } 8335 } 8336 } 8337 8338 return false; 8339 } 8340 8341 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8342 return std::make_unique<DifferentNameValidatorCCC>(*this); 8343 } 8344 8345 private: 8346 ASTContext &Context; 8347 FunctionDecl *OriginalFD; 8348 CXXRecordDecl *ExpectedParent; 8349 }; 8350 8351 } // end anonymous namespace 8352 8353 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8354 TypoCorrectedFunctionDefinitions.insert(F); 8355 } 8356 8357 /// Generate diagnostics for an invalid function redeclaration. 8358 /// 8359 /// This routine handles generating the diagnostic messages for an invalid 8360 /// function redeclaration, including finding possible similar declarations 8361 /// or performing typo correction if there are no previous declarations with 8362 /// the same name. 8363 /// 8364 /// Returns a NamedDecl iff typo correction was performed and substituting in 8365 /// the new declaration name does not cause new errors. 8366 static NamedDecl *DiagnoseInvalidRedeclaration( 8367 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8368 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8369 DeclarationName Name = NewFD->getDeclName(); 8370 DeclContext *NewDC = NewFD->getDeclContext(); 8371 SmallVector<unsigned, 1> MismatchedParams; 8372 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8373 TypoCorrection Correction; 8374 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8375 unsigned DiagMsg = 8376 IsLocalFriend ? diag::err_no_matching_local_friend : 8377 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8378 diag::err_member_decl_does_not_match; 8379 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8380 IsLocalFriend ? Sema::LookupLocalFriendName 8381 : Sema::LookupOrdinaryName, 8382 Sema::ForVisibleRedeclaration); 8383 8384 NewFD->setInvalidDecl(); 8385 if (IsLocalFriend) 8386 SemaRef.LookupName(Prev, S); 8387 else 8388 SemaRef.LookupQualifiedName(Prev, NewDC); 8389 assert(!Prev.isAmbiguous() && 8390 "Cannot have an ambiguity in previous-declaration lookup"); 8391 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8392 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8393 MD ? MD->getParent() : nullptr); 8394 if (!Prev.empty()) { 8395 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8396 Func != FuncEnd; ++Func) { 8397 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8398 if (FD && 8399 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8400 // Add 1 to the index so that 0 can mean the mismatch didn't 8401 // involve a parameter 8402 unsigned ParamNum = 8403 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8404 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8405 } 8406 } 8407 // If the qualified name lookup yielded nothing, try typo correction 8408 } else if ((Correction = SemaRef.CorrectTypo( 8409 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8410 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8411 IsLocalFriend ? nullptr : NewDC))) { 8412 // Set up everything for the call to ActOnFunctionDeclarator 8413 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8414 ExtraArgs.D.getIdentifierLoc()); 8415 Previous.clear(); 8416 Previous.setLookupName(Correction.getCorrection()); 8417 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8418 CDeclEnd = Correction.end(); 8419 CDecl != CDeclEnd; ++CDecl) { 8420 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8421 if (FD && !FD->hasBody() && 8422 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8423 Previous.addDecl(FD); 8424 } 8425 } 8426 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8427 8428 NamedDecl *Result; 8429 // Retry building the function declaration with the new previous 8430 // declarations, and with errors suppressed. 8431 { 8432 // Trap errors. 8433 Sema::SFINAETrap Trap(SemaRef); 8434 8435 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8436 // pieces need to verify the typo-corrected C++ declaration and hopefully 8437 // eliminate the need for the parameter pack ExtraArgs. 8438 Result = SemaRef.ActOnFunctionDeclarator( 8439 ExtraArgs.S, ExtraArgs.D, 8440 Correction.getCorrectionDecl()->getDeclContext(), 8441 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8442 ExtraArgs.AddToScope); 8443 8444 if (Trap.hasErrorOccurred()) 8445 Result = nullptr; 8446 } 8447 8448 if (Result) { 8449 // Determine which correction we picked. 8450 Decl *Canonical = Result->getCanonicalDecl(); 8451 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8452 I != E; ++I) 8453 if ((*I)->getCanonicalDecl() == Canonical) 8454 Correction.setCorrectionDecl(*I); 8455 8456 // Let Sema know about the correction. 8457 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8458 SemaRef.diagnoseTypo( 8459 Correction, 8460 SemaRef.PDiag(IsLocalFriend 8461 ? diag::err_no_matching_local_friend_suggest 8462 : diag::err_member_decl_does_not_match_suggest) 8463 << Name << NewDC << IsDefinition); 8464 return Result; 8465 } 8466 8467 // Pretend the typo correction never occurred 8468 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8469 ExtraArgs.D.getIdentifierLoc()); 8470 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8471 Previous.clear(); 8472 Previous.setLookupName(Name); 8473 } 8474 8475 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8476 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8477 8478 bool NewFDisConst = false; 8479 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8480 NewFDisConst = NewMD->isConst(); 8481 8482 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8483 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8484 NearMatch != NearMatchEnd; ++NearMatch) { 8485 FunctionDecl *FD = NearMatch->first; 8486 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8487 bool FDisConst = MD && MD->isConst(); 8488 bool IsMember = MD || !IsLocalFriend; 8489 8490 // FIXME: These notes are poorly worded for the local friend case. 8491 if (unsigned Idx = NearMatch->second) { 8492 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8493 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8494 if (Loc.isInvalid()) Loc = FD->getLocation(); 8495 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8496 : diag::note_local_decl_close_param_match) 8497 << Idx << FDParam->getType() 8498 << NewFD->getParamDecl(Idx - 1)->getType(); 8499 } else if (FDisConst != NewFDisConst) { 8500 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8501 << NewFDisConst << FD->getSourceRange().getEnd(); 8502 } else 8503 SemaRef.Diag(FD->getLocation(), 8504 IsMember ? diag::note_member_def_close_match 8505 : diag::note_local_decl_close_match); 8506 } 8507 return nullptr; 8508 } 8509 8510 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8511 switch (D.getDeclSpec().getStorageClassSpec()) { 8512 default: llvm_unreachable("Unknown storage class!"); 8513 case DeclSpec::SCS_auto: 8514 case DeclSpec::SCS_register: 8515 case DeclSpec::SCS_mutable: 8516 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8517 diag::err_typecheck_sclass_func); 8518 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8519 D.setInvalidType(); 8520 break; 8521 case DeclSpec::SCS_unspecified: break; 8522 case DeclSpec::SCS_extern: 8523 if (D.getDeclSpec().isExternInLinkageSpec()) 8524 return SC_None; 8525 return SC_Extern; 8526 case DeclSpec::SCS_static: { 8527 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8528 // C99 6.7.1p5: 8529 // The declaration of an identifier for a function that has 8530 // block scope shall have no explicit storage-class specifier 8531 // other than extern 8532 // See also (C++ [dcl.stc]p4). 8533 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8534 diag::err_static_block_func); 8535 break; 8536 } else 8537 return SC_Static; 8538 } 8539 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8540 } 8541 8542 // No explicit storage class has already been returned 8543 return SC_None; 8544 } 8545 8546 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8547 DeclContext *DC, QualType &R, 8548 TypeSourceInfo *TInfo, 8549 StorageClass SC, 8550 bool &IsVirtualOkay) { 8551 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8552 DeclarationName Name = NameInfo.getName(); 8553 8554 FunctionDecl *NewFD = nullptr; 8555 bool isInline = D.getDeclSpec().isInlineSpecified(); 8556 8557 if (!SemaRef.getLangOpts().CPlusPlus) { 8558 // Determine whether the function was written with a 8559 // prototype. This true when: 8560 // - there is a prototype in the declarator, or 8561 // - the type R of the function is some kind of typedef or other non- 8562 // attributed reference to a type name (which eventually refers to a 8563 // function type). 8564 bool HasPrototype = 8565 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8566 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8567 8568 NewFD = FunctionDecl::Create( 8569 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8570 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8571 ConstexprSpecKind::Unspecified, 8572 /*TrailingRequiresClause=*/nullptr); 8573 if (D.isInvalidType()) 8574 NewFD->setInvalidDecl(); 8575 8576 return NewFD; 8577 } 8578 8579 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8580 8581 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8582 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8583 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8584 diag::err_constexpr_wrong_decl_kind) 8585 << static_cast<int>(ConstexprKind); 8586 ConstexprKind = ConstexprSpecKind::Unspecified; 8587 D.getMutableDeclSpec().ClearConstexprSpec(); 8588 } 8589 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8590 8591 // Check that the return type is not an abstract class type. 8592 // For record types, this is done by the AbstractClassUsageDiagnoser once 8593 // the class has been completely parsed. 8594 if (!DC->isRecord() && 8595 SemaRef.RequireNonAbstractType( 8596 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8597 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8598 D.setInvalidType(); 8599 8600 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8601 // This is a C++ constructor declaration. 8602 assert(DC->isRecord() && 8603 "Constructors can only be declared in a member context"); 8604 8605 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8606 return CXXConstructorDecl::Create( 8607 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8608 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8609 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8610 InheritedConstructor(), TrailingRequiresClause); 8611 8612 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8613 // This is a C++ destructor declaration. 8614 if (DC->isRecord()) { 8615 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8616 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8617 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8618 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8619 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8620 /*isImplicitlyDeclared=*/false, ConstexprKind, 8621 TrailingRequiresClause); 8622 8623 // If the destructor needs an implicit exception specification, set it 8624 // now. FIXME: It'd be nice to be able to create the right type to start 8625 // with, but the type needs to reference the destructor declaration. 8626 if (SemaRef.getLangOpts().CPlusPlus11) 8627 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8628 8629 IsVirtualOkay = true; 8630 return NewDD; 8631 8632 } else { 8633 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8634 D.setInvalidType(); 8635 8636 // Create a FunctionDecl to satisfy the function definition parsing 8637 // code path. 8638 return FunctionDecl::Create( 8639 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8640 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8641 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8642 } 8643 8644 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8645 if (!DC->isRecord()) { 8646 SemaRef.Diag(D.getIdentifierLoc(), 8647 diag::err_conv_function_not_member); 8648 return nullptr; 8649 } 8650 8651 SemaRef.CheckConversionDeclarator(D, R, SC); 8652 if (D.isInvalidType()) 8653 return nullptr; 8654 8655 IsVirtualOkay = true; 8656 return CXXConversionDecl::Create( 8657 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8658 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8659 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8660 TrailingRequiresClause); 8661 8662 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8663 if (TrailingRequiresClause) 8664 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8665 diag::err_trailing_requires_clause_on_deduction_guide) 8666 << TrailingRequiresClause->getSourceRange(); 8667 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8668 8669 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8670 ExplicitSpecifier, NameInfo, R, TInfo, 8671 D.getEndLoc()); 8672 } else if (DC->isRecord()) { 8673 // If the name of the function is the same as the name of the record, 8674 // then this must be an invalid constructor that has a return type. 8675 // (The parser checks for a return type and makes the declarator a 8676 // constructor if it has no return type). 8677 if (Name.getAsIdentifierInfo() && 8678 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8679 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8680 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8681 << SourceRange(D.getIdentifierLoc()); 8682 return nullptr; 8683 } 8684 8685 // This is a C++ method declaration. 8686 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8687 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8688 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8689 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8690 IsVirtualOkay = !Ret->isStatic(); 8691 return Ret; 8692 } else { 8693 bool isFriend = 8694 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8695 if (!isFriend && SemaRef.CurContext->isRecord()) 8696 return nullptr; 8697 8698 // Determine whether the function was written with a 8699 // prototype. This true when: 8700 // - we're in C++ (where every function has a prototype), 8701 return FunctionDecl::Create( 8702 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8703 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8704 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8705 } 8706 } 8707 8708 enum OpenCLParamType { 8709 ValidKernelParam, 8710 PtrPtrKernelParam, 8711 PtrKernelParam, 8712 InvalidAddrSpacePtrKernelParam, 8713 InvalidKernelParam, 8714 RecordKernelParam 8715 }; 8716 8717 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8718 // Size dependent types are just typedefs to normal integer types 8719 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8720 // integers other than by their names. 8721 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8722 8723 // Remove typedefs one by one until we reach a typedef 8724 // for a size dependent type. 8725 QualType DesugaredTy = Ty; 8726 do { 8727 ArrayRef<StringRef> Names(SizeTypeNames); 8728 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8729 if (Names.end() != Match) 8730 return true; 8731 8732 Ty = DesugaredTy; 8733 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8734 } while (DesugaredTy != Ty); 8735 8736 return false; 8737 } 8738 8739 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8740 if (PT->isDependentType()) 8741 return InvalidKernelParam; 8742 8743 if (PT->isPointerType() || PT->isReferenceType()) { 8744 QualType PointeeType = PT->getPointeeType(); 8745 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8746 PointeeType.getAddressSpace() == LangAS::opencl_private || 8747 PointeeType.getAddressSpace() == LangAS::Default) 8748 return InvalidAddrSpacePtrKernelParam; 8749 8750 if (PointeeType->isPointerType()) { 8751 // This is a pointer to pointer parameter. 8752 // Recursively check inner type. 8753 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8754 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8755 ParamKind == InvalidKernelParam) 8756 return ParamKind; 8757 8758 return PtrPtrKernelParam; 8759 } 8760 8761 // C++ for OpenCL v1.0 s2.4: 8762 // Moreover the types used in parameters of the kernel functions must be: 8763 // Standard layout types for pointer parameters. The same applies to 8764 // reference if an implementation supports them in kernel parameters. 8765 if (S.getLangOpts().OpenCLCPlusPlus && 8766 !S.getOpenCLOptions().isAvailableOption( 8767 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8768 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8769 !PointeeType->isStandardLayoutType()) 8770 return InvalidKernelParam; 8771 8772 return PtrKernelParam; 8773 } 8774 8775 // OpenCL v1.2 s6.9.k: 8776 // Arguments to kernel functions in a program cannot be declared with the 8777 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8778 // uintptr_t or a struct and/or union that contain fields declared to be one 8779 // of these built-in scalar types. 8780 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8781 return InvalidKernelParam; 8782 8783 if (PT->isImageType()) 8784 return PtrKernelParam; 8785 8786 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8787 return InvalidKernelParam; 8788 8789 // OpenCL extension spec v1.2 s9.5: 8790 // This extension adds support for half scalar and vector types as built-in 8791 // types that can be used for arithmetic operations, conversions etc. 8792 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8793 PT->isHalfType()) 8794 return InvalidKernelParam; 8795 8796 // Look into an array argument to check if it has a forbidden type. 8797 if (PT->isArrayType()) { 8798 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8799 // Call ourself to check an underlying type of an array. Since the 8800 // getPointeeOrArrayElementType returns an innermost type which is not an 8801 // array, this recursive call only happens once. 8802 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8803 } 8804 8805 // C++ for OpenCL v1.0 s2.4: 8806 // Moreover the types used in parameters of the kernel functions must be: 8807 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8808 // types) for parameters passed by value; 8809 if (S.getLangOpts().OpenCLCPlusPlus && 8810 !S.getOpenCLOptions().isAvailableOption( 8811 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8812 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 8813 return InvalidKernelParam; 8814 8815 if (PT->isRecordType()) 8816 return RecordKernelParam; 8817 8818 return ValidKernelParam; 8819 } 8820 8821 static void checkIsValidOpenCLKernelParameter( 8822 Sema &S, 8823 Declarator &D, 8824 ParmVarDecl *Param, 8825 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8826 QualType PT = Param->getType(); 8827 8828 // Cache the valid types we encounter to avoid rechecking structs that are 8829 // used again 8830 if (ValidTypes.count(PT.getTypePtr())) 8831 return; 8832 8833 switch (getOpenCLKernelParameterType(S, PT)) { 8834 case PtrPtrKernelParam: 8835 // OpenCL v3.0 s6.11.a: 8836 // A kernel function argument cannot be declared as a pointer to a pointer 8837 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8838 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 8839 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8840 D.setInvalidType(); 8841 return; 8842 } 8843 8844 ValidTypes.insert(PT.getTypePtr()); 8845 return; 8846 8847 case InvalidAddrSpacePtrKernelParam: 8848 // OpenCL v1.0 s6.5: 8849 // __kernel function arguments declared to be a pointer of a type can point 8850 // to one of the following address spaces only : __global, __local or 8851 // __constant. 8852 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8853 D.setInvalidType(); 8854 return; 8855 8856 // OpenCL v1.2 s6.9.k: 8857 // Arguments to kernel functions in a program cannot be declared with the 8858 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8859 // uintptr_t or a struct and/or union that contain fields declared to be 8860 // one of these built-in scalar types. 8861 8862 case InvalidKernelParam: 8863 // OpenCL v1.2 s6.8 n: 8864 // A kernel function argument cannot be declared 8865 // of event_t type. 8866 // Do not diagnose half type since it is diagnosed as invalid argument 8867 // type for any function elsewhere. 8868 if (!PT->isHalfType()) { 8869 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8870 8871 // Explain what typedefs are involved. 8872 const TypedefType *Typedef = nullptr; 8873 while ((Typedef = PT->getAs<TypedefType>())) { 8874 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8875 // SourceLocation may be invalid for a built-in type. 8876 if (Loc.isValid()) 8877 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8878 PT = Typedef->desugar(); 8879 } 8880 } 8881 8882 D.setInvalidType(); 8883 return; 8884 8885 case PtrKernelParam: 8886 case ValidKernelParam: 8887 ValidTypes.insert(PT.getTypePtr()); 8888 return; 8889 8890 case RecordKernelParam: 8891 break; 8892 } 8893 8894 // Track nested structs we will inspect 8895 SmallVector<const Decl *, 4> VisitStack; 8896 8897 // Track where we are in the nested structs. Items will migrate from 8898 // VisitStack to HistoryStack as we do the DFS for bad field. 8899 SmallVector<const FieldDecl *, 4> HistoryStack; 8900 HistoryStack.push_back(nullptr); 8901 8902 // At this point we already handled everything except of a RecordType or 8903 // an ArrayType of a RecordType. 8904 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8905 const RecordType *RecTy = 8906 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8907 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8908 8909 VisitStack.push_back(RecTy->getDecl()); 8910 assert(VisitStack.back() && "First decl null?"); 8911 8912 do { 8913 const Decl *Next = VisitStack.pop_back_val(); 8914 if (!Next) { 8915 assert(!HistoryStack.empty()); 8916 // Found a marker, we have gone up a level 8917 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8918 ValidTypes.insert(Hist->getType().getTypePtr()); 8919 8920 continue; 8921 } 8922 8923 // Adds everything except the original parameter declaration (which is not a 8924 // field itself) to the history stack. 8925 const RecordDecl *RD; 8926 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8927 HistoryStack.push_back(Field); 8928 8929 QualType FieldTy = Field->getType(); 8930 // Other field types (known to be valid or invalid) are handled while we 8931 // walk around RecordDecl::fields(). 8932 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8933 "Unexpected type."); 8934 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8935 8936 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8937 } else { 8938 RD = cast<RecordDecl>(Next); 8939 } 8940 8941 // Add a null marker so we know when we've gone back up a level 8942 VisitStack.push_back(nullptr); 8943 8944 for (const auto *FD : RD->fields()) { 8945 QualType QT = FD->getType(); 8946 8947 if (ValidTypes.count(QT.getTypePtr())) 8948 continue; 8949 8950 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8951 if (ParamType == ValidKernelParam) 8952 continue; 8953 8954 if (ParamType == RecordKernelParam) { 8955 VisitStack.push_back(FD); 8956 continue; 8957 } 8958 8959 // OpenCL v1.2 s6.9.p: 8960 // Arguments to kernel functions that are declared to be a struct or union 8961 // do not allow OpenCL objects to be passed as elements of the struct or 8962 // union. 8963 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8964 ParamType == InvalidAddrSpacePtrKernelParam) { 8965 S.Diag(Param->getLocation(), 8966 diag::err_record_with_pointers_kernel_param) 8967 << PT->isUnionType() 8968 << PT; 8969 } else { 8970 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8971 } 8972 8973 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8974 << OrigRecDecl->getDeclName(); 8975 8976 // We have an error, now let's go back up through history and show where 8977 // the offending field came from 8978 for (ArrayRef<const FieldDecl *>::const_iterator 8979 I = HistoryStack.begin() + 1, 8980 E = HistoryStack.end(); 8981 I != E; ++I) { 8982 const FieldDecl *OuterField = *I; 8983 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8984 << OuterField->getType(); 8985 } 8986 8987 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8988 << QT->isPointerType() 8989 << QT; 8990 D.setInvalidType(); 8991 return; 8992 } 8993 } while (!VisitStack.empty()); 8994 } 8995 8996 /// Find the DeclContext in which a tag is implicitly declared if we see an 8997 /// elaborated type specifier in the specified context, and lookup finds 8998 /// nothing. 8999 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9000 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9001 DC = DC->getParent(); 9002 return DC; 9003 } 9004 9005 /// Find the Scope in which a tag is implicitly declared if we see an 9006 /// elaborated type specifier in the specified context, and lookup finds 9007 /// nothing. 9008 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9009 while (S->isClassScope() || 9010 (LangOpts.CPlusPlus && 9011 S->isFunctionPrototypeScope()) || 9012 ((S->getFlags() & Scope::DeclScope) == 0) || 9013 (S->getEntity() && S->getEntity()->isTransparentContext())) 9014 S = S->getParent(); 9015 return S; 9016 } 9017 9018 NamedDecl* 9019 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9020 TypeSourceInfo *TInfo, LookupResult &Previous, 9021 MultiTemplateParamsArg TemplateParamListsRef, 9022 bool &AddToScope) { 9023 QualType R = TInfo->getType(); 9024 9025 assert(R->isFunctionType()); 9026 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9027 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9028 9029 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9030 for (TemplateParameterList *TPL : TemplateParamListsRef) 9031 TemplateParamLists.push_back(TPL); 9032 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9033 if (!TemplateParamLists.empty() && 9034 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9035 TemplateParamLists.back() = Invented; 9036 else 9037 TemplateParamLists.push_back(Invented); 9038 } 9039 9040 // TODO: consider using NameInfo for diagnostic. 9041 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9042 DeclarationName Name = NameInfo.getName(); 9043 StorageClass SC = getFunctionStorageClass(*this, D); 9044 9045 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9046 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9047 diag::err_invalid_thread) 9048 << DeclSpec::getSpecifierName(TSCS); 9049 9050 if (D.isFirstDeclarationOfMember()) 9051 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9052 D.getIdentifierLoc()); 9053 9054 bool isFriend = false; 9055 FunctionTemplateDecl *FunctionTemplate = nullptr; 9056 bool isMemberSpecialization = false; 9057 bool isFunctionTemplateSpecialization = false; 9058 9059 bool isDependentClassScopeExplicitSpecialization = false; 9060 bool HasExplicitTemplateArgs = false; 9061 TemplateArgumentListInfo TemplateArgs; 9062 9063 bool isVirtualOkay = false; 9064 9065 DeclContext *OriginalDC = DC; 9066 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9067 9068 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9069 isVirtualOkay); 9070 if (!NewFD) return nullptr; 9071 9072 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9073 NewFD->setTopLevelDeclInObjCContainer(); 9074 9075 // Set the lexical context. If this is a function-scope declaration, or has a 9076 // C++ scope specifier, or is the object of a friend declaration, the lexical 9077 // context will be different from the semantic context. 9078 NewFD->setLexicalDeclContext(CurContext); 9079 9080 if (IsLocalExternDecl) 9081 NewFD->setLocalExternDecl(); 9082 9083 if (getLangOpts().CPlusPlus) { 9084 bool isInline = D.getDeclSpec().isInlineSpecified(); 9085 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9086 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9087 isFriend = D.getDeclSpec().isFriendSpecified(); 9088 if (isFriend && !isInline && D.isFunctionDefinition()) { 9089 // C++ [class.friend]p5 9090 // A function can be defined in a friend declaration of a 9091 // class . . . . Such a function is implicitly inline. 9092 NewFD->setImplicitlyInline(); 9093 } 9094 9095 // If this is a method defined in an __interface, and is not a constructor 9096 // or an overloaded operator, then set the pure flag (isVirtual will already 9097 // return true). 9098 if (const CXXRecordDecl *Parent = 9099 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9100 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9101 NewFD->setPure(true); 9102 9103 // C++ [class.union]p2 9104 // A union can have member functions, but not virtual functions. 9105 if (isVirtual && Parent->isUnion()) 9106 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9107 } 9108 9109 SetNestedNameSpecifier(*this, NewFD, D); 9110 isMemberSpecialization = false; 9111 isFunctionTemplateSpecialization = false; 9112 if (D.isInvalidType()) 9113 NewFD->setInvalidDecl(); 9114 9115 // Match up the template parameter lists with the scope specifier, then 9116 // determine whether we have a template or a template specialization. 9117 bool Invalid = false; 9118 TemplateParameterList *TemplateParams = 9119 MatchTemplateParametersToScopeSpecifier( 9120 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9121 D.getCXXScopeSpec(), 9122 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9123 ? D.getName().TemplateId 9124 : nullptr, 9125 TemplateParamLists, isFriend, isMemberSpecialization, 9126 Invalid); 9127 if (TemplateParams) { 9128 // Check that we can declare a template here. 9129 if (CheckTemplateDeclScope(S, TemplateParams)) 9130 NewFD->setInvalidDecl(); 9131 9132 if (TemplateParams->size() > 0) { 9133 // This is a function template 9134 9135 // A destructor cannot be a template. 9136 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9137 Diag(NewFD->getLocation(), diag::err_destructor_template); 9138 NewFD->setInvalidDecl(); 9139 } 9140 9141 // If we're adding a template to a dependent context, we may need to 9142 // rebuilding some of the types used within the template parameter list, 9143 // now that we know what the current instantiation is. 9144 if (DC->isDependentContext()) { 9145 ContextRAII SavedContext(*this, DC); 9146 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9147 Invalid = true; 9148 } 9149 9150 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9151 NewFD->getLocation(), 9152 Name, TemplateParams, 9153 NewFD); 9154 FunctionTemplate->setLexicalDeclContext(CurContext); 9155 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9156 9157 // For source fidelity, store the other template param lists. 9158 if (TemplateParamLists.size() > 1) { 9159 NewFD->setTemplateParameterListsInfo(Context, 9160 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9161 .drop_back(1)); 9162 } 9163 } else { 9164 // This is a function template specialization. 9165 isFunctionTemplateSpecialization = true; 9166 // For source fidelity, store all the template param lists. 9167 if (TemplateParamLists.size() > 0) 9168 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9169 9170 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9171 if (isFriend) { 9172 // We want to remove the "template<>", found here. 9173 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9174 9175 // If we remove the template<> and the name is not a 9176 // template-id, we're actually silently creating a problem: 9177 // the friend declaration will refer to an untemplated decl, 9178 // and clearly the user wants a template specialization. So 9179 // we need to insert '<>' after the name. 9180 SourceLocation InsertLoc; 9181 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9182 InsertLoc = D.getName().getSourceRange().getEnd(); 9183 InsertLoc = getLocForEndOfToken(InsertLoc); 9184 } 9185 9186 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9187 << Name << RemoveRange 9188 << FixItHint::CreateRemoval(RemoveRange) 9189 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9190 } 9191 } 9192 } else { 9193 // Check that we can declare a template here. 9194 if (!TemplateParamLists.empty() && isMemberSpecialization && 9195 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9196 NewFD->setInvalidDecl(); 9197 9198 // All template param lists were matched against the scope specifier: 9199 // this is NOT (an explicit specialization of) a template. 9200 if (TemplateParamLists.size() > 0) 9201 // For source fidelity, store all the template param lists. 9202 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9203 } 9204 9205 if (Invalid) { 9206 NewFD->setInvalidDecl(); 9207 if (FunctionTemplate) 9208 FunctionTemplate->setInvalidDecl(); 9209 } 9210 9211 // C++ [dcl.fct.spec]p5: 9212 // The virtual specifier shall only be used in declarations of 9213 // nonstatic class member functions that appear within a 9214 // member-specification of a class declaration; see 10.3. 9215 // 9216 if (isVirtual && !NewFD->isInvalidDecl()) { 9217 if (!isVirtualOkay) { 9218 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9219 diag::err_virtual_non_function); 9220 } else if (!CurContext->isRecord()) { 9221 // 'virtual' was specified outside of the class. 9222 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9223 diag::err_virtual_out_of_class) 9224 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9225 } else if (NewFD->getDescribedFunctionTemplate()) { 9226 // C++ [temp.mem]p3: 9227 // A member function template shall not be virtual. 9228 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9229 diag::err_virtual_member_function_template) 9230 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9231 } else { 9232 // Okay: Add virtual to the method. 9233 NewFD->setVirtualAsWritten(true); 9234 } 9235 9236 if (getLangOpts().CPlusPlus14 && 9237 NewFD->getReturnType()->isUndeducedType()) 9238 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9239 } 9240 9241 if (getLangOpts().CPlusPlus14 && 9242 (NewFD->isDependentContext() || 9243 (isFriend && CurContext->isDependentContext())) && 9244 NewFD->getReturnType()->isUndeducedType()) { 9245 // If the function template is referenced directly (for instance, as a 9246 // member of the current instantiation), pretend it has a dependent type. 9247 // This is not really justified by the standard, but is the only sane 9248 // thing to do. 9249 // FIXME: For a friend function, we have not marked the function as being 9250 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9251 const FunctionProtoType *FPT = 9252 NewFD->getType()->castAs<FunctionProtoType>(); 9253 QualType Result = 9254 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9255 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9256 FPT->getExtProtoInfo())); 9257 } 9258 9259 // C++ [dcl.fct.spec]p3: 9260 // The inline specifier shall not appear on a block scope function 9261 // declaration. 9262 if (isInline && !NewFD->isInvalidDecl()) { 9263 if (CurContext->isFunctionOrMethod()) { 9264 // 'inline' is not allowed on block scope function declaration. 9265 Diag(D.getDeclSpec().getInlineSpecLoc(), 9266 diag::err_inline_declaration_block_scope) << Name 9267 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9268 } 9269 } 9270 9271 // C++ [dcl.fct.spec]p6: 9272 // The explicit specifier shall be used only in the declaration of a 9273 // constructor or conversion function within its class definition; 9274 // see 12.3.1 and 12.3.2. 9275 if (hasExplicit && !NewFD->isInvalidDecl() && 9276 !isa<CXXDeductionGuideDecl>(NewFD)) { 9277 if (!CurContext->isRecord()) { 9278 // 'explicit' was specified outside of the class. 9279 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9280 diag::err_explicit_out_of_class) 9281 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9282 } else if (!isa<CXXConstructorDecl>(NewFD) && 9283 !isa<CXXConversionDecl>(NewFD)) { 9284 // 'explicit' was specified on a function that wasn't a constructor 9285 // or conversion function. 9286 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9287 diag::err_explicit_non_ctor_or_conv_function) 9288 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9289 } 9290 } 9291 9292 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9293 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9294 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9295 // are implicitly inline. 9296 NewFD->setImplicitlyInline(); 9297 9298 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9299 // be either constructors or to return a literal type. Therefore, 9300 // destructors cannot be declared constexpr. 9301 if (isa<CXXDestructorDecl>(NewFD) && 9302 (!getLangOpts().CPlusPlus20 || 9303 ConstexprKind == ConstexprSpecKind::Consteval)) { 9304 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9305 << static_cast<int>(ConstexprKind); 9306 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9307 ? ConstexprSpecKind::Unspecified 9308 : ConstexprSpecKind::Constexpr); 9309 } 9310 // C++20 [dcl.constexpr]p2: An allocation function, or a 9311 // deallocation function shall not be declared with the consteval 9312 // specifier. 9313 if (ConstexprKind == ConstexprSpecKind::Consteval && 9314 (NewFD->getOverloadedOperator() == OO_New || 9315 NewFD->getOverloadedOperator() == OO_Array_New || 9316 NewFD->getOverloadedOperator() == OO_Delete || 9317 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9318 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9319 diag::err_invalid_consteval_decl_kind) 9320 << NewFD; 9321 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9322 } 9323 } 9324 9325 // If __module_private__ was specified, mark the function accordingly. 9326 if (D.getDeclSpec().isModulePrivateSpecified()) { 9327 if (isFunctionTemplateSpecialization) { 9328 SourceLocation ModulePrivateLoc 9329 = D.getDeclSpec().getModulePrivateSpecLoc(); 9330 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9331 << 0 9332 << FixItHint::CreateRemoval(ModulePrivateLoc); 9333 } else { 9334 NewFD->setModulePrivate(); 9335 if (FunctionTemplate) 9336 FunctionTemplate->setModulePrivate(); 9337 } 9338 } 9339 9340 if (isFriend) { 9341 if (FunctionTemplate) { 9342 FunctionTemplate->setObjectOfFriendDecl(); 9343 FunctionTemplate->setAccess(AS_public); 9344 } 9345 NewFD->setObjectOfFriendDecl(); 9346 NewFD->setAccess(AS_public); 9347 } 9348 9349 // If a function is defined as defaulted or deleted, mark it as such now. 9350 // We'll do the relevant checks on defaulted / deleted functions later. 9351 switch (D.getFunctionDefinitionKind()) { 9352 case FunctionDefinitionKind::Declaration: 9353 case FunctionDefinitionKind::Definition: 9354 break; 9355 9356 case FunctionDefinitionKind::Defaulted: 9357 NewFD->setDefaulted(); 9358 break; 9359 9360 case FunctionDefinitionKind::Deleted: 9361 NewFD->setDeletedAsWritten(); 9362 break; 9363 } 9364 9365 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9366 D.isFunctionDefinition()) { 9367 // C++ [class.mfct]p2: 9368 // A member function may be defined (8.4) in its class definition, in 9369 // which case it is an inline member function (7.1.2) 9370 NewFD->setImplicitlyInline(); 9371 } 9372 9373 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9374 !CurContext->isRecord()) { 9375 // C++ [class.static]p1: 9376 // A data or function member of a class may be declared static 9377 // in a class definition, in which case it is a static member of 9378 // the class. 9379 9380 // Complain about the 'static' specifier if it's on an out-of-line 9381 // member function definition. 9382 9383 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9384 // member function template declaration and class member template 9385 // declaration (MSVC versions before 2015), warn about this. 9386 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9387 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9388 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9389 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9390 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9391 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9392 } 9393 9394 // C++11 [except.spec]p15: 9395 // A deallocation function with no exception-specification is treated 9396 // as if it were specified with noexcept(true). 9397 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9398 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9399 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9400 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9401 NewFD->setType(Context.getFunctionType( 9402 FPT->getReturnType(), FPT->getParamTypes(), 9403 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9404 } 9405 9406 // Filter out previous declarations that don't match the scope. 9407 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9408 D.getCXXScopeSpec().isNotEmpty() || 9409 isMemberSpecialization || 9410 isFunctionTemplateSpecialization); 9411 9412 // Handle GNU asm-label extension (encoded as an attribute). 9413 if (Expr *E = (Expr*) D.getAsmLabel()) { 9414 // The parser guarantees this is a string. 9415 StringLiteral *SE = cast<StringLiteral>(E); 9416 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9417 /*IsLiteralLabel=*/true, 9418 SE->getStrTokenLoc(0))); 9419 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9420 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9421 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9422 if (I != ExtnameUndeclaredIdentifiers.end()) { 9423 if (isDeclExternC(NewFD)) { 9424 NewFD->addAttr(I->second); 9425 ExtnameUndeclaredIdentifiers.erase(I); 9426 } else 9427 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9428 << /*Variable*/0 << NewFD; 9429 } 9430 } 9431 9432 // Copy the parameter declarations from the declarator D to the function 9433 // declaration NewFD, if they are available. First scavenge them into Params. 9434 SmallVector<ParmVarDecl*, 16> Params; 9435 unsigned FTIIdx; 9436 if (D.isFunctionDeclarator(FTIIdx)) { 9437 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9438 9439 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9440 // function that takes no arguments, not a function that takes a 9441 // single void argument. 9442 // We let through "const void" here because Sema::GetTypeForDeclarator 9443 // already checks for that case. 9444 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9445 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9446 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9447 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9448 Param->setDeclContext(NewFD); 9449 Params.push_back(Param); 9450 9451 if (Param->isInvalidDecl()) 9452 NewFD->setInvalidDecl(); 9453 } 9454 } 9455 9456 if (!getLangOpts().CPlusPlus) { 9457 // In C, find all the tag declarations from the prototype and move them 9458 // into the function DeclContext. Remove them from the surrounding tag 9459 // injection context of the function, which is typically but not always 9460 // the TU. 9461 DeclContext *PrototypeTagContext = 9462 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9463 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9464 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9465 9466 // We don't want to reparent enumerators. Look at their parent enum 9467 // instead. 9468 if (!TD) { 9469 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9470 TD = cast<EnumDecl>(ECD->getDeclContext()); 9471 } 9472 if (!TD) 9473 continue; 9474 DeclContext *TagDC = TD->getLexicalDeclContext(); 9475 if (!TagDC->containsDecl(TD)) 9476 continue; 9477 TagDC->removeDecl(TD); 9478 TD->setDeclContext(NewFD); 9479 NewFD->addDecl(TD); 9480 9481 // Preserve the lexical DeclContext if it is not the surrounding tag 9482 // injection context of the FD. In this example, the semantic context of 9483 // E will be f and the lexical context will be S, while both the 9484 // semantic and lexical contexts of S will be f: 9485 // void f(struct S { enum E { a } f; } s); 9486 if (TagDC != PrototypeTagContext) 9487 TD->setLexicalDeclContext(TagDC); 9488 } 9489 } 9490 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9491 // When we're declaring a function with a typedef, typeof, etc as in the 9492 // following example, we'll need to synthesize (unnamed) 9493 // parameters for use in the declaration. 9494 // 9495 // @code 9496 // typedef void fn(int); 9497 // fn f; 9498 // @endcode 9499 9500 // Synthesize a parameter for each argument type. 9501 for (const auto &AI : FT->param_types()) { 9502 ParmVarDecl *Param = 9503 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9504 Param->setScopeInfo(0, Params.size()); 9505 Params.push_back(Param); 9506 } 9507 } else { 9508 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9509 "Should not need args for typedef of non-prototype fn"); 9510 } 9511 9512 // Finally, we know we have the right number of parameters, install them. 9513 NewFD->setParams(Params); 9514 9515 if (D.getDeclSpec().isNoreturnSpecified()) 9516 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9517 D.getDeclSpec().getNoreturnSpecLoc(), 9518 AttributeCommonInfo::AS_Keyword)); 9519 9520 // Functions returning a variably modified type violate C99 6.7.5.2p2 9521 // because all functions have linkage. 9522 if (!NewFD->isInvalidDecl() && 9523 NewFD->getReturnType()->isVariablyModifiedType()) { 9524 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9525 NewFD->setInvalidDecl(); 9526 } 9527 9528 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9529 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9530 !NewFD->hasAttr<SectionAttr>()) 9531 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9532 Context, PragmaClangTextSection.SectionName, 9533 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9534 9535 // Apply an implicit SectionAttr if #pragma code_seg is active. 9536 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9537 !NewFD->hasAttr<SectionAttr>()) { 9538 NewFD->addAttr(SectionAttr::CreateImplicit( 9539 Context, CodeSegStack.CurrentValue->getString(), 9540 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9541 SectionAttr::Declspec_allocate)); 9542 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9543 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9544 ASTContext::PSF_Read, 9545 NewFD)) 9546 NewFD->dropAttr<SectionAttr>(); 9547 } 9548 9549 // Apply an implicit CodeSegAttr from class declspec or 9550 // apply an implicit SectionAttr from #pragma code_seg if active. 9551 if (!NewFD->hasAttr<CodeSegAttr>()) { 9552 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9553 D.isFunctionDefinition())) { 9554 NewFD->addAttr(SAttr); 9555 } 9556 } 9557 9558 // Handle attributes. 9559 ProcessDeclAttributes(S, NewFD, D); 9560 9561 if (getLangOpts().OpenCL) { 9562 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9563 // type declaration will generate a compilation error. 9564 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9565 if (AddressSpace != LangAS::Default) { 9566 Diag(NewFD->getLocation(), 9567 diag::err_opencl_return_value_with_address_space); 9568 NewFD->setInvalidDecl(); 9569 } 9570 } 9571 9572 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) 9573 checkDeviceDecl(NewFD, D.getBeginLoc()); 9574 9575 if (!getLangOpts().CPlusPlus) { 9576 // Perform semantic checking on the function declaration. 9577 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9578 CheckMain(NewFD, D.getDeclSpec()); 9579 9580 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9581 CheckMSVCRTEntryPoint(NewFD); 9582 9583 if (!NewFD->isInvalidDecl()) 9584 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9585 isMemberSpecialization)); 9586 else if (!Previous.empty()) 9587 // Recover gracefully from an invalid redeclaration. 9588 D.setRedeclaration(true); 9589 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9590 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9591 "previous declaration set still overloaded"); 9592 9593 // Diagnose no-prototype function declarations with calling conventions that 9594 // don't support variadic calls. Only do this in C and do it after merging 9595 // possibly prototyped redeclarations. 9596 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9597 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9598 CallingConv CC = FT->getExtInfo().getCC(); 9599 if (!supportsVariadicCall(CC)) { 9600 // Windows system headers sometimes accidentally use stdcall without 9601 // (void) parameters, so we relax this to a warning. 9602 int DiagID = 9603 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9604 Diag(NewFD->getLocation(), DiagID) 9605 << FunctionType::getNameForCallConv(CC); 9606 } 9607 } 9608 9609 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9610 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9611 checkNonTrivialCUnion(NewFD->getReturnType(), 9612 NewFD->getReturnTypeSourceRange().getBegin(), 9613 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9614 } else { 9615 // C++11 [replacement.functions]p3: 9616 // The program's definitions shall not be specified as inline. 9617 // 9618 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9619 // 9620 // Suppress the diagnostic if the function is __attribute__((used)), since 9621 // that forces an external definition to be emitted. 9622 if (D.getDeclSpec().isInlineSpecified() && 9623 NewFD->isReplaceableGlobalAllocationFunction() && 9624 !NewFD->hasAttr<UsedAttr>()) 9625 Diag(D.getDeclSpec().getInlineSpecLoc(), 9626 diag::ext_operator_new_delete_declared_inline) 9627 << NewFD->getDeclName(); 9628 9629 // If the declarator is a template-id, translate the parser's template 9630 // argument list into our AST format. 9631 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9632 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9633 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9634 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9635 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9636 TemplateId->NumArgs); 9637 translateTemplateArguments(TemplateArgsPtr, 9638 TemplateArgs); 9639 9640 HasExplicitTemplateArgs = true; 9641 9642 if (NewFD->isInvalidDecl()) { 9643 HasExplicitTemplateArgs = false; 9644 } else if (FunctionTemplate) { 9645 // Function template with explicit template arguments. 9646 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9647 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9648 9649 HasExplicitTemplateArgs = false; 9650 } else { 9651 assert((isFunctionTemplateSpecialization || 9652 D.getDeclSpec().isFriendSpecified()) && 9653 "should have a 'template<>' for this decl"); 9654 // "friend void foo<>(int);" is an implicit specialization decl. 9655 isFunctionTemplateSpecialization = true; 9656 } 9657 } else if (isFriend && isFunctionTemplateSpecialization) { 9658 // This combination is only possible in a recovery case; the user 9659 // wrote something like: 9660 // template <> friend void foo(int); 9661 // which we're recovering from as if the user had written: 9662 // friend void foo<>(int); 9663 // Go ahead and fake up a template id. 9664 HasExplicitTemplateArgs = true; 9665 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9666 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9667 } 9668 9669 // We do not add HD attributes to specializations here because 9670 // they may have different constexpr-ness compared to their 9671 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9672 // may end up with different effective targets. Instead, a 9673 // specialization inherits its target attributes from its template 9674 // in the CheckFunctionTemplateSpecialization() call below. 9675 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9676 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9677 9678 // If it's a friend (and only if it's a friend), it's possible 9679 // that either the specialized function type or the specialized 9680 // template is dependent, and therefore matching will fail. In 9681 // this case, don't check the specialization yet. 9682 if (isFunctionTemplateSpecialization && isFriend && 9683 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9684 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9685 TemplateArgs.arguments()))) { 9686 assert(HasExplicitTemplateArgs && 9687 "friend function specialization without template args"); 9688 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9689 Previous)) 9690 NewFD->setInvalidDecl(); 9691 } else if (isFunctionTemplateSpecialization) { 9692 if (CurContext->isDependentContext() && CurContext->isRecord() 9693 && !isFriend) { 9694 isDependentClassScopeExplicitSpecialization = true; 9695 } else if (!NewFD->isInvalidDecl() && 9696 CheckFunctionTemplateSpecialization( 9697 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9698 Previous)) 9699 NewFD->setInvalidDecl(); 9700 9701 // C++ [dcl.stc]p1: 9702 // A storage-class-specifier shall not be specified in an explicit 9703 // specialization (14.7.3) 9704 FunctionTemplateSpecializationInfo *Info = 9705 NewFD->getTemplateSpecializationInfo(); 9706 if (Info && SC != SC_None) { 9707 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9708 Diag(NewFD->getLocation(), 9709 diag::err_explicit_specialization_inconsistent_storage_class) 9710 << SC 9711 << FixItHint::CreateRemoval( 9712 D.getDeclSpec().getStorageClassSpecLoc()); 9713 9714 else 9715 Diag(NewFD->getLocation(), 9716 diag::ext_explicit_specialization_storage_class) 9717 << FixItHint::CreateRemoval( 9718 D.getDeclSpec().getStorageClassSpecLoc()); 9719 } 9720 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9721 if (CheckMemberSpecialization(NewFD, Previous)) 9722 NewFD->setInvalidDecl(); 9723 } 9724 9725 // Perform semantic checking on the function declaration. 9726 if (!isDependentClassScopeExplicitSpecialization) { 9727 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9728 CheckMain(NewFD, D.getDeclSpec()); 9729 9730 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9731 CheckMSVCRTEntryPoint(NewFD); 9732 9733 if (!NewFD->isInvalidDecl()) 9734 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9735 isMemberSpecialization)); 9736 else if (!Previous.empty()) 9737 // Recover gracefully from an invalid redeclaration. 9738 D.setRedeclaration(true); 9739 } 9740 9741 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9742 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9743 "previous declaration set still overloaded"); 9744 9745 NamedDecl *PrincipalDecl = (FunctionTemplate 9746 ? cast<NamedDecl>(FunctionTemplate) 9747 : NewFD); 9748 9749 if (isFriend && NewFD->getPreviousDecl()) { 9750 AccessSpecifier Access = AS_public; 9751 if (!NewFD->isInvalidDecl()) 9752 Access = NewFD->getPreviousDecl()->getAccess(); 9753 9754 NewFD->setAccess(Access); 9755 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9756 } 9757 9758 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9759 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9760 PrincipalDecl->setNonMemberOperator(); 9761 9762 // If we have a function template, check the template parameter 9763 // list. This will check and merge default template arguments. 9764 if (FunctionTemplate) { 9765 FunctionTemplateDecl *PrevTemplate = 9766 FunctionTemplate->getPreviousDecl(); 9767 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9768 PrevTemplate ? PrevTemplate->getTemplateParameters() 9769 : nullptr, 9770 D.getDeclSpec().isFriendSpecified() 9771 ? (D.isFunctionDefinition() 9772 ? TPC_FriendFunctionTemplateDefinition 9773 : TPC_FriendFunctionTemplate) 9774 : (D.getCXXScopeSpec().isSet() && 9775 DC && DC->isRecord() && 9776 DC->isDependentContext()) 9777 ? TPC_ClassTemplateMember 9778 : TPC_FunctionTemplate); 9779 } 9780 9781 if (NewFD->isInvalidDecl()) { 9782 // Ignore all the rest of this. 9783 } else if (!D.isRedeclaration()) { 9784 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9785 AddToScope }; 9786 // Fake up an access specifier if it's supposed to be a class member. 9787 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9788 NewFD->setAccess(AS_public); 9789 9790 // Qualified decls generally require a previous declaration. 9791 if (D.getCXXScopeSpec().isSet()) { 9792 // ...with the major exception of templated-scope or 9793 // dependent-scope friend declarations. 9794 9795 // TODO: we currently also suppress this check in dependent 9796 // contexts because (1) the parameter depth will be off when 9797 // matching friend templates and (2) we might actually be 9798 // selecting a friend based on a dependent factor. But there 9799 // are situations where these conditions don't apply and we 9800 // can actually do this check immediately. 9801 // 9802 // Unless the scope is dependent, it's always an error if qualified 9803 // redeclaration lookup found nothing at all. Diagnose that now; 9804 // nothing will diagnose that error later. 9805 if (isFriend && 9806 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9807 (!Previous.empty() && CurContext->isDependentContext()))) { 9808 // ignore these 9809 } else if (NewFD->isCPUDispatchMultiVersion() || 9810 NewFD->isCPUSpecificMultiVersion()) { 9811 // ignore this, we allow the redeclaration behavior here to create new 9812 // versions of the function. 9813 } else { 9814 // The user tried to provide an out-of-line definition for a 9815 // function that is a member of a class or namespace, but there 9816 // was no such member function declared (C++ [class.mfct]p2, 9817 // C++ [namespace.memdef]p2). For example: 9818 // 9819 // class X { 9820 // void f() const; 9821 // }; 9822 // 9823 // void X::f() { } // ill-formed 9824 // 9825 // Complain about this problem, and attempt to suggest close 9826 // matches (e.g., those that differ only in cv-qualifiers and 9827 // whether the parameter types are references). 9828 9829 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9830 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9831 AddToScope = ExtraArgs.AddToScope; 9832 return Result; 9833 } 9834 } 9835 9836 // Unqualified local friend declarations are required to resolve 9837 // to something. 9838 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9839 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9840 *this, Previous, NewFD, ExtraArgs, true, S)) { 9841 AddToScope = ExtraArgs.AddToScope; 9842 return Result; 9843 } 9844 } 9845 } else if (!D.isFunctionDefinition() && 9846 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9847 !isFriend && !isFunctionTemplateSpecialization && 9848 !isMemberSpecialization) { 9849 // An out-of-line member function declaration must also be a 9850 // definition (C++ [class.mfct]p2). 9851 // Note that this is not the case for explicit specializations of 9852 // function templates or member functions of class templates, per 9853 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9854 // extension for compatibility with old SWIG code which likes to 9855 // generate them. 9856 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9857 << D.getCXXScopeSpec().getRange(); 9858 } 9859 } 9860 9861 // If this is the first declaration of a library builtin function, add 9862 // attributes as appropriate. 9863 if (!D.isRedeclaration() && 9864 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9865 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9866 if (unsigned BuiltinID = II->getBuiltinID()) { 9867 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9868 // Validate the type matches unless this builtin is specified as 9869 // matching regardless of its declared type. 9870 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9871 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9872 } else { 9873 ASTContext::GetBuiltinTypeError Error; 9874 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9875 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9876 9877 if (!Error && !BuiltinType.isNull() && 9878 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9879 NewFD->getType(), BuiltinType)) 9880 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9881 } 9882 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9883 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9884 // FIXME: We should consider this a builtin only in the std namespace. 9885 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9886 } 9887 } 9888 } 9889 } 9890 9891 ProcessPragmaWeak(S, NewFD); 9892 checkAttributesAfterMerging(*this, *NewFD); 9893 9894 AddKnownFunctionAttributes(NewFD); 9895 9896 if (NewFD->hasAttr<OverloadableAttr>() && 9897 !NewFD->getType()->getAs<FunctionProtoType>()) { 9898 Diag(NewFD->getLocation(), 9899 diag::err_attribute_overloadable_no_prototype) 9900 << NewFD; 9901 9902 // Turn this into a variadic function with no parameters. 9903 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9904 FunctionProtoType::ExtProtoInfo EPI( 9905 Context.getDefaultCallingConvention(true, false)); 9906 EPI.Variadic = true; 9907 EPI.ExtInfo = FT->getExtInfo(); 9908 9909 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9910 NewFD->setType(R); 9911 } 9912 9913 // If there's a #pragma GCC visibility in scope, and this isn't a class 9914 // member, set the visibility of this function. 9915 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9916 AddPushedVisibilityAttribute(NewFD); 9917 9918 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9919 // marking the function. 9920 AddCFAuditedAttribute(NewFD); 9921 9922 // If this is a function definition, check if we have to apply optnone due to 9923 // a pragma. 9924 if(D.isFunctionDefinition()) 9925 AddRangeBasedOptnone(NewFD); 9926 9927 // If this is the first declaration of an extern C variable, update 9928 // the map of such variables. 9929 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9930 isIncompleteDeclExternC(*this, NewFD)) 9931 RegisterLocallyScopedExternCDecl(NewFD, S); 9932 9933 // Set this FunctionDecl's range up to the right paren. 9934 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9935 9936 if (D.isRedeclaration() && !Previous.empty()) { 9937 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9938 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9939 isMemberSpecialization || 9940 isFunctionTemplateSpecialization, 9941 D.isFunctionDefinition()); 9942 } 9943 9944 if (getLangOpts().CUDA) { 9945 IdentifierInfo *II = NewFD->getIdentifier(); 9946 if (II && II->isStr(getCudaConfigureFuncName()) && 9947 !NewFD->isInvalidDecl() && 9948 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9949 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 9950 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9951 << getCudaConfigureFuncName(); 9952 Context.setcudaConfigureCallDecl(NewFD); 9953 } 9954 9955 // Variadic functions, other than a *declaration* of printf, are not allowed 9956 // in device-side CUDA code, unless someone passed 9957 // -fcuda-allow-variadic-functions. 9958 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9959 (NewFD->hasAttr<CUDADeviceAttr>() || 9960 NewFD->hasAttr<CUDAGlobalAttr>()) && 9961 !(II && II->isStr("printf") && NewFD->isExternC() && 9962 !D.isFunctionDefinition())) { 9963 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9964 } 9965 } 9966 9967 MarkUnusedFileScopedDecl(NewFD); 9968 9969 9970 9971 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9972 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9973 if (SC == SC_Static) { 9974 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9975 D.setInvalidType(); 9976 } 9977 9978 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9979 if (!NewFD->getReturnType()->isVoidType()) { 9980 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9981 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9982 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9983 : FixItHint()); 9984 D.setInvalidType(); 9985 } 9986 9987 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9988 for (auto Param : NewFD->parameters()) 9989 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9990 9991 if (getLangOpts().OpenCLCPlusPlus) { 9992 if (DC->isRecord()) { 9993 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9994 D.setInvalidType(); 9995 } 9996 if (FunctionTemplate) { 9997 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9998 D.setInvalidType(); 9999 } 10000 } 10001 } 10002 10003 if (getLangOpts().CPlusPlus) { 10004 if (FunctionTemplate) { 10005 if (NewFD->isInvalidDecl()) 10006 FunctionTemplate->setInvalidDecl(); 10007 return FunctionTemplate; 10008 } 10009 10010 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10011 CompleteMemberSpecialization(NewFD, Previous); 10012 } 10013 10014 for (const ParmVarDecl *Param : NewFD->parameters()) { 10015 QualType PT = Param->getType(); 10016 10017 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10018 // types. 10019 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10020 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10021 QualType ElemTy = PipeTy->getElementType(); 10022 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10023 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10024 D.setInvalidType(); 10025 } 10026 } 10027 } 10028 } 10029 10030 // Here we have an function template explicit specialization at class scope. 10031 // The actual specialization will be postponed to template instatiation 10032 // time via the ClassScopeFunctionSpecializationDecl node. 10033 if (isDependentClassScopeExplicitSpecialization) { 10034 ClassScopeFunctionSpecializationDecl *NewSpec = 10035 ClassScopeFunctionSpecializationDecl::Create( 10036 Context, CurContext, NewFD->getLocation(), 10037 cast<CXXMethodDecl>(NewFD), 10038 HasExplicitTemplateArgs, TemplateArgs); 10039 CurContext->addDecl(NewSpec); 10040 AddToScope = false; 10041 } 10042 10043 // Diagnose availability attributes. Availability cannot be used on functions 10044 // that are run during load/unload. 10045 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10046 if (NewFD->hasAttr<ConstructorAttr>()) { 10047 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10048 << 1; 10049 NewFD->dropAttr<AvailabilityAttr>(); 10050 } 10051 if (NewFD->hasAttr<DestructorAttr>()) { 10052 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10053 << 2; 10054 NewFD->dropAttr<AvailabilityAttr>(); 10055 } 10056 } 10057 10058 // Diagnose no_builtin attribute on function declaration that are not a 10059 // definition. 10060 // FIXME: We should really be doing this in 10061 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10062 // the FunctionDecl and at this point of the code 10063 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10064 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10065 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10066 switch (D.getFunctionDefinitionKind()) { 10067 case FunctionDefinitionKind::Defaulted: 10068 case FunctionDefinitionKind::Deleted: 10069 Diag(NBA->getLocation(), 10070 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10071 << NBA->getSpelling(); 10072 break; 10073 case FunctionDefinitionKind::Declaration: 10074 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10075 << NBA->getSpelling(); 10076 break; 10077 case FunctionDefinitionKind::Definition: 10078 break; 10079 } 10080 10081 return NewFD; 10082 } 10083 10084 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10085 /// when __declspec(code_seg) "is applied to a class, all member functions of 10086 /// the class and nested classes -- this includes compiler-generated special 10087 /// member functions -- are put in the specified segment." 10088 /// The actual behavior is a little more complicated. The Microsoft compiler 10089 /// won't check outer classes if there is an active value from #pragma code_seg. 10090 /// The CodeSeg is always applied from the direct parent but only from outer 10091 /// classes when the #pragma code_seg stack is empty. See: 10092 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10093 /// available since MS has removed the page. 10094 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10095 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10096 if (!Method) 10097 return nullptr; 10098 const CXXRecordDecl *Parent = Method->getParent(); 10099 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10100 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10101 NewAttr->setImplicit(true); 10102 return NewAttr; 10103 } 10104 10105 // The Microsoft compiler won't check outer classes for the CodeSeg 10106 // when the #pragma code_seg stack is active. 10107 if (S.CodeSegStack.CurrentValue) 10108 return nullptr; 10109 10110 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10111 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10112 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10113 NewAttr->setImplicit(true); 10114 return NewAttr; 10115 } 10116 } 10117 return nullptr; 10118 } 10119 10120 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10121 /// containing class. Otherwise it will return implicit SectionAttr if the 10122 /// function is a definition and there is an active value on CodeSegStack 10123 /// (from the current #pragma code-seg value). 10124 /// 10125 /// \param FD Function being declared. 10126 /// \param IsDefinition Whether it is a definition or just a declarartion. 10127 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10128 /// nullptr if no attribute should be added. 10129 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10130 bool IsDefinition) { 10131 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10132 return A; 10133 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10134 CodeSegStack.CurrentValue) 10135 return SectionAttr::CreateImplicit( 10136 getASTContext(), CodeSegStack.CurrentValue->getString(), 10137 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10138 SectionAttr::Declspec_allocate); 10139 return nullptr; 10140 } 10141 10142 /// Determines if we can perform a correct type check for \p D as a 10143 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10144 /// best-effort check. 10145 /// 10146 /// \param NewD The new declaration. 10147 /// \param OldD The old declaration. 10148 /// \param NewT The portion of the type of the new declaration to check. 10149 /// \param OldT The portion of the type of the old declaration to check. 10150 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10151 QualType NewT, QualType OldT) { 10152 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10153 return true; 10154 10155 // For dependently-typed local extern declarations and friends, we can't 10156 // perform a correct type check in general until instantiation: 10157 // 10158 // int f(); 10159 // template<typename T> void g() { T f(); } 10160 // 10161 // (valid if g() is only instantiated with T = int). 10162 if (NewT->isDependentType() && 10163 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10164 return false; 10165 10166 // Similarly, if the previous declaration was a dependent local extern 10167 // declaration, we don't really know its type yet. 10168 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10169 return false; 10170 10171 return true; 10172 } 10173 10174 /// Checks if the new declaration declared in dependent context must be 10175 /// put in the same redeclaration chain as the specified declaration. 10176 /// 10177 /// \param D Declaration that is checked. 10178 /// \param PrevDecl Previous declaration found with proper lookup method for the 10179 /// same declaration name. 10180 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10181 /// belongs to. 10182 /// 10183 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10184 if (!D->getLexicalDeclContext()->isDependentContext()) 10185 return true; 10186 10187 // Don't chain dependent friend function definitions until instantiation, to 10188 // permit cases like 10189 // 10190 // void func(); 10191 // template<typename T> class C1 { friend void func() {} }; 10192 // template<typename T> class C2 { friend void func() {} }; 10193 // 10194 // ... which is valid if only one of C1 and C2 is ever instantiated. 10195 // 10196 // FIXME: This need only apply to function definitions. For now, we proxy 10197 // this by checking for a file-scope function. We do not want this to apply 10198 // to friend declarations nominating member functions, because that gets in 10199 // the way of access checks. 10200 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10201 return false; 10202 10203 auto *VD = dyn_cast<ValueDecl>(D); 10204 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10205 return !VD || !PrevVD || 10206 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10207 PrevVD->getType()); 10208 } 10209 10210 /// Check the target attribute of the function for MultiVersion 10211 /// validity. 10212 /// 10213 /// Returns true if there was an error, false otherwise. 10214 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10215 const auto *TA = FD->getAttr<TargetAttr>(); 10216 assert(TA && "MultiVersion Candidate requires a target attribute"); 10217 ParsedTargetAttr ParseInfo = TA->parse(); 10218 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10219 enum ErrType { Feature = 0, Architecture = 1 }; 10220 10221 if (!ParseInfo.Architecture.empty() && 10222 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10223 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10224 << Architecture << ParseInfo.Architecture; 10225 return true; 10226 } 10227 10228 for (const auto &Feat : ParseInfo.Features) { 10229 auto BareFeat = StringRef{Feat}.substr(1); 10230 if (Feat[0] == '-') { 10231 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10232 << Feature << ("no-" + BareFeat).str(); 10233 return true; 10234 } 10235 10236 if (!TargetInfo.validateCpuSupports(BareFeat) || 10237 !TargetInfo.isValidFeatureName(BareFeat)) { 10238 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10239 << Feature << BareFeat; 10240 return true; 10241 } 10242 } 10243 return false; 10244 } 10245 10246 // Provide a white-list of attributes that are allowed to be combined with 10247 // multiversion functions. 10248 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10249 MultiVersionKind MVType) { 10250 // Note: this list/diagnosis must match the list in 10251 // checkMultiversionAttributesAllSame. 10252 switch (Kind) { 10253 default: 10254 return false; 10255 case attr::Used: 10256 return MVType == MultiVersionKind::Target; 10257 case attr::NonNull: 10258 case attr::NoThrow: 10259 return true; 10260 } 10261 } 10262 10263 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10264 const FunctionDecl *FD, 10265 const FunctionDecl *CausedFD, 10266 MultiVersionKind MVType) { 10267 bool IsCPUSpecificCPUDispatchMVType = 10268 MVType == MultiVersionKind::CPUDispatch || 10269 MVType == MultiVersionKind::CPUSpecific; 10270 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10271 Sema &S, const Attr *A) { 10272 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10273 << IsCPUSpecificCPUDispatchMVType << A; 10274 if (CausedFD) 10275 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10276 return true; 10277 }; 10278 10279 for (const Attr *A : FD->attrs()) { 10280 switch (A->getKind()) { 10281 case attr::CPUDispatch: 10282 case attr::CPUSpecific: 10283 if (MVType != MultiVersionKind::CPUDispatch && 10284 MVType != MultiVersionKind::CPUSpecific) 10285 return Diagnose(S, A); 10286 break; 10287 case attr::Target: 10288 if (MVType != MultiVersionKind::Target) 10289 return Diagnose(S, A); 10290 break; 10291 default: 10292 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10293 return Diagnose(S, A); 10294 break; 10295 } 10296 } 10297 return false; 10298 } 10299 10300 bool Sema::areMultiversionVariantFunctionsCompatible( 10301 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10302 const PartialDiagnostic &NoProtoDiagID, 10303 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10304 const PartialDiagnosticAt &NoSupportDiagIDAt, 10305 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10306 bool ConstexprSupported, bool CLinkageMayDiffer) { 10307 enum DoesntSupport { 10308 FuncTemplates = 0, 10309 VirtFuncs = 1, 10310 DeducedReturn = 2, 10311 Constructors = 3, 10312 Destructors = 4, 10313 DeletedFuncs = 5, 10314 DefaultedFuncs = 6, 10315 ConstexprFuncs = 7, 10316 ConstevalFuncs = 8, 10317 }; 10318 enum Different { 10319 CallingConv = 0, 10320 ReturnType = 1, 10321 ConstexprSpec = 2, 10322 InlineSpec = 3, 10323 StorageClass = 4, 10324 Linkage = 5, 10325 }; 10326 10327 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10328 !OldFD->getType()->getAs<FunctionProtoType>()) { 10329 Diag(OldFD->getLocation(), NoProtoDiagID); 10330 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10331 return true; 10332 } 10333 10334 if (NoProtoDiagID.getDiagID() != 0 && 10335 !NewFD->getType()->getAs<FunctionProtoType>()) 10336 return Diag(NewFD->getLocation(), NoProtoDiagID); 10337 10338 if (!TemplatesSupported && 10339 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10340 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10341 << FuncTemplates; 10342 10343 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10344 if (NewCXXFD->isVirtual()) 10345 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10346 << VirtFuncs; 10347 10348 if (isa<CXXConstructorDecl>(NewCXXFD)) 10349 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10350 << Constructors; 10351 10352 if (isa<CXXDestructorDecl>(NewCXXFD)) 10353 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10354 << Destructors; 10355 } 10356 10357 if (NewFD->isDeleted()) 10358 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10359 << DeletedFuncs; 10360 10361 if (NewFD->isDefaulted()) 10362 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10363 << DefaultedFuncs; 10364 10365 if (!ConstexprSupported && NewFD->isConstexpr()) 10366 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10367 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10368 10369 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10370 const auto *NewType = cast<FunctionType>(NewQType); 10371 QualType NewReturnType = NewType->getReturnType(); 10372 10373 if (NewReturnType->isUndeducedType()) 10374 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10375 << DeducedReturn; 10376 10377 // Ensure the return type is identical. 10378 if (OldFD) { 10379 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10380 const auto *OldType = cast<FunctionType>(OldQType); 10381 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10382 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10383 10384 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10385 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10386 10387 QualType OldReturnType = OldType->getReturnType(); 10388 10389 if (OldReturnType != NewReturnType) 10390 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10391 10392 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10393 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10394 10395 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10396 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10397 10398 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10399 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10400 10401 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10402 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10403 10404 if (CheckEquivalentExceptionSpec( 10405 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10406 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10407 return true; 10408 } 10409 return false; 10410 } 10411 10412 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10413 const FunctionDecl *NewFD, 10414 bool CausesMV, 10415 MultiVersionKind MVType) { 10416 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10417 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10418 if (OldFD) 10419 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10420 return true; 10421 } 10422 10423 bool IsCPUSpecificCPUDispatchMVType = 10424 MVType == MultiVersionKind::CPUDispatch || 10425 MVType == MultiVersionKind::CPUSpecific; 10426 10427 if (CausesMV && OldFD && 10428 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10429 return true; 10430 10431 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10432 return true; 10433 10434 // Only allow transition to MultiVersion if it hasn't been used. 10435 if (OldFD && CausesMV && OldFD->isUsed(false)) 10436 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10437 10438 return S.areMultiversionVariantFunctionsCompatible( 10439 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10440 PartialDiagnosticAt(NewFD->getLocation(), 10441 S.PDiag(diag::note_multiversioning_caused_here)), 10442 PartialDiagnosticAt(NewFD->getLocation(), 10443 S.PDiag(diag::err_multiversion_doesnt_support) 10444 << IsCPUSpecificCPUDispatchMVType), 10445 PartialDiagnosticAt(NewFD->getLocation(), 10446 S.PDiag(diag::err_multiversion_diff)), 10447 /*TemplatesSupported=*/false, 10448 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10449 /*CLinkageMayDiffer=*/false); 10450 } 10451 10452 /// Check the validity of a multiversion function declaration that is the 10453 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10454 /// 10455 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10456 /// 10457 /// Returns true if there was an error, false otherwise. 10458 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10459 MultiVersionKind MVType, 10460 const TargetAttr *TA) { 10461 assert(MVType != MultiVersionKind::None && 10462 "Function lacks multiversion attribute"); 10463 10464 // Target only causes MV if it is default, otherwise this is a normal 10465 // function. 10466 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10467 return false; 10468 10469 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10470 FD->setInvalidDecl(); 10471 return true; 10472 } 10473 10474 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10475 FD->setInvalidDecl(); 10476 return true; 10477 } 10478 10479 FD->setIsMultiVersion(); 10480 return false; 10481 } 10482 10483 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10484 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10485 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10486 return true; 10487 } 10488 10489 return false; 10490 } 10491 10492 static bool CheckTargetCausesMultiVersioning( 10493 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10494 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10495 LookupResult &Previous) { 10496 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10497 ParsedTargetAttr NewParsed = NewTA->parse(); 10498 // Sort order doesn't matter, it just needs to be consistent. 10499 llvm::sort(NewParsed.Features); 10500 10501 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10502 // to change, this is a simple redeclaration. 10503 if (!NewTA->isDefaultVersion() && 10504 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10505 return false; 10506 10507 // Otherwise, this decl causes MultiVersioning. 10508 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10509 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10510 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10511 NewFD->setInvalidDecl(); 10512 return true; 10513 } 10514 10515 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10516 MultiVersionKind::Target)) { 10517 NewFD->setInvalidDecl(); 10518 return true; 10519 } 10520 10521 if (CheckMultiVersionValue(S, NewFD)) { 10522 NewFD->setInvalidDecl(); 10523 return true; 10524 } 10525 10526 // If this is 'default', permit the forward declaration. 10527 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10528 Redeclaration = true; 10529 OldDecl = OldFD; 10530 OldFD->setIsMultiVersion(); 10531 NewFD->setIsMultiVersion(); 10532 return false; 10533 } 10534 10535 if (CheckMultiVersionValue(S, OldFD)) { 10536 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10537 NewFD->setInvalidDecl(); 10538 return true; 10539 } 10540 10541 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10542 10543 if (OldParsed == NewParsed) { 10544 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10545 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10546 NewFD->setInvalidDecl(); 10547 return true; 10548 } 10549 10550 for (const auto *FD : OldFD->redecls()) { 10551 const auto *CurTA = FD->getAttr<TargetAttr>(); 10552 // We allow forward declarations before ANY multiversioning attributes, but 10553 // nothing after the fact. 10554 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10555 (!CurTA || CurTA->isInherited())) { 10556 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10557 << 0; 10558 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10559 NewFD->setInvalidDecl(); 10560 return true; 10561 } 10562 } 10563 10564 OldFD->setIsMultiVersion(); 10565 NewFD->setIsMultiVersion(); 10566 Redeclaration = false; 10567 MergeTypeWithPrevious = false; 10568 OldDecl = nullptr; 10569 Previous.clear(); 10570 return false; 10571 } 10572 10573 /// Check the validity of a new function declaration being added to an existing 10574 /// multiversioned declaration collection. 10575 static bool CheckMultiVersionAdditionalDecl( 10576 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10577 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10578 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10579 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10580 LookupResult &Previous) { 10581 10582 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10583 // Disallow mixing of multiversioning types. 10584 if ((OldMVType == MultiVersionKind::Target && 10585 NewMVType != MultiVersionKind::Target) || 10586 (NewMVType == MultiVersionKind::Target && 10587 OldMVType != MultiVersionKind::Target)) { 10588 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10589 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10590 NewFD->setInvalidDecl(); 10591 return true; 10592 } 10593 10594 ParsedTargetAttr NewParsed; 10595 if (NewTA) { 10596 NewParsed = NewTA->parse(); 10597 llvm::sort(NewParsed.Features); 10598 } 10599 10600 bool UseMemberUsingDeclRules = 10601 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10602 10603 // Next, check ALL non-overloads to see if this is a redeclaration of a 10604 // previous member of the MultiVersion set. 10605 for (NamedDecl *ND : Previous) { 10606 FunctionDecl *CurFD = ND->getAsFunction(); 10607 if (!CurFD) 10608 continue; 10609 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10610 continue; 10611 10612 if (NewMVType == MultiVersionKind::Target) { 10613 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10614 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10615 NewFD->setIsMultiVersion(); 10616 Redeclaration = true; 10617 OldDecl = ND; 10618 return false; 10619 } 10620 10621 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10622 if (CurParsed == NewParsed) { 10623 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10624 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10625 NewFD->setInvalidDecl(); 10626 return true; 10627 } 10628 } else { 10629 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10630 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10631 // Handle CPUDispatch/CPUSpecific versions. 10632 // Only 1 CPUDispatch function is allowed, this will make it go through 10633 // the redeclaration errors. 10634 if (NewMVType == MultiVersionKind::CPUDispatch && 10635 CurFD->hasAttr<CPUDispatchAttr>()) { 10636 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10637 std::equal( 10638 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10639 NewCPUDisp->cpus_begin(), 10640 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10641 return Cur->getName() == New->getName(); 10642 })) { 10643 NewFD->setIsMultiVersion(); 10644 Redeclaration = true; 10645 OldDecl = ND; 10646 return false; 10647 } 10648 10649 // If the declarations don't match, this is an error condition. 10650 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10651 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10652 NewFD->setInvalidDecl(); 10653 return true; 10654 } 10655 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10656 10657 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10658 std::equal( 10659 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10660 NewCPUSpec->cpus_begin(), 10661 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10662 return Cur->getName() == New->getName(); 10663 })) { 10664 NewFD->setIsMultiVersion(); 10665 Redeclaration = true; 10666 OldDecl = ND; 10667 return false; 10668 } 10669 10670 // Only 1 version of CPUSpecific is allowed for each CPU. 10671 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10672 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10673 if (CurII == NewII) { 10674 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10675 << NewII; 10676 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10677 NewFD->setInvalidDecl(); 10678 return true; 10679 } 10680 } 10681 } 10682 } 10683 // If the two decls aren't the same MVType, there is no possible error 10684 // condition. 10685 } 10686 } 10687 10688 // Else, this is simply a non-redecl case. Checking the 'value' is only 10689 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10690 // handled in the attribute adding step. 10691 if (NewMVType == MultiVersionKind::Target && 10692 CheckMultiVersionValue(S, NewFD)) { 10693 NewFD->setInvalidDecl(); 10694 return true; 10695 } 10696 10697 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10698 !OldFD->isMultiVersion(), NewMVType)) { 10699 NewFD->setInvalidDecl(); 10700 return true; 10701 } 10702 10703 // Permit forward declarations in the case where these two are compatible. 10704 if (!OldFD->isMultiVersion()) { 10705 OldFD->setIsMultiVersion(); 10706 NewFD->setIsMultiVersion(); 10707 Redeclaration = true; 10708 OldDecl = OldFD; 10709 return false; 10710 } 10711 10712 NewFD->setIsMultiVersion(); 10713 Redeclaration = false; 10714 MergeTypeWithPrevious = false; 10715 OldDecl = nullptr; 10716 Previous.clear(); 10717 return false; 10718 } 10719 10720 10721 /// Check the validity of a mulitversion function declaration. 10722 /// Also sets the multiversion'ness' of the function itself. 10723 /// 10724 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10725 /// 10726 /// Returns true if there was an error, false otherwise. 10727 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10728 bool &Redeclaration, NamedDecl *&OldDecl, 10729 bool &MergeTypeWithPrevious, 10730 LookupResult &Previous) { 10731 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10732 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10733 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10734 10735 // Mixing Multiversioning types is prohibited. 10736 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10737 (NewCPUDisp && NewCPUSpec)) { 10738 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10739 NewFD->setInvalidDecl(); 10740 return true; 10741 } 10742 10743 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10744 10745 // Main isn't allowed to become a multiversion function, however it IS 10746 // permitted to have 'main' be marked with the 'target' optimization hint. 10747 if (NewFD->isMain()) { 10748 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10749 MVType == MultiVersionKind::CPUDispatch || 10750 MVType == MultiVersionKind::CPUSpecific) { 10751 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10752 NewFD->setInvalidDecl(); 10753 return true; 10754 } 10755 return false; 10756 } 10757 10758 if (!OldDecl || !OldDecl->getAsFunction() || 10759 OldDecl->getDeclContext()->getRedeclContext() != 10760 NewFD->getDeclContext()->getRedeclContext()) { 10761 // If there's no previous declaration, AND this isn't attempting to cause 10762 // multiversioning, this isn't an error condition. 10763 if (MVType == MultiVersionKind::None) 10764 return false; 10765 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10766 } 10767 10768 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10769 10770 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10771 return false; 10772 10773 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10774 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10775 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10776 NewFD->setInvalidDecl(); 10777 return true; 10778 } 10779 10780 // Handle the target potentially causes multiversioning case. 10781 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10782 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10783 Redeclaration, OldDecl, 10784 MergeTypeWithPrevious, Previous); 10785 10786 // At this point, we have a multiversion function decl (in OldFD) AND an 10787 // appropriate attribute in the current function decl. Resolve that these are 10788 // still compatible with previous declarations. 10789 return CheckMultiVersionAdditionalDecl( 10790 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10791 OldDecl, MergeTypeWithPrevious, Previous); 10792 } 10793 10794 /// Perform semantic checking of a new function declaration. 10795 /// 10796 /// Performs semantic analysis of the new function declaration 10797 /// NewFD. This routine performs all semantic checking that does not 10798 /// require the actual declarator involved in the declaration, and is 10799 /// used both for the declaration of functions as they are parsed 10800 /// (called via ActOnDeclarator) and for the declaration of functions 10801 /// that have been instantiated via C++ template instantiation (called 10802 /// via InstantiateDecl). 10803 /// 10804 /// \param IsMemberSpecialization whether this new function declaration is 10805 /// a member specialization (that replaces any definition provided by the 10806 /// previous declaration). 10807 /// 10808 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10809 /// 10810 /// \returns true if the function declaration is a redeclaration. 10811 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10812 LookupResult &Previous, 10813 bool IsMemberSpecialization) { 10814 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10815 "Variably modified return types are not handled here"); 10816 10817 // Determine whether the type of this function should be merged with 10818 // a previous visible declaration. This never happens for functions in C++, 10819 // and always happens in C if the previous declaration was visible. 10820 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10821 !Previous.isShadowed(); 10822 10823 bool Redeclaration = false; 10824 NamedDecl *OldDecl = nullptr; 10825 bool MayNeedOverloadableChecks = false; 10826 10827 // Merge or overload the declaration with an existing declaration of 10828 // the same name, if appropriate. 10829 if (!Previous.empty()) { 10830 // Determine whether NewFD is an overload of PrevDecl or 10831 // a declaration that requires merging. If it's an overload, 10832 // there's no more work to do here; we'll just add the new 10833 // function to the scope. 10834 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10835 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10836 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10837 Redeclaration = true; 10838 OldDecl = Candidate; 10839 } 10840 } else { 10841 MayNeedOverloadableChecks = true; 10842 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10843 /*NewIsUsingDecl*/ false)) { 10844 case Ovl_Match: 10845 Redeclaration = true; 10846 break; 10847 10848 case Ovl_NonFunction: 10849 Redeclaration = true; 10850 break; 10851 10852 case Ovl_Overload: 10853 Redeclaration = false; 10854 break; 10855 } 10856 } 10857 } 10858 10859 // Check for a previous extern "C" declaration with this name. 10860 if (!Redeclaration && 10861 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10862 if (!Previous.empty()) { 10863 // This is an extern "C" declaration with the same name as a previous 10864 // declaration, and thus redeclares that entity... 10865 Redeclaration = true; 10866 OldDecl = Previous.getFoundDecl(); 10867 MergeTypeWithPrevious = false; 10868 10869 // ... except in the presence of __attribute__((overloadable)). 10870 if (OldDecl->hasAttr<OverloadableAttr>() || 10871 NewFD->hasAttr<OverloadableAttr>()) { 10872 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10873 MayNeedOverloadableChecks = true; 10874 Redeclaration = false; 10875 OldDecl = nullptr; 10876 } 10877 } 10878 } 10879 } 10880 10881 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10882 MergeTypeWithPrevious, Previous)) 10883 return Redeclaration; 10884 10885 // PPC MMA non-pointer types are not allowed as function return types. 10886 if (Context.getTargetInfo().getTriple().isPPC64() && 10887 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10888 NewFD->setInvalidDecl(); 10889 } 10890 10891 // C++11 [dcl.constexpr]p8: 10892 // A constexpr specifier for a non-static member function that is not 10893 // a constructor declares that member function to be const. 10894 // 10895 // This needs to be delayed until we know whether this is an out-of-line 10896 // definition of a static member function. 10897 // 10898 // This rule is not present in C++1y, so we produce a backwards 10899 // compatibility warning whenever it happens in C++11. 10900 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10901 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10902 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10903 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10904 CXXMethodDecl *OldMD = nullptr; 10905 if (OldDecl) 10906 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10907 if (!OldMD || !OldMD->isStatic()) { 10908 const FunctionProtoType *FPT = 10909 MD->getType()->castAs<FunctionProtoType>(); 10910 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10911 EPI.TypeQuals.addConst(); 10912 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10913 FPT->getParamTypes(), EPI)); 10914 10915 // Warn that we did this, if we're not performing template instantiation. 10916 // In that case, we'll have warned already when the template was defined. 10917 if (!inTemplateInstantiation()) { 10918 SourceLocation AddConstLoc; 10919 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10920 .IgnoreParens().getAs<FunctionTypeLoc>()) 10921 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10922 10923 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10924 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10925 } 10926 } 10927 } 10928 10929 if (Redeclaration) { 10930 // NewFD and OldDecl represent declarations that need to be 10931 // merged. 10932 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10933 NewFD->setInvalidDecl(); 10934 return Redeclaration; 10935 } 10936 10937 Previous.clear(); 10938 Previous.addDecl(OldDecl); 10939 10940 if (FunctionTemplateDecl *OldTemplateDecl = 10941 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10942 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10943 FunctionTemplateDecl *NewTemplateDecl 10944 = NewFD->getDescribedFunctionTemplate(); 10945 assert(NewTemplateDecl && "Template/non-template mismatch"); 10946 10947 // The call to MergeFunctionDecl above may have created some state in 10948 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10949 // can add it as a redeclaration. 10950 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10951 10952 NewFD->setPreviousDeclaration(OldFD); 10953 if (NewFD->isCXXClassMember()) { 10954 NewFD->setAccess(OldTemplateDecl->getAccess()); 10955 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10956 } 10957 10958 // If this is an explicit specialization of a member that is a function 10959 // template, mark it as a member specialization. 10960 if (IsMemberSpecialization && 10961 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10962 NewTemplateDecl->setMemberSpecialization(); 10963 assert(OldTemplateDecl->isMemberSpecialization()); 10964 // Explicit specializations of a member template do not inherit deleted 10965 // status from the parent member template that they are specializing. 10966 if (OldFD->isDeleted()) { 10967 // FIXME: This assert will not hold in the presence of modules. 10968 assert(OldFD->getCanonicalDecl() == OldFD); 10969 // FIXME: We need an update record for this AST mutation. 10970 OldFD->setDeletedAsWritten(false); 10971 } 10972 } 10973 10974 } else { 10975 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10976 auto *OldFD = cast<FunctionDecl>(OldDecl); 10977 // This needs to happen first so that 'inline' propagates. 10978 NewFD->setPreviousDeclaration(OldFD); 10979 if (NewFD->isCXXClassMember()) 10980 NewFD->setAccess(OldFD->getAccess()); 10981 } 10982 } 10983 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10984 !NewFD->getAttr<OverloadableAttr>()) { 10985 assert((Previous.empty() || 10986 llvm::any_of(Previous, 10987 [](const NamedDecl *ND) { 10988 return ND->hasAttr<OverloadableAttr>(); 10989 })) && 10990 "Non-redecls shouldn't happen without overloadable present"); 10991 10992 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10993 const auto *FD = dyn_cast<FunctionDecl>(ND); 10994 return FD && !FD->hasAttr<OverloadableAttr>(); 10995 }); 10996 10997 if (OtherUnmarkedIter != Previous.end()) { 10998 Diag(NewFD->getLocation(), 10999 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11000 Diag((*OtherUnmarkedIter)->getLocation(), 11001 diag::note_attribute_overloadable_prev_overload) 11002 << false; 11003 11004 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11005 } 11006 } 11007 11008 if (LangOpts.OpenMP) 11009 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11010 11011 // Semantic checking for this function declaration (in isolation). 11012 11013 if (getLangOpts().CPlusPlus) { 11014 // C++-specific checks. 11015 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11016 CheckConstructor(Constructor); 11017 } else if (CXXDestructorDecl *Destructor = 11018 dyn_cast<CXXDestructorDecl>(NewFD)) { 11019 CXXRecordDecl *Record = Destructor->getParent(); 11020 QualType ClassType = Context.getTypeDeclType(Record); 11021 11022 // FIXME: Shouldn't we be able to perform this check even when the class 11023 // type is dependent? Both gcc and edg can handle that. 11024 if (!ClassType->isDependentType()) { 11025 DeclarationName Name 11026 = Context.DeclarationNames.getCXXDestructorName( 11027 Context.getCanonicalType(ClassType)); 11028 if (NewFD->getDeclName() != Name) { 11029 Diag(NewFD->getLocation(), diag::err_destructor_name); 11030 NewFD->setInvalidDecl(); 11031 return Redeclaration; 11032 } 11033 } 11034 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11035 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11036 CheckDeductionGuideTemplate(TD); 11037 11038 // A deduction guide is not on the list of entities that can be 11039 // explicitly specialized. 11040 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11041 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11042 << /*explicit specialization*/ 1; 11043 } 11044 11045 // Find any virtual functions that this function overrides. 11046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11047 if (!Method->isFunctionTemplateSpecialization() && 11048 !Method->getDescribedFunctionTemplate() && 11049 Method->isCanonicalDecl()) { 11050 AddOverriddenMethods(Method->getParent(), Method); 11051 } 11052 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11053 // C++2a [class.virtual]p6 11054 // A virtual method shall not have a requires-clause. 11055 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11056 diag::err_constrained_virtual_method); 11057 11058 if (Method->isStatic()) 11059 checkThisInStaticMemberFunctionType(Method); 11060 } 11061 11062 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11063 ActOnConversionDeclarator(Conversion); 11064 11065 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11066 if (NewFD->isOverloadedOperator() && 11067 CheckOverloadedOperatorDeclaration(NewFD)) { 11068 NewFD->setInvalidDecl(); 11069 return Redeclaration; 11070 } 11071 11072 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11073 if (NewFD->getLiteralIdentifier() && 11074 CheckLiteralOperatorDeclaration(NewFD)) { 11075 NewFD->setInvalidDecl(); 11076 return Redeclaration; 11077 } 11078 11079 // In C++, check default arguments now that we have merged decls. Unless 11080 // the lexical context is the class, because in this case this is done 11081 // during delayed parsing anyway. 11082 if (!CurContext->isRecord()) 11083 CheckCXXDefaultArguments(NewFD); 11084 11085 // If this function is declared as being extern "C", then check to see if 11086 // the function returns a UDT (class, struct, or union type) that is not C 11087 // compatible, and if it does, warn the user. 11088 // But, issue any diagnostic on the first declaration only. 11089 if (Previous.empty() && NewFD->isExternC()) { 11090 QualType R = NewFD->getReturnType(); 11091 if (R->isIncompleteType() && !R->isVoidType()) 11092 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11093 << NewFD << R; 11094 else if (!R.isPODType(Context) && !R->isVoidType() && 11095 !R->isObjCObjectPointerType()) 11096 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11097 } 11098 11099 // C++1z [dcl.fct]p6: 11100 // [...] whether the function has a non-throwing exception-specification 11101 // [is] part of the function type 11102 // 11103 // This results in an ABI break between C++14 and C++17 for functions whose 11104 // declared type includes an exception-specification in a parameter or 11105 // return type. (Exception specifications on the function itself are OK in 11106 // most cases, and exception specifications are not permitted in most other 11107 // contexts where they could make it into a mangling.) 11108 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11109 auto HasNoexcept = [&](QualType T) -> bool { 11110 // Strip off declarator chunks that could be between us and a function 11111 // type. We don't need to look far, exception specifications are very 11112 // restricted prior to C++17. 11113 if (auto *RT = T->getAs<ReferenceType>()) 11114 T = RT->getPointeeType(); 11115 else if (T->isAnyPointerType()) 11116 T = T->getPointeeType(); 11117 else if (auto *MPT = T->getAs<MemberPointerType>()) 11118 T = MPT->getPointeeType(); 11119 if (auto *FPT = T->getAs<FunctionProtoType>()) 11120 if (FPT->isNothrow()) 11121 return true; 11122 return false; 11123 }; 11124 11125 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11126 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11127 for (QualType T : FPT->param_types()) 11128 AnyNoexcept |= HasNoexcept(T); 11129 if (AnyNoexcept) 11130 Diag(NewFD->getLocation(), 11131 diag::warn_cxx17_compat_exception_spec_in_signature) 11132 << NewFD; 11133 } 11134 11135 if (!Redeclaration && LangOpts.CUDA) 11136 checkCUDATargetOverload(NewFD, Previous); 11137 } 11138 return Redeclaration; 11139 } 11140 11141 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11142 // C++11 [basic.start.main]p3: 11143 // A program that [...] declares main to be inline, static or 11144 // constexpr is ill-formed. 11145 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11146 // appear in a declaration of main. 11147 // static main is not an error under C99, but we should warn about it. 11148 // We accept _Noreturn main as an extension. 11149 if (FD->getStorageClass() == SC_Static) 11150 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11151 ? diag::err_static_main : diag::warn_static_main) 11152 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11153 if (FD->isInlineSpecified()) 11154 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11155 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11156 if (DS.isNoreturnSpecified()) { 11157 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11158 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11159 Diag(NoreturnLoc, diag::ext_noreturn_main); 11160 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11161 << FixItHint::CreateRemoval(NoreturnRange); 11162 } 11163 if (FD->isConstexpr()) { 11164 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11165 << FD->isConsteval() 11166 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11167 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11168 } 11169 11170 if (getLangOpts().OpenCL) { 11171 Diag(FD->getLocation(), diag::err_opencl_no_main) 11172 << FD->hasAttr<OpenCLKernelAttr>(); 11173 FD->setInvalidDecl(); 11174 return; 11175 } 11176 11177 QualType T = FD->getType(); 11178 assert(T->isFunctionType() && "function decl is not of function type"); 11179 const FunctionType* FT = T->castAs<FunctionType>(); 11180 11181 // Set default calling convention for main() 11182 if (FT->getCallConv() != CC_C) { 11183 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11184 FD->setType(QualType(FT, 0)); 11185 T = Context.getCanonicalType(FD->getType()); 11186 } 11187 11188 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11189 // In C with GNU extensions we allow main() to have non-integer return 11190 // type, but we should warn about the extension, and we disable the 11191 // implicit-return-zero rule. 11192 11193 // GCC in C mode accepts qualified 'int'. 11194 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11195 FD->setHasImplicitReturnZero(true); 11196 else { 11197 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11198 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11199 if (RTRange.isValid()) 11200 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11201 << FixItHint::CreateReplacement(RTRange, "int"); 11202 } 11203 } else { 11204 // In C and C++, main magically returns 0 if you fall off the end; 11205 // set the flag which tells us that. 11206 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11207 11208 // All the standards say that main() should return 'int'. 11209 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11210 FD->setHasImplicitReturnZero(true); 11211 else { 11212 // Otherwise, this is just a flat-out error. 11213 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11214 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11215 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11216 : FixItHint()); 11217 FD->setInvalidDecl(true); 11218 } 11219 } 11220 11221 // Treat protoless main() as nullary. 11222 if (isa<FunctionNoProtoType>(FT)) return; 11223 11224 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11225 unsigned nparams = FTP->getNumParams(); 11226 assert(FD->getNumParams() == nparams); 11227 11228 bool HasExtraParameters = (nparams > 3); 11229 11230 if (FTP->isVariadic()) { 11231 Diag(FD->getLocation(), diag::ext_variadic_main); 11232 // FIXME: if we had information about the location of the ellipsis, we 11233 // could add a FixIt hint to remove it as a parameter. 11234 } 11235 11236 // Darwin passes an undocumented fourth argument of type char**. If 11237 // other platforms start sprouting these, the logic below will start 11238 // getting shifty. 11239 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11240 HasExtraParameters = false; 11241 11242 if (HasExtraParameters) { 11243 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11244 FD->setInvalidDecl(true); 11245 nparams = 3; 11246 } 11247 11248 // FIXME: a lot of the following diagnostics would be improved 11249 // if we had some location information about types. 11250 11251 QualType CharPP = 11252 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11253 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11254 11255 for (unsigned i = 0; i < nparams; ++i) { 11256 QualType AT = FTP->getParamType(i); 11257 11258 bool mismatch = true; 11259 11260 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11261 mismatch = false; 11262 else if (Expected[i] == CharPP) { 11263 // As an extension, the following forms are okay: 11264 // char const ** 11265 // char const * const * 11266 // char * const * 11267 11268 QualifierCollector qs; 11269 const PointerType* PT; 11270 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11271 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11272 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11273 Context.CharTy)) { 11274 qs.removeConst(); 11275 mismatch = !qs.empty(); 11276 } 11277 } 11278 11279 if (mismatch) { 11280 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11281 // TODO: suggest replacing given type with expected type 11282 FD->setInvalidDecl(true); 11283 } 11284 } 11285 11286 if (nparams == 1 && !FD->isInvalidDecl()) { 11287 Diag(FD->getLocation(), diag::warn_main_one_arg); 11288 } 11289 11290 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11291 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11292 FD->setInvalidDecl(); 11293 } 11294 } 11295 11296 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11297 11298 // Default calling convention for main and wmain is __cdecl 11299 if (FD->getName() == "main" || FD->getName() == "wmain") 11300 return false; 11301 11302 // Default calling convention for MinGW is __cdecl 11303 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11304 if (T.isWindowsGNUEnvironment()) 11305 return false; 11306 11307 // Default calling convention for WinMain, wWinMain and DllMain 11308 // is __stdcall on 32 bit Windows 11309 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11310 return true; 11311 11312 return false; 11313 } 11314 11315 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11316 QualType T = FD->getType(); 11317 assert(T->isFunctionType() && "function decl is not of function type"); 11318 const FunctionType *FT = T->castAs<FunctionType>(); 11319 11320 // Set an implicit return of 'zero' if the function can return some integral, 11321 // enumeration, pointer or nullptr type. 11322 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11323 FT->getReturnType()->isAnyPointerType() || 11324 FT->getReturnType()->isNullPtrType()) 11325 // DllMain is exempt because a return value of zero means it failed. 11326 if (FD->getName() != "DllMain") 11327 FD->setHasImplicitReturnZero(true); 11328 11329 // Explicity specified calling conventions are applied to MSVC entry points 11330 if (!hasExplicitCallingConv(T)) { 11331 if (isDefaultStdCall(FD, *this)) { 11332 if (FT->getCallConv() != CC_X86StdCall) { 11333 FT = Context.adjustFunctionType( 11334 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11335 FD->setType(QualType(FT, 0)); 11336 } 11337 } else if (FT->getCallConv() != CC_C) { 11338 FT = Context.adjustFunctionType(FT, 11339 FT->getExtInfo().withCallingConv(CC_C)); 11340 FD->setType(QualType(FT, 0)); 11341 } 11342 } 11343 11344 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11345 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11346 FD->setInvalidDecl(); 11347 } 11348 } 11349 11350 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11351 // FIXME: Need strict checking. In C89, we need to check for 11352 // any assignment, increment, decrement, function-calls, or 11353 // commas outside of a sizeof. In C99, it's the same list, 11354 // except that the aforementioned are allowed in unevaluated 11355 // expressions. Everything else falls under the 11356 // "may accept other forms of constant expressions" exception. 11357 // 11358 // Regular C++ code will not end up here (exceptions: language extensions, 11359 // OpenCL C++ etc), so the constant expression rules there don't matter. 11360 if (Init->isValueDependent()) { 11361 assert(Init->containsErrors() && 11362 "Dependent code should only occur in error-recovery path."); 11363 return true; 11364 } 11365 const Expr *Culprit; 11366 if (Init->isConstantInitializer(Context, false, &Culprit)) 11367 return false; 11368 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11369 << Culprit->getSourceRange(); 11370 return true; 11371 } 11372 11373 namespace { 11374 // Visits an initialization expression to see if OrigDecl is evaluated in 11375 // its own initialization and throws a warning if it does. 11376 class SelfReferenceChecker 11377 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11378 Sema &S; 11379 Decl *OrigDecl; 11380 bool isRecordType; 11381 bool isPODType; 11382 bool isReferenceType; 11383 11384 bool isInitList; 11385 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11386 11387 public: 11388 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11389 11390 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11391 S(S), OrigDecl(OrigDecl) { 11392 isPODType = false; 11393 isRecordType = false; 11394 isReferenceType = false; 11395 isInitList = false; 11396 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11397 isPODType = VD->getType().isPODType(S.Context); 11398 isRecordType = VD->getType()->isRecordType(); 11399 isReferenceType = VD->getType()->isReferenceType(); 11400 } 11401 } 11402 11403 // For most expressions, just call the visitor. For initializer lists, 11404 // track the index of the field being initialized since fields are 11405 // initialized in order allowing use of previously initialized fields. 11406 void CheckExpr(Expr *E) { 11407 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11408 if (!InitList) { 11409 Visit(E); 11410 return; 11411 } 11412 11413 // Track and increment the index here. 11414 isInitList = true; 11415 InitFieldIndex.push_back(0); 11416 for (auto Child : InitList->children()) { 11417 CheckExpr(cast<Expr>(Child)); 11418 ++InitFieldIndex.back(); 11419 } 11420 InitFieldIndex.pop_back(); 11421 } 11422 11423 // Returns true if MemberExpr is checked and no further checking is needed. 11424 // Returns false if additional checking is required. 11425 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11426 llvm::SmallVector<FieldDecl*, 4> Fields; 11427 Expr *Base = E; 11428 bool ReferenceField = false; 11429 11430 // Get the field members used. 11431 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11432 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11433 if (!FD) 11434 return false; 11435 Fields.push_back(FD); 11436 if (FD->getType()->isReferenceType()) 11437 ReferenceField = true; 11438 Base = ME->getBase()->IgnoreParenImpCasts(); 11439 } 11440 11441 // Keep checking only if the base Decl is the same. 11442 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11443 if (!DRE || DRE->getDecl() != OrigDecl) 11444 return false; 11445 11446 // A reference field can be bound to an unininitialized field. 11447 if (CheckReference && !ReferenceField) 11448 return true; 11449 11450 // Convert FieldDecls to their index number. 11451 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11452 for (const FieldDecl *I : llvm::reverse(Fields)) 11453 UsedFieldIndex.push_back(I->getFieldIndex()); 11454 11455 // See if a warning is needed by checking the first difference in index 11456 // numbers. If field being used has index less than the field being 11457 // initialized, then the use is safe. 11458 for (auto UsedIter = UsedFieldIndex.begin(), 11459 UsedEnd = UsedFieldIndex.end(), 11460 OrigIter = InitFieldIndex.begin(), 11461 OrigEnd = InitFieldIndex.end(); 11462 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11463 if (*UsedIter < *OrigIter) 11464 return true; 11465 if (*UsedIter > *OrigIter) 11466 break; 11467 } 11468 11469 // TODO: Add a different warning which will print the field names. 11470 HandleDeclRefExpr(DRE); 11471 return true; 11472 } 11473 11474 // For most expressions, the cast is directly above the DeclRefExpr. 11475 // For conditional operators, the cast can be outside the conditional 11476 // operator if both expressions are DeclRefExpr's. 11477 void HandleValue(Expr *E) { 11478 E = E->IgnoreParens(); 11479 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11480 HandleDeclRefExpr(DRE); 11481 return; 11482 } 11483 11484 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11485 Visit(CO->getCond()); 11486 HandleValue(CO->getTrueExpr()); 11487 HandleValue(CO->getFalseExpr()); 11488 return; 11489 } 11490 11491 if (BinaryConditionalOperator *BCO = 11492 dyn_cast<BinaryConditionalOperator>(E)) { 11493 Visit(BCO->getCond()); 11494 HandleValue(BCO->getFalseExpr()); 11495 return; 11496 } 11497 11498 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11499 HandleValue(OVE->getSourceExpr()); 11500 return; 11501 } 11502 11503 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11504 if (BO->getOpcode() == BO_Comma) { 11505 Visit(BO->getLHS()); 11506 HandleValue(BO->getRHS()); 11507 return; 11508 } 11509 } 11510 11511 if (isa<MemberExpr>(E)) { 11512 if (isInitList) { 11513 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11514 false /*CheckReference*/)) 11515 return; 11516 } 11517 11518 Expr *Base = E->IgnoreParenImpCasts(); 11519 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11520 // Check for static member variables and don't warn on them. 11521 if (!isa<FieldDecl>(ME->getMemberDecl())) 11522 return; 11523 Base = ME->getBase()->IgnoreParenImpCasts(); 11524 } 11525 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11526 HandleDeclRefExpr(DRE); 11527 return; 11528 } 11529 11530 Visit(E); 11531 } 11532 11533 // Reference types not handled in HandleValue are handled here since all 11534 // uses of references are bad, not just r-value uses. 11535 void VisitDeclRefExpr(DeclRefExpr *E) { 11536 if (isReferenceType) 11537 HandleDeclRefExpr(E); 11538 } 11539 11540 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11541 if (E->getCastKind() == CK_LValueToRValue) { 11542 HandleValue(E->getSubExpr()); 11543 return; 11544 } 11545 11546 Inherited::VisitImplicitCastExpr(E); 11547 } 11548 11549 void VisitMemberExpr(MemberExpr *E) { 11550 if (isInitList) { 11551 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11552 return; 11553 } 11554 11555 // Don't warn on arrays since they can be treated as pointers. 11556 if (E->getType()->canDecayToPointerType()) return; 11557 11558 // Warn when a non-static method call is followed by non-static member 11559 // field accesses, which is followed by a DeclRefExpr. 11560 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11561 bool Warn = (MD && !MD->isStatic()); 11562 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11563 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11564 if (!isa<FieldDecl>(ME->getMemberDecl())) 11565 Warn = false; 11566 Base = ME->getBase()->IgnoreParenImpCasts(); 11567 } 11568 11569 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11570 if (Warn) 11571 HandleDeclRefExpr(DRE); 11572 return; 11573 } 11574 11575 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11576 // Visit that expression. 11577 Visit(Base); 11578 } 11579 11580 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11581 Expr *Callee = E->getCallee(); 11582 11583 if (isa<UnresolvedLookupExpr>(Callee)) 11584 return Inherited::VisitCXXOperatorCallExpr(E); 11585 11586 Visit(Callee); 11587 for (auto Arg: E->arguments()) 11588 HandleValue(Arg->IgnoreParenImpCasts()); 11589 } 11590 11591 void VisitUnaryOperator(UnaryOperator *E) { 11592 // For POD record types, addresses of its own members are well-defined. 11593 if (E->getOpcode() == UO_AddrOf && isRecordType && 11594 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11595 if (!isPODType) 11596 HandleValue(E->getSubExpr()); 11597 return; 11598 } 11599 11600 if (E->isIncrementDecrementOp()) { 11601 HandleValue(E->getSubExpr()); 11602 return; 11603 } 11604 11605 Inherited::VisitUnaryOperator(E); 11606 } 11607 11608 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11609 11610 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11611 if (E->getConstructor()->isCopyConstructor()) { 11612 Expr *ArgExpr = E->getArg(0); 11613 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11614 if (ILE->getNumInits() == 1) 11615 ArgExpr = ILE->getInit(0); 11616 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11617 if (ICE->getCastKind() == CK_NoOp) 11618 ArgExpr = ICE->getSubExpr(); 11619 HandleValue(ArgExpr); 11620 return; 11621 } 11622 Inherited::VisitCXXConstructExpr(E); 11623 } 11624 11625 void VisitCallExpr(CallExpr *E) { 11626 // Treat std::move as a use. 11627 if (E->isCallToStdMove()) { 11628 HandleValue(E->getArg(0)); 11629 return; 11630 } 11631 11632 Inherited::VisitCallExpr(E); 11633 } 11634 11635 void VisitBinaryOperator(BinaryOperator *E) { 11636 if (E->isCompoundAssignmentOp()) { 11637 HandleValue(E->getLHS()); 11638 Visit(E->getRHS()); 11639 return; 11640 } 11641 11642 Inherited::VisitBinaryOperator(E); 11643 } 11644 11645 // A custom visitor for BinaryConditionalOperator is needed because the 11646 // regular visitor would check the condition and true expression separately 11647 // but both point to the same place giving duplicate diagnostics. 11648 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11649 Visit(E->getCond()); 11650 Visit(E->getFalseExpr()); 11651 } 11652 11653 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11654 Decl* ReferenceDecl = DRE->getDecl(); 11655 if (OrigDecl != ReferenceDecl) return; 11656 unsigned diag; 11657 if (isReferenceType) { 11658 diag = diag::warn_uninit_self_reference_in_reference_init; 11659 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11660 diag = diag::warn_static_self_reference_in_init; 11661 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11662 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11663 DRE->getDecl()->getType()->isRecordType()) { 11664 diag = diag::warn_uninit_self_reference_in_init; 11665 } else { 11666 // Local variables will be handled by the CFG analysis. 11667 return; 11668 } 11669 11670 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11671 S.PDiag(diag) 11672 << DRE->getDecl() << OrigDecl->getLocation() 11673 << DRE->getSourceRange()); 11674 } 11675 }; 11676 11677 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11678 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11679 bool DirectInit) { 11680 // Parameters arguments are occassionially constructed with itself, 11681 // for instance, in recursive functions. Skip them. 11682 if (isa<ParmVarDecl>(OrigDecl)) 11683 return; 11684 11685 E = E->IgnoreParens(); 11686 11687 // Skip checking T a = a where T is not a record or reference type. 11688 // Doing so is a way to silence uninitialized warnings. 11689 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11690 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11691 if (ICE->getCastKind() == CK_LValueToRValue) 11692 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11693 if (DRE->getDecl() == OrigDecl) 11694 return; 11695 11696 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11697 } 11698 } // end anonymous namespace 11699 11700 namespace { 11701 // Simple wrapper to add the name of a variable or (if no variable is 11702 // available) a DeclarationName into a diagnostic. 11703 struct VarDeclOrName { 11704 VarDecl *VDecl; 11705 DeclarationName Name; 11706 11707 friend const Sema::SemaDiagnosticBuilder & 11708 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11709 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11710 } 11711 }; 11712 } // end anonymous namespace 11713 11714 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11715 DeclarationName Name, QualType Type, 11716 TypeSourceInfo *TSI, 11717 SourceRange Range, bool DirectInit, 11718 Expr *Init) { 11719 bool IsInitCapture = !VDecl; 11720 assert((!VDecl || !VDecl->isInitCapture()) && 11721 "init captures are expected to be deduced prior to initialization"); 11722 11723 VarDeclOrName VN{VDecl, Name}; 11724 11725 DeducedType *Deduced = Type->getContainedDeducedType(); 11726 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11727 11728 // C++11 [dcl.spec.auto]p3 11729 if (!Init) { 11730 assert(VDecl && "no init for init capture deduction?"); 11731 11732 // Except for class argument deduction, and then for an initializing 11733 // declaration only, i.e. no static at class scope or extern. 11734 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11735 VDecl->hasExternalStorage() || 11736 VDecl->isStaticDataMember()) { 11737 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11738 << VDecl->getDeclName() << Type; 11739 return QualType(); 11740 } 11741 } 11742 11743 ArrayRef<Expr*> DeduceInits; 11744 if (Init) 11745 DeduceInits = Init; 11746 11747 if (DirectInit) { 11748 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11749 DeduceInits = PL->exprs(); 11750 } 11751 11752 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11753 assert(VDecl && "non-auto type for init capture deduction?"); 11754 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11755 InitializationKind Kind = InitializationKind::CreateForInit( 11756 VDecl->getLocation(), DirectInit, Init); 11757 // FIXME: Initialization should not be taking a mutable list of inits. 11758 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11759 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11760 InitsCopy); 11761 } 11762 11763 if (DirectInit) { 11764 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11765 DeduceInits = IL->inits(); 11766 } 11767 11768 // Deduction only works if we have exactly one source expression. 11769 if (DeduceInits.empty()) { 11770 // It isn't possible to write this directly, but it is possible to 11771 // end up in this situation with "auto x(some_pack...);" 11772 Diag(Init->getBeginLoc(), IsInitCapture 11773 ? diag::err_init_capture_no_expression 11774 : diag::err_auto_var_init_no_expression) 11775 << VN << Type << Range; 11776 return QualType(); 11777 } 11778 11779 if (DeduceInits.size() > 1) { 11780 Diag(DeduceInits[1]->getBeginLoc(), 11781 IsInitCapture ? diag::err_init_capture_multiple_expressions 11782 : diag::err_auto_var_init_multiple_expressions) 11783 << VN << Type << Range; 11784 return QualType(); 11785 } 11786 11787 Expr *DeduceInit = DeduceInits[0]; 11788 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11789 Diag(Init->getBeginLoc(), IsInitCapture 11790 ? diag::err_init_capture_paren_braces 11791 : diag::err_auto_var_init_paren_braces) 11792 << isa<InitListExpr>(Init) << VN << Type << Range; 11793 return QualType(); 11794 } 11795 11796 // Expressions default to 'id' when we're in a debugger. 11797 bool DefaultedAnyToId = false; 11798 if (getLangOpts().DebuggerCastResultToId && 11799 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11800 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11801 if (Result.isInvalid()) { 11802 return QualType(); 11803 } 11804 Init = Result.get(); 11805 DefaultedAnyToId = true; 11806 } 11807 11808 // C++ [dcl.decomp]p1: 11809 // If the assignment-expression [...] has array type A and no ref-qualifier 11810 // is present, e has type cv A 11811 if (VDecl && isa<DecompositionDecl>(VDecl) && 11812 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11813 DeduceInit->getType()->isConstantArrayType()) 11814 return Context.getQualifiedType(DeduceInit->getType(), 11815 Type.getQualifiers()); 11816 11817 QualType DeducedType; 11818 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11819 if (!IsInitCapture) 11820 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11821 else if (isa<InitListExpr>(Init)) 11822 Diag(Range.getBegin(), 11823 diag::err_init_capture_deduction_failure_from_init_list) 11824 << VN 11825 << (DeduceInit->getType().isNull() ? TSI->getType() 11826 : DeduceInit->getType()) 11827 << DeduceInit->getSourceRange(); 11828 else 11829 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11830 << VN << TSI->getType() 11831 << (DeduceInit->getType().isNull() ? TSI->getType() 11832 : DeduceInit->getType()) 11833 << DeduceInit->getSourceRange(); 11834 } 11835 11836 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11837 // 'id' instead of a specific object type prevents most of our usual 11838 // checks. 11839 // We only want to warn outside of template instantiations, though: 11840 // inside a template, the 'id' could have come from a parameter. 11841 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11842 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11843 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11844 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11845 } 11846 11847 return DeducedType; 11848 } 11849 11850 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11851 Expr *Init) { 11852 assert(!Init || !Init->containsErrors()); 11853 QualType DeducedType = deduceVarTypeFromInitializer( 11854 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11855 VDecl->getSourceRange(), DirectInit, Init); 11856 if (DeducedType.isNull()) { 11857 VDecl->setInvalidDecl(); 11858 return true; 11859 } 11860 11861 VDecl->setType(DeducedType); 11862 assert(VDecl->isLinkageValid()); 11863 11864 // In ARC, infer lifetime. 11865 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11866 VDecl->setInvalidDecl(); 11867 11868 if (getLangOpts().OpenCL) 11869 deduceOpenCLAddressSpace(VDecl); 11870 11871 // If this is a redeclaration, check that the type we just deduced matches 11872 // the previously declared type. 11873 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11874 // We never need to merge the type, because we cannot form an incomplete 11875 // array of auto, nor deduce such a type. 11876 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11877 } 11878 11879 // Check the deduced type is valid for a variable declaration. 11880 CheckVariableDeclarationType(VDecl); 11881 return VDecl->isInvalidDecl(); 11882 } 11883 11884 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11885 SourceLocation Loc) { 11886 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11887 Init = EWC->getSubExpr(); 11888 11889 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11890 Init = CE->getSubExpr(); 11891 11892 QualType InitType = Init->getType(); 11893 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11894 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11895 "shouldn't be called if type doesn't have a non-trivial C struct"); 11896 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11897 for (auto I : ILE->inits()) { 11898 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11899 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11900 continue; 11901 SourceLocation SL = I->getExprLoc(); 11902 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11903 } 11904 return; 11905 } 11906 11907 if (isa<ImplicitValueInitExpr>(Init)) { 11908 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11909 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11910 NTCUK_Init); 11911 } else { 11912 // Assume all other explicit initializers involving copying some existing 11913 // object. 11914 // TODO: ignore any explicit initializers where we can guarantee 11915 // copy-elision. 11916 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11917 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11918 } 11919 } 11920 11921 namespace { 11922 11923 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11924 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11925 // in the source code or implicitly by the compiler if it is in a union 11926 // defined in a system header and has non-trivial ObjC ownership 11927 // qualifications. We don't want those fields to participate in determining 11928 // whether the containing union is non-trivial. 11929 return FD->hasAttr<UnavailableAttr>(); 11930 } 11931 11932 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11933 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11934 void> { 11935 using Super = 11936 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11937 void>; 11938 11939 DiagNonTrivalCUnionDefaultInitializeVisitor( 11940 QualType OrigTy, SourceLocation OrigLoc, 11941 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11942 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11943 11944 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11945 const FieldDecl *FD, bool InNonTrivialUnion) { 11946 if (const auto *AT = S.Context.getAsArrayType(QT)) 11947 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11948 InNonTrivialUnion); 11949 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11950 } 11951 11952 void visitARCStrong(QualType QT, const FieldDecl *FD, 11953 bool InNonTrivialUnion) { 11954 if (InNonTrivialUnion) 11955 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11956 << 1 << 0 << QT << FD->getName(); 11957 } 11958 11959 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11960 if (InNonTrivialUnion) 11961 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11962 << 1 << 0 << QT << FD->getName(); 11963 } 11964 11965 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11966 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11967 if (RD->isUnion()) { 11968 if (OrigLoc.isValid()) { 11969 bool IsUnion = false; 11970 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11971 IsUnion = OrigRD->isUnion(); 11972 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11973 << 0 << OrigTy << IsUnion << UseContext; 11974 // Reset OrigLoc so that this diagnostic is emitted only once. 11975 OrigLoc = SourceLocation(); 11976 } 11977 InNonTrivialUnion = true; 11978 } 11979 11980 if (InNonTrivialUnion) 11981 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11982 << 0 << 0 << QT.getUnqualifiedType() << ""; 11983 11984 for (const FieldDecl *FD : RD->fields()) 11985 if (!shouldIgnoreForRecordTriviality(FD)) 11986 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11987 } 11988 11989 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11990 11991 // The non-trivial C union type or the struct/union type that contains a 11992 // non-trivial C union. 11993 QualType OrigTy; 11994 SourceLocation OrigLoc; 11995 Sema::NonTrivialCUnionContext UseContext; 11996 Sema &S; 11997 }; 11998 11999 struct DiagNonTrivalCUnionDestructedTypeVisitor 12000 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12001 using Super = 12002 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12003 12004 DiagNonTrivalCUnionDestructedTypeVisitor( 12005 QualType OrigTy, SourceLocation OrigLoc, 12006 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12007 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12008 12009 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12010 const FieldDecl *FD, bool InNonTrivialUnion) { 12011 if (const auto *AT = S.Context.getAsArrayType(QT)) 12012 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12013 InNonTrivialUnion); 12014 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12015 } 12016 12017 void visitARCStrong(QualType QT, const FieldDecl *FD, 12018 bool InNonTrivialUnion) { 12019 if (InNonTrivialUnion) 12020 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12021 << 1 << 1 << QT << FD->getName(); 12022 } 12023 12024 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12025 if (InNonTrivialUnion) 12026 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12027 << 1 << 1 << QT << FD->getName(); 12028 } 12029 12030 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12031 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12032 if (RD->isUnion()) { 12033 if (OrigLoc.isValid()) { 12034 bool IsUnion = false; 12035 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12036 IsUnion = OrigRD->isUnion(); 12037 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12038 << 1 << OrigTy << IsUnion << UseContext; 12039 // Reset OrigLoc so that this diagnostic is emitted only once. 12040 OrigLoc = SourceLocation(); 12041 } 12042 InNonTrivialUnion = true; 12043 } 12044 12045 if (InNonTrivialUnion) 12046 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12047 << 0 << 1 << QT.getUnqualifiedType() << ""; 12048 12049 for (const FieldDecl *FD : RD->fields()) 12050 if (!shouldIgnoreForRecordTriviality(FD)) 12051 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12052 } 12053 12054 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12055 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12056 bool InNonTrivialUnion) {} 12057 12058 // The non-trivial C union type or the struct/union type that contains a 12059 // non-trivial C union. 12060 QualType OrigTy; 12061 SourceLocation OrigLoc; 12062 Sema::NonTrivialCUnionContext UseContext; 12063 Sema &S; 12064 }; 12065 12066 struct DiagNonTrivalCUnionCopyVisitor 12067 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12068 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12069 12070 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12071 Sema::NonTrivialCUnionContext UseContext, 12072 Sema &S) 12073 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12074 12075 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12076 const FieldDecl *FD, bool InNonTrivialUnion) { 12077 if (const auto *AT = S.Context.getAsArrayType(QT)) 12078 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12079 InNonTrivialUnion); 12080 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12081 } 12082 12083 void visitARCStrong(QualType QT, const FieldDecl *FD, 12084 bool InNonTrivialUnion) { 12085 if (InNonTrivialUnion) 12086 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12087 << 1 << 2 << QT << FD->getName(); 12088 } 12089 12090 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12091 if (InNonTrivialUnion) 12092 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12093 << 1 << 2 << QT << FD->getName(); 12094 } 12095 12096 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12097 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12098 if (RD->isUnion()) { 12099 if (OrigLoc.isValid()) { 12100 bool IsUnion = false; 12101 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12102 IsUnion = OrigRD->isUnion(); 12103 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12104 << 2 << OrigTy << IsUnion << UseContext; 12105 // Reset OrigLoc so that this diagnostic is emitted only once. 12106 OrigLoc = SourceLocation(); 12107 } 12108 InNonTrivialUnion = true; 12109 } 12110 12111 if (InNonTrivialUnion) 12112 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12113 << 0 << 2 << QT.getUnqualifiedType() << ""; 12114 12115 for (const FieldDecl *FD : RD->fields()) 12116 if (!shouldIgnoreForRecordTriviality(FD)) 12117 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12118 } 12119 12120 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12121 const FieldDecl *FD, bool InNonTrivialUnion) {} 12122 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12123 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12124 bool InNonTrivialUnion) {} 12125 12126 // The non-trivial C union type or the struct/union type that contains a 12127 // non-trivial C union. 12128 QualType OrigTy; 12129 SourceLocation OrigLoc; 12130 Sema::NonTrivialCUnionContext UseContext; 12131 Sema &S; 12132 }; 12133 12134 } // namespace 12135 12136 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12137 NonTrivialCUnionContext UseContext, 12138 unsigned NonTrivialKind) { 12139 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12140 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12141 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12142 "shouldn't be called if type doesn't have a non-trivial C union"); 12143 12144 if ((NonTrivialKind & NTCUK_Init) && 12145 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12146 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12147 .visit(QT, nullptr, false); 12148 if ((NonTrivialKind & NTCUK_Destruct) && 12149 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12150 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12151 .visit(QT, nullptr, false); 12152 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12153 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12154 .visit(QT, nullptr, false); 12155 } 12156 12157 /// AddInitializerToDecl - Adds the initializer Init to the 12158 /// declaration dcl. If DirectInit is true, this is C++ direct 12159 /// initialization rather than copy initialization. 12160 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12161 // If there is no declaration, there was an error parsing it. Just ignore 12162 // the initializer. 12163 if (!RealDecl || RealDecl->isInvalidDecl()) { 12164 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12165 return; 12166 } 12167 12168 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12169 // Pure-specifiers are handled in ActOnPureSpecifier. 12170 Diag(Method->getLocation(), diag::err_member_function_initialization) 12171 << Method->getDeclName() << Init->getSourceRange(); 12172 Method->setInvalidDecl(); 12173 return; 12174 } 12175 12176 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12177 if (!VDecl) { 12178 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12179 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12180 RealDecl->setInvalidDecl(); 12181 return; 12182 } 12183 12184 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12185 if (VDecl->getType()->isUndeducedType()) { 12186 // Attempt typo correction early so that the type of the init expression can 12187 // be deduced based on the chosen correction if the original init contains a 12188 // TypoExpr. 12189 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12190 if (!Res.isUsable()) { 12191 // There are unresolved typos in Init, just drop them. 12192 // FIXME: improve the recovery strategy to preserve the Init. 12193 RealDecl->setInvalidDecl(); 12194 return; 12195 } 12196 if (Res.get()->containsErrors()) { 12197 // Invalidate the decl as we don't know the type for recovery-expr yet. 12198 RealDecl->setInvalidDecl(); 12199 VDecl->setInit(Res.get()); 12200 return; 12201 } 12202 Init = Res.get(); 12203 12204 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12205 return; 12206 } 12207 12208 // dllimport cannot be used on variable definitions. 12209 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12210 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12211 VDecl->setInvalidDecl(); 12212 return; 12213 } 12214 12215 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12216 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12217 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12218 VDecl->setInvalidDecl(); 12219 return; 12220 } 12221 12222 if (!VDecl->getType()->isDependentType()) { 12223 // A definition must end up with a complete type, which means it must be 12224 // complete with the restriction that an array type might be completed by 12225 // the initializer; note that later code assumes this restriction. 12226 QualType BaseDeclType = VDecl->getType(); 12227 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12228 BaseDeclType = Array->getElementType(); 12229 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12230 diag::err_typecheck_decl_incomplete_type)) { 12231 RealDecl->setInvalidDecl(); 12232 return; 12233 } 12234 12235 // The variable can not have an abstract class type. 12236 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12237 diag::err_abstract_type_in_decl, 12238 AbstractVariableType)) 12239 VDecl->setInvalidDecl(); 12240 } 12241 12242 // If adding the initializer will turn this declaration into a definition, 12243 // and we already have a definition for this variable, diagnose or otherwise 12244 // handle the situation. 12245 if (VarDecl *Def = VDecl->getDefinition()) 12246 if (Def != VDecl && 12247 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12248 !VDecl->isThisDeclarationADemotedDefinition() && 12249 checkVarDeclRedefinition(Def, VDecl)) 12250 return; 12251 12252 if (getLangOpts().CPlusPlus) { 12253 // C++ [class.static.data]p4 12254 // If a static data member is of const integral or const 12255 // enumeration type, its declaration in the class definition can 12256 // specify a constant-initializer which shall be an integral 12257 // constant expression (5.19). In that case, the member can appear 12258 // in integral constant expressions. The member shall still be 12259 // defined in a namespace scope if it is used in the program and the 12260 // namespace scope definition shall not contain an initializer. 12261 // 12262 // We already performed a redefinition check above, but for static 12263 // data members we also need to check whether there was an in-class 12264 // declaration with an initializer. 12265 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12266 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12267 << VDecl->getDeclName(); 12268 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12269 diag::note_previous_initializer) 12270 << 0; 12271 return; 12272 } 12273 12274 if (VDecl->hasLocalStorage()) 12275 setFunctionHasBranchProtectedScope(); 12276 12277 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12278 VDecl->setInvalidDecl(); 12279 return; 12280 } 12281 } 12282 12283 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12284 // a kernel function cannot be initialized." 12285 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12286 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12287 VDecl->setInvalidDecl(); 12288 return; 12289 } 12290 12291 // The LoaderUninitialized attribute acts as a definition (of undef). 12292 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12293 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12294 VDecl->setInvalidDecl(); 12295 return; 12296 } 12297 12298 // Get the decls type and save a reference for later, since 12299 // CheckInitializerTypes may change it. 12300 QualType DclT = VDecl->getType(), SavT = DclT; 12301 12302 // Expressions default to 'id' when we're in a debugger 12303 // and we are assigning it to a variable of Objective-C pointer type. 12304 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12305 Init->getType() == Context.UnknownAnyTy) { 12306 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12307 if (Result.isInvalid()) { 12308 VDecl->setInvalidDecl(); 12309 return; 12310 } 12311 Init = Result.get(); 12312 } 12313 12314 // Perform the initialization. 12315 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12316 if (!VDecl->isInvalidDecl()) { 12317 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12318 InitializationKind Kind = InitializationKind::CreateForInit( 12319 VDecl->getLocation(), DirectInit, Init); 12320 12321 MultiExprArg Args = Init; 12322 if (CXXDirectInit) 12323 Args = MultiExprArg(CXXDirectInit->getExprs(), 12324 CXXDirectInit->getNumExprs()); 12325 12326 // Try to correct any TypoExprs in the initialization arguments. 12327 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12328 ExprResult Res = CorrectDelayedTyposInExpr( 12329 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12330 [this, Entity, Kind](Expr *E) { 12331 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12332 return Init.Failed() ? ExprError() : E; 12333 }); 12334 if (Res.isInvalid()) { 12335 VDecl->setInvalidDecl(); 12336 } else if (Res.get() != Args[Idx]) { 12337 Args[Idx] = Res.get(); 12338 } 12339 } 12340 if (VDecl->isInvalidDecl()) 12341 return; 12342 12343 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12344 /*TopLevelOfInitList=*/false, 12345 /*TreatUnavailableAsInvalid=*/false); 12346 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12347 if (Result.isInvalid()) { 12348 // If the provied initializer fails to initialize the var decl, 12349 // we attach a recovery expr for better recovery. 12350 auto RecoveryExpr = 12351 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12352 if (RecoveryExpr.get()) 12353 VDecl->setInit(RecoveryExpr.get()); 12354 return; 12355 } 12356 12357 Init = Result.getAs<Expr>(); 12358 } 12359 12360 // Check for self-references within variable initializers. 12361 // Variables declared within a function/method body (except for references) 12362 // are handled by a dataflow analysis. 12363 // This is undefined behavior in C++, but valid in C. 12364 if (getLangOpts().CPlusPlus) 12365 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12366 VDecl->getType()->isReferenceType()) 12367 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12368 12369 // If the type changed, it means we had an incomplete type that was 12370 // completed by the initializer. For example: 12371 // int ary[] = { 1, 3, 5 }; 12372 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12373 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12374 VDecl->setType(DclT); 12375 12376 if (!VDecl->isInvalidDecl()) { 12377 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12378 12379 if (VDecl->hasAttr<BlocksAttr>()) 12380 checkRetainCycles(VDecl, Init); 12381 12382 // It is safe to assign a weak reference into a strong variable. 12383 // Although this code can still have problems: 12384 // id x = self.weakProp; 12385 // id y = self.weakProp; 12386 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12387 // paths through the function. This should be revisited if 12388 // -Wrepeated-use-of-weak is made flow-sensitive. 12389 if (FunctionScopeInfo *FSI = getCurFunction()) 12390 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12391 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12392 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12393 Init->getBeginLoc())) 12394 FSI->markSafeWeakUse(Init); 12395 } 12396 12397 // The initialization is usually a full-expression. 12398 // 12399 // FIXME: If this is a braced initialization of an aggregate, it is not 12400 // an expression, and each individual field initializer is a separate 12401 // full-expression. For instance, in: 12402 // 12403 // struct Temp { ~Temp(); }; 12404 // struct S { S(Temp); }; 12405 // struct T { S a, b; } t = { Temp(), Temp() } 12406 // 12407 // we should destroy the first Temp before constructing the second. 12408 ExprResult Result = 12409 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12410 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12411 if (Result.isInvalid()) { 12412 VDecl->setInvalidDecl(); 12413 return; 12414 } 12415 Init = Result.get(); 12416 12417 // Attach the initializer to the decl. 12418 VDecl->setInit(Init); 12419 12420 if (VDecl->isLocalVarDecl()) { 12421 // Don't check the initializer if the declaration is malformed. 12422 if (VDecl->isInvalidDecl()) { 12423 // do nothing 12424 12425 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12426 // This is true even in C++ for OpenCL. 12427 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12428 CheckForConstantInitializer(Init, DclT); 12429 12430 // Otherwise, C++ does not restrict the initializer. 12431 } else if (getLangOpts().CPlusPlus) { 12432 // do nothing 12433 12434 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12435 // static storage duration shall be constant expressions or string literals. 12436 } else if (VDecl->getStorageClass() == SC_Static) { 12437 CheckForConstantInitializer(Init, DclT); 12438 12439 // C89 is stricter than C99 for aggregate initializers. 12440 // C89 6.5.7p3: All the expressions [...] in an initializer list 12441 // for an object that has aggregate or union type shall be 12442 // constant expressions. 12443 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12444 isa<InitListExpr>(Init)) { 12445 const Expr *Culprit; 12446 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12447 Diag(Culprit->getExprLoc(), 12448 diag::ext_aggregate_init_not_constant) 12449 << Culprit->getSourceRange(); 12450 } 12451 } 12452 12453 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12454 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12455 if (VDecl->hasLocalStorage()) 12456 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12457 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12458 VDecl->getLexicalDeclContext()->isRecord()) { 12459 // This is an in-class initialization for a static data member, e.g., 12460 // 12461 // struct S { 12462 // static const int value = 17; 12463 // }; 12464 12465 // C++ [class.mem]p4: 12466 // A member-declarator can contain a constant-initializer only 12467 // if it declares a static member (9.4) of const integral or 12468 // const enumeration type, see 9.4.2. 12469 // 12470 // C++11 [class.static.data]p3: 12471 // If a non-volatile non-inline const static data member is of integral 12472 // or enumeration type, its declaration in the class definition can 12473 // specify a brace-or-equal-initializer in which every initializer-clause 12474 // that is an assignment-expression is a constant expression. A static 12475 // data member of literal type can be declared in the class definition 12476 // with the constexpr specifier; if so, its declaration shall specify a 12477 // brace-or-equal-initializer in which every initializer-clause that is 12478 // an assignment-expression is a constant expression. 12479 12480 // Do nothing on dependent types. 12481 if (DclT->isDependentType()) { 12482 12483 // Allow any 'static constexpr' members, whether or not they are of literal 12484 // type. We separately check that every constexpr variable is of literal 12485 // type. 12486 } else if (VDecl->isConstexpr()) { 12487 12488 // Require constness. 12489 } else if (!DclT.isConstQualified()) { 12490 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12491 << Init->getSourceRange(); 12492 VDecl->setInvalidDecl(); 12493 12494 // We allow integer constant expressions in all cases. 12495 } else if (DclT->isIntegralOrEnumerationType()) { 12496 // Check whether the expression is a constant expression. 12497 SourceLocation Loc; 12498 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12499 // In C++11, a non-constexpr const static data member with an 12500 // in-class initializer cannot be volatile. 12501 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12502 else if (Init->isValueDependent()) 12503 ; // Nothing to check. 12504 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12505 ; // Ok, it's an ICE! 12506 else if (Init->getType()->isScopedEnumeralType() && 12507 Init->isCXX11ConstantExpr(Context)) 12508 ; // Ok, it is a scoped-enum constant expression. 12509 else if (Init->isEvaluatable(Context)) { 12510 // If we can constant fold the initializer through heroics, accept it, 12511 // but report this as a use of an extension for -pedantic. 12512 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12513 << Init->getSourceRange(); 12514 } else { 12515 // Otherwise, this is some crazy unknown case. Report the issue at the 12516 // location provided by the isIntegerConstantExpr failed check. 12517 Diag(Loc, diag::err_in_class_initializer_non_constant) 12518 << Init->getSourceRange(); 12519 VDecl->setInvalidDecl(); 12520 } 12521 12522 // We allow foldable floating-point constants as an extension. 12523 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12524 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12525 // it anyway and provide a fixit to add the 'constexpr'. 12526 if (getLangOpts().CPlusPlus11) { 12527 Diag(VDecl->getLocation(), 12528 diag::ext_in_class_initializer_float_type_cxx11) 12529 << DclT << Init->getSourceRange(); 12530 Diag(VDecl->getBeginLoc(), 12531 diag::note_in_class_initializer_float_type_cxx11) 12532 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12533 } else { 12534 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12535 << DclT << Init->getSourceRange(); 12536 12537 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12538 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12539 << Init->getSourceRange(); 12540 VDecl->setInvalidDecl(); 12541 } 12542 } 12543 12544 // Suggest adding 'constexpr' in C++11 for literal types. 12545 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12546 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12547 << DclT << Init->getSourceRange() 12548 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12549 VDecl->setConstexpr(true); 12550 12551 } else { 12552 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12553 << DclT << Init->getSourceRange(); 12554 VDecl->setInvalidDecl(); 12555 } 12556 } else if (VDecl->isFileVarDecl()) { 12557 // In C, extern is typically used to avoid tentative definitions when 12558 // declaring variables in headers, but adding an intializer makes it a 12559 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12560 // In C++, extern is often used to give implictly static const variables 12561 // external linkage, so don't warn in that case. If selectany is present, 12562 // this might be header code intended for C and C++ inclusion, so apply the 12563 // C++ rules. 12564 if (VDecl->getStorageClass() == SC_Extern && 12565 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12566 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12567 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12568 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12569 Diag(VDecl->getLocation(), diag::warn_extern_init); 12570 12571 // In Microsoft C++ mode, a const variable defined in namespace scope has 12572 // external linkage by default if the variable is declared with 12573 // __declspec(dllexport). 12574 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12575 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12576 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12577 VDecl->setStorageClass(SC_Extern); 12578 12579 // C99 6.7.8p4. All file scoped initializers need to be constant. 12580 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12581 CheckForConstantInitializer(Init, DclT); 12582 } 12583 12584 QualType InitType = Init->getType(); 12585 if (!InitType.isNull() && 12586 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12587 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12588 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12589 12590 // We will represent direct-initialization similarly to copy-initialization: 12591 // int x(1); -as-> int x = 1; 12592 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12593 // 12594 // Clients that want to distinguish between the two forms, can check for 12595 // direct initializer using VarDecl::getInitStyle(). 12596 // A major benefit is that clients that don't particularly care about which 12597 // exactly form was it (like the CodeGen) can handle both cases without 12598 // special case code. 12599 12600 // C++ 8.5p11: 12601 // The form of initialization (using parentheses or '=') is generally 12602 // insignificant, but does matter when the entity being initialized has a 12603 // class type. 12604 if (CXXDirectInit) { 12605 assert(DirectInit && "Call-style initializer must be direct init."); 12606 VDecl->setInitStyle(VarDecl::CallInit); 12607 } else if (DirectInit) { 12608 // This must be list-initialization. No other way is direct-initialization. 12609 VDecl->setInitStyle(VarDecl::ListInit); 12610 } 12611 12612 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12613 DeclsToCheckForDeferredDiags.insert(VDecl); 12614 CheckCompleteVariableDeclaration(VDecl); 12615 } 12616 12617 /// ActOnInitializerError - Given that there was an error parsing an 12618 /// initializer for the given declaration, try to return to some form 12619 /// of sanity. 12620 void Sema::ActOnInitializerError(Decl *D) { 12621 // Our main concern here is re-establishing invariants like "a 12622 // variable's type is either dependent or complete". 12623 if (!D || D->isInvalidDecl()) return; 12624 12625 VarDecl *VD = dyn_cast<VarDecl>(D); 12626 if (!VD) return; 12627 12628 // Bindings are not usable if we can't make sense of the initializer. 12629 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12630 for (auto *BD : DD->bindings()) 12631 BD->setInvalidDecl(); 12632 12633 // Auto types are meaningless if we can't make sense of the initializer. 12634 if (VD->getType()->isUndeducedType()) { 12635 D->setInvalidDecl(); 12636 return; 12637 } 12638 12639 QualType Ty = VD->getType(); 12640 if (Ty->isDependentType()) return; 12641 12642 // Require a complete type. 12643 if (RequireCompleteType(VD->getLocation(), 12644 Context.getBaseElementType(Ty), 12645 diag::err_typecheck_decl_incomplete_type)) { 12646 VD->setInvalidDecl(); 12647 return; 12648 } 12649 12650 // Require a non-abstract type. 12651 if (RequireNonAbstractType(VD->getLocation(), Ty, 12652 diag::err_abstract_type_in_decl, 12653 AbstractVariableType)) { 12654 VD->setInvalidDecl(); 12655 return; 12656 } 12657 12658 // Don't bother complaining about constructors or destructors, 12659 // though. 12660 } 12661 12662 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12663 // If there is no declaration, there was an error parsing it. Just ignore it. 12664 if (!RealDecl) 12665 return; 12666 12667 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12668 QualType Type = Var->getType(); 12669 12670 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12671 if (isa<DecompositionDecl>(RealDecl)) { 12672 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12673 Var->setInvalidDecl(); 12674 return; 12675 } 12676 12677 if (Type->isUndeducedType() && 12678 DeduceVariableDeclarationType(Var, false, nullptr)) 12679 return; 12680 12681 // C++11 [class.static.data]p3: A static data member can be declared with 12682 // the constexpr specifier; if so, its declaration shall specify 12683 // a brace-or-equal-initializer. 12684 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12685 // the definition of a variable [...] or the declaration of a static data 12686 // member. 12687 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12688 !Var->isThisDeclarationADemotedDefinition()) { 12689 if (Var->isStaticDataMember()) { 12690 // C++1z removes the relevant rule; the in-class declaration is always 12691 // a definition there. 12692 if (!getLangOpts().CPlusPlus17 && 12693 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12694 Diag(Var->getLocation(), 12695 diag::err_constexpr_static_mem_var_requires_init) 12696 << Var; 12697 Var->setInvalidDecl(); 12698 return; 12699 } 12700 } else { 12701 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12702 Var->setInvalidDecl(); 12703 return; 12704 } 12705 } 12706 12707 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12708 // be initialized. 12709 if (!Var->isInvalidDecl() && 12710 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12711 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12712 bool HasConstExprDefaultConstructor = false; 12713 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12714 for (auto *Ctor : RD->ctors()) { 12715 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12716 Ctor->getMethodQualifiers().getAddressSpace() == 12717 LangAS::opencl_constant) { 12718 HasConstExprDefaultConstructor = true; 12719 } 12720 } 12721 } 12722 if (!HasConstExprDefaultConstructor) { 12723 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12724 Var->setInvalidDecl(); 12725 return; 12726 } 12727 } 12728 12729 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12730 if (Var->getStorageClass() == SC_Extern) { 12731 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12732 << Var; 12733 Var->setInvalidDecl(); 12734 return; 12735 } 12736 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12737 diag::err_typecheck_decl_incomplete_type)) { 12738 Var->setInvalidDecl(); 12739 return; 12740 } 12741 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12742 if (!RD->hasTrivialDefaultConstructor()) { 12743 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12744 Var->setInvalidDecl(); 12745 return; 12746 } 12747 } 12748 // The declaration is unitialized, no need for further checks. 12749 return; 12750 } 12751 12752 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12753 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12754 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12755 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12756 NTCUC_DefaultInitializedObject, NTCUK_Init); 12757 12758 12759 switch (DefKind) { 12760 case VarDecl::Definition: 12761 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12762 break; 12763 12764 // We have an out-of-line definition of a static data member 12765 // that has an in-class initializer, so we type-check this like 12766 // a declaration. 12767 // 12768 LLVM_FALLTHROUGH; 12769 12770 case VarDecl::DeclarationOnly: 12771 // It's only a declaration. 12772 12773 // Block scope. C99 6.7p7: If an identifier for an object is 12774 // declared with no linkage (C99 6.2.2p6), the type for the 12775 // object shall be complete. 12776 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12777 !Var->hasLinkage() && !Var->isInvalidDecl() && 12778 RequireCompleteType(Var->getLocation(), Type, 12779 diag::err_typecheck_decl_incomplete_type)) 12780 Var->setInvalidDecl(); 12781 12782 // Make sure that the type is not abstract. 12783 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12784 RequireNonAbstractType(Var->getLocation(), Type, 12785 diag::err_abstract_type_in_decl, 12786 AbstractVariableType)) 12787 Var->setInvalidDecl(); 12788 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12789 Var->getStorageClass() == SC_PrivateExtern) { 12790 Diag(Var->getLocation(), diag::warn_private_extern); 12791 Diag(Var->getLocation(), diag::note_private_extern); 12792 } 12793 12794 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12795 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12796 ExternalDeclarations.push_back(Var); 12797 12798 return; 12799 12800 case VarDecl::TentativeDefinition: 12801 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12802 // object that has file scope without an initializer, and without a 12803 // storage-class specifier or with the storage-class specifier "static", 12804 // constitutes a tentative definition. Note: A tentative definition with 12805 // external linkage is valid (C99 6.2.2p5). 12806 if (!Var->isInvalidDecl()) { 12807 if (const IncompleteArrayType *ArrayT 12808 = Context.getAsIncompleteArrayType(Type)) { 12809 if (RequireCompleteSizedType( 12810 Var->getLocation(), ArrayT->getElementType(), 12811 diag::err_array_incomplete_or_sizeless_type)) 12812 Var->setInvalidDecl(); 12813 } else if (Var->getStorageClass() == SC_Static) { 12814 // C99 6.9.2p3: If the declaration of an identifier for an object is 12815 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12816 // declared type shall not be an incomplete type. 12817 // NOTE: code such as the following 12818 // static struct s; 12819 // struct s { int a; }; 12820 // is accepted by gcc. Hence here we issue a warning instead of 12821 // an error and we do not invalidate the static declaration. 12822 // NOTE: to avoid multiple warnings, only check the first declaration. 12823 if (Var->isFirstDecl()) 12824 RequireCompleteType(Var->getLocation(), Type, 12825 diag::ext_typecheck_decl_incomplete_type); 12826 } 12827 } 12828 12829 // Record the tentative definition; we're done. 12830 if (!Var->isInvalidDecl()) 12831 TentativeDefinitions.push_back(Var); 12832 return; 12833 } 12834 12835 // Provide a specific diagnostic for uninitialized variable 12836 // definitions with incomplete array type. 12837 if (Type->isIncompleteArrayType()) { 12838 Diag(Var->getLocation(), 12839 diag::err_typecheck_incomplete_array_needs_initializer); 12840 Var->setInvalidDecl(); 12841 return; 12842 } 12843 12844 // Provide a specific diagnostic for uninitialized variable 12845 // definitions with reference type. 12846 if (Type->isReferenceType()) { 12847 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12848 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12849 Var->setInvalidDecl(); 12850 return; 12851 } 12852 12853 // Do not attempt to type-check the default initializer for a 12854 // variable with dependent type. 12855 if (Type->isDependentType()) 12856 return; 12857 12858 if (Var->isInvalidDecl()) 12859 return; 12860 12861 if (!Var->hasAttr<AliasAttr>()) { 12862 if (RequireCompleteType(Var->getLocation(), 12863 Context.getBaseElementType(Type), 12864 diag::err_typecheck_decl_incomplete_type)) { 12865 Var->setInvalidDecl(); 12866 return; 12867 } 12868 } else { 12869 return; 12870 } 12871 12872 // The variable can not have an abstract class type. 12873 if (RequireNonAbstractType(Var->getLocation(), Type, 12874 diag::err_abstract_type_in_decl, 12875 AbstractVariableType)) { 12876 Var->setInvalidDecl(); 12877 return; 12878 } 12879 12880 // Check for jumps past the implicit initializer. C++0x 12881 // clarifies that this applies to a "variable with automatic 12882 // storage duration", not a "local variable". 12883 // C++11 [stmt.dcl]p3 12884 // A program that jumps from a point where a variable with automatic 12885 // storage duration is not in scope to a point where it is in scope is 12886 // ill-formed unless the variable has scalar type, class type with a 12887 // trivial default constructor and a trivial destructor, a cv-qualified 12888 // version of one of these types, or an array of one of the preceding 12889 // types and is declared without an initializer. 12890 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12891 if (const RecordType *Record 12892 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12893 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12894 // Mark the function (if we're in one) for further checking even if the 12895 // looser rules of C++11 do not require such checks, so that we can 12896 // diagnose incompatibilities with C++98. 12897 if (!CXXRecord->isPOD()) 12898 setFunctionHasBranchProtectedScope(); 12899 } 12900 } 12901 // In OpenCL, we can't initialize objects in the __local address space, 12902 // even implicitly, so don't synthesize an implicit initializer. 12903 if (getLangOpts().OpenCL && 12904 Var->getType().getAddressSpace() == LangAS::opencl_local) 12905 return; 12906 // C++03 [dcl.init]p9: 12907 // If no initializer is specified for an object, and the 12908 // object is of (possibly cv-qualified) non-POD class type (or 12909 // array thereof), the object shall be default-initialized; if 12910 // the object is of const-qualified type, the underlying class 12911 // type shall have a user-declared default 12912 // constructor. Otherwise, if no initializer is specified for 12913 // a non- static object, the object and its subobjects, if 12914 // any, have an indeterminate initial value); if the object 12915 // or any of its subobjects are of const-qualified type, the 12916 // program is ill-formed. 12917 // C++0x [dcl.init]p11: 12918 // If no initializer is specified for an object, the object is 12919 // default-initialized; [...]. 12920 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12921 InitializationKind Kind 12922 = InitializationKind::CreateDefault(Var->getLocation()); 12923 12924 InitializationSequence InitSeq(*this, Entity, Kind, None); 12925 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12926 12927 if (Init.get()) { 12928 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12929 // This is important for template substitution. 12930 Var->setInitStyle(VarDecl::CallInit); 12931 } else if (Init.isInvalid()) { 12932 // If default-init fails, attach a recovery-expr initializer to track 12933 // that initialization was attempted and failed. 12934 auto RecoveryExpr = 12935 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12936 if (RecoveryExpr.get()) 12937 Var->setInit(RecoveryExpr.get()); 12938 } 12939 12940 CheckCompleteVariableDeclaration(Var); 12941 } 12942 } 12943 12944 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12945 // If there is no declaration, there was an error parsing it. Ignore it. 12946 if (!D) 12947 return; 12948 12949 VarDecl *VD = dyn_cast<VarDecl>(D); 12950 if (!VD) { 12951 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12952 D->setInvalidDecl(); 12953 return; 12954 } 12955 12956 VD->setCXXForRangeDecl(true); 12957 12958 // for-range-declaration cannot be given a storage class specifier. 12959 int Error = -1; 12960 switch (VD->getStorageClass()) { 12961 case SC_None: 12962 break; 12963 case SC_Extern: 12964 Error = 0; 12965 break; 12966 case SC_Static: 12967 Error = 1; 12968 break; 12969 case SC_PrivateExtern: 12970 Error = 2; 12971 break; 12972 case SC_Auto: 12973 Error = 3; 12974 break; 12975 case SC_Register: 12976 Error = 4; 12977 break; 12978 } 12979 12980 // for-range-declaration cannot be given a storage class specifier con't. 12981 switch (VD->getTSCSpec()) { 12982 case TSCS_thread_local: 12983 Error = 6; 12984 break; 12985 case TSCS___thread: 12986 case TSCS__Thread_local: 12987 case TSCS_unspecified: 12988 break; 12989 } 12990 12991 if (Error != -1) { 12992 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12993 << VD << Error; 12994 D->setInvalidDecl(); 12995 } 12996 } 12997 12998 StmtResult 12999 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13000 IdentifierInfo *Ident, 13001 ParsedAttributes &Attrs, 13002 SourceLocation AttrEnd) { 13003 // C++1y [stmt.iter]p1: 13004 // A range-based for statement of the form 13005 // for ( for-range-identifier : for-range-initializer ) statement 13006 // is equivalent to 13007 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13008 DeclSpec DS(Attrs.getPool().getFactory()); 13009 13010 const char *PrevSpec; 13011 unsigned DiagID; 13012 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13013 getPrintingPolicy()); 13014 13015 Declarator D(DS, DeclaratorContext::ForInit); 13016 D.SetIdentifier(Ident, IdentLoc); 13017 D.takeAttributes(Attrs, AttrEnd); 13018 13019 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13020 IdentLoc); 13021 Decl *Var = ActOnDeclarator(S, D); 13022 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13023 FinalizeDeclaration(Var); 13024 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13025 AttrEnd.isValid() ? AttrEnd : IdentLoc); 13026 } 13027 13028 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13029 if (var->isInvalidDecl()) return; 13030 13031 MaybeAddCUDAConstantAttr(var); 13032 13033 if (getLangOpts().OpenCL) { 13034 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13035 // initialiser 13036 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13037 !var->hasInit()) { 13038 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13039 << 1 /*Init*/; 13040 var->setInvalidDecl(); 13041 return; 13042 } 13043 } 13044 13045 // In Objective-C, don't allow jumps past the implicit initialization of a 13046 // local retaining variable. 13047 if (getLangOpts().ObjC && 13048 var->hasLocalStorage()) { 13049 switch (var->getType().getObjCLifetime()) { 13050 case Qualifiers::OCL_None: 13051 case Qualifiers::OCL_ExplicitNone: 13052 case Qualifiers::OCL_Autoreleasing: 13053 break; 13054 13055 case Qualifiers::OCL_Weak: 13056 case Qualifiers::OCL_Strong: 13057 setFunctionHasBranchProtectedScope(); 13058 break; 13059 } 13060 } 13061 13062 if (var->hasLocalStorage() && 13063 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13064 setFunctionHasBranchProtectedScope(); 13065 13066 // Warn about externally-visible variables being defined without a 13067 // prior declaration. We only want to do this for global 13068 // declarations, but we also specifically need to avoid doing it for 13069 // class members because the linkage of an anonymous class can 13070 // change if it's later given a typedef name. 13071 if (var->isThisDeclarationADefinition() && 13072 var->getDeclContext()->getRedeclContext()->isFileContext() && 13073 var->isExternallyVisible() && var->hasLinkage() && 13074 !var->isInline() && !var->getDescribedVarTemplate() && 13075 !isa<VarTemplatePartialSpecializationDecl>(var) && 13076 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13077 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13078 var->getLocation())) { 13079 // Find a previous declaration that's not a definition. 13080 VarDecl *prev = var->getPreviousDecl(); 13081 while (prev && prev->isThisDeclarationADefinition()) 13082 prev = prev->getPreviousDecl(); 13083 13084 if (!prev) { 13085 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13086 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13087 << /* variable */ 0; 13088 } 13089 } 13090 13091 // Cache the result of checking for constant initialization. 13092 Optional<bool> CacheHasConstInit; 13093 const Expr *CacheCulprit = nullptr; 13094 auto checkConstInit = [&]() mutable { 13095 if (!CacheHasConstInit) 13096 CacheHasConstInit = var->getInit()->isConstantInitializer( 13097 Context, var->getType()->isReferenceType(), &CacheCulprit); 13098 return *CacheHasConstInit; 13099 }; 13100 13101 if (var->getTLSKind() == VarDecl::TLS_Static) { 13102 if (var->getType().isDestructedType()) { 13103 // GNU C++98 edits for __thread, [basic.start.term]p3: 13104 // The type of an object with thread storage duration shall not 13105 // have a non-trivial destructor. 13106 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13107 if (getLangOpts().CPlusPlus11) 13108 Diag(var->getLocation(), diag::note_use_thread_local); 13109 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13110 if (!checkConstInit()) { 13111 // GNU C++98 edits for __thread, [basic.start.init]p4: 13112 // An object of thread storage duration shall not require dynamic 13113 // initialization. 13114 // FIXME: Need strict checking here. 13115 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13116 << CacheCulprit->getSourceRange(); 13117 if (getLangOpts().CPlusPlus11) 13118 Diag(var->getLocation(), diag::note_use_thread_local); 13119 } 13120 } 13121 } 13122 13123 13124 if (!var->getType()->isStructureType() && var->hasInit() && 13125 isa<InitListExpr>(var->getInit())) { 13126 const auto *ILE = cast<InitListExpr>(var->getInit()); 13127 unsigned NumInits = ILE->getNumInits(); 13128 if (NumInits > 2) 13129 for (unsigned I = 0; I < NumInits; ++I) { 13130 const auto *Init = ILE->getInit(I); 13131 if (!Init) 13132 break; 13133 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13134 if (!SL) 13135 break; 13136 13137 unsigned NumConcat = SL->getNumConcatenated(); 13138 // Diagnose missing comma in string array initialization. 13139 // Do not warn when all the elements in the initializer are concatenated 13140 // together. Do not warn for macros too. 13141 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13142 bool OnlyOneMissingComma = true; 13143 for (unsigned J = I + 1; J < NumInits; ++J) { 13144 const auto *Init = ILE->getInit(J); 13145 if (!Init) 13146 break; 13147 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13148 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13149 OnlyOneMissingComma = false; 13150 break; 13151 } 13152 } 13153 13154 if (OnlyOneMissingComma) { 13155 SmallVector<FixItHint, 1> Hints; 13156 for (unsigned i = 0; i < NumConcat - 1; ++i) 13157 Hints.push_back(FixItHint::CreateInsertion( 13158 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13159 13160 Diag(SL->getStrTokenLoc(1), 13161 diag::warn_concatenated_literal_array_init) 13162 << Hints; 13163 Diag(SL->getBeginLoc(), 13164 diag::note_concatenated_string_literal_silence); 13165 } 13166 // In any case, stop now. 13167 break; 13168 } 13169 } 13170 } 13171 13172 13173 QualType type = var->getType(); 13174 13175 if (var->hasAttr<BlocksAttr>()) 13176 getCurFunction()->addByrefBlockVar(var); 13177 13178 Expr *Init = var->getInit(); 13179 bool GlobalStorage = var->hasGlobalStorage(); 13180 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13181 QualType baseType = Context.getBaseElementType(type); 13182 bool HasConstInit = true; 13183 13184 // Check whether the initializer is sufficiently constant. 13185 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13186 !Init->isValueDependent() && 13187 (GlobalStorage || var->isConstexpr() || 13188 var->mightBeUsableInConstantExpressions(Context))) { 13189 // If this variable might have a constant initializer or might be usable in 13190 // constant expressions, check whether or not it actually is now. We can't 13191 // do this lazily, because the result might depend on things that change 13192 // later, such as which constexpr functions happen to be defined. 13193 SmallVector<PartialDiagnosticAt, 8> Notes; 13194 if (!getLangOpts().CPlusPlus11) { 13195 // Prior to C++11, in contexts where a constant initializer is required, 13196 // the set of valid constant initializers is described by syntactic rules 13197 // in [expr.const]p2-6. 13198 // FIXME: Stricter checking for these rules would be useful for constinit / 13199 // -Wglobal-constructors. 13200 HasConstInit = checkConstInit(); 13201 13202 // Compute and cache the constant value, and remember that we have a 13203 // constant initializer. 13204 if (HasConstInit) { 13205 (void)var->checkForConstantInitialization(Notes); 13206 Notes.clear(); 13207 } else if (CacheCulprit) { 13208 Notes.emplace_back(CacheCulprit->getExprLoc(), 13209 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13210 Notes.back().second << CacheCulprit->getSourceRange(); 13211 } 13212 } else { 13213 // Evaluate the initializer to see if it's a constant initializer. 13214 HasConstInit = var->checkForConstantInitialization(Notes); 13215 } 13216 13217 if (HasConstInit) { 13218 // FIXME: Consider replacing the initializer with a ConstantExpr. 13219 } else if (var->isConstexpr()) { 13220 SourceLocation DiagLoc = var->getLocation(); 13221 // If the note doesn't add any useful information other than a source 13222 // location, fold it into the primary diagnostic. 13223 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13224 diag::note_invalid_subexpr_in_const_expr) { 13225 DiagLoc = Notes[0].first; 13226 Notes.clear(); 13227 } 13228 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13229 << var << Init->getSourceRange(); 13230 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13231 Diag(Notes[I].first, Notes[I].second); 13232 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13233 auto *Attr = var->getAttr<ConstInitAttr>(); 13234 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13235 << Init->getSourceRange(); 13236 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13237 << Attr->getRange() << Attr->isConstinit(); 13238 for (auto &it : Notes) 13239 Diag(it.first, it.second); 13240 } else if (IsGlobal && 13241 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13242 var->getLocation())) { 13243 // Warn about globals which don't have a constant initializer. Don't 13244 // warn about globals with a non-trivial destructor because we already 13245 // warned about them. 13246 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13247 if (!(RD && !RD->hasTrivialDestructor())) { 13248 // checkConstInit() here permits trivial default initialization even in 13249 // C++11 onwards, where such an initializer is not a constant initializer 13250 // but nonetheless doesn't require a global constructor. 13251 if (!checkConstInit()) 13252 Diag(var->getLocation(), diag::warn_global_constructor) 13253 << Init->getSourceRange(); 13254 } 13255 } 13256 } 13257 13258 // Apply section attributes and pragmas to global variables. 13259 if (GlobalStorage && var->isThisDeclarationADefinition() && 13260 !inTemplateInstantiation()) { 13261 PragmaStack<StringLiteral *> *Stack = nullptr; 13262 int SectionFlags = ASTContext::PSF_Read; 13263 if (var->getType().isConstQualified()) { 13264 if (HasConstInit) 13265 Stack = &ConstSegStack; 13266 else { 13267 Stack = &BSSSegStack; 13268 SectionFlags |= ASTContext::PSF_Write; 13269 } 13270 } else if (var->hasInit() && HasConstInit) { 13271 Stack = &DataSegStack; 13272 SectionFlags |= ASTContext::PSF_Write; 13273 } else { 13274 Stack = &BSSSegStack; 13275 SectionFlags |= ASTContext::PSF_Write; 13276 } 13277 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13278 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13279 SectionFlags |= ASTContext::PSF_Implicit; 13280 UnifySection(SA->getName(), SectionFlags, var); 13281 } else if (Stack->CurrentValue) { 13282 SectionFlags |= ASTContext::PSF_Implicit; 13283 auto SectionName = Stack->CurrentValue->getString(); 13284 var->addAttr(SectionAttr::CreateImplicit( 13285 Context, SectionName, Stack->CurrentPragmaLocation, 13286 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13287 if (UnifySection(SectionName, SectionFlags, var)) 13288 var->dropAttr<SectionAttr>(); 13289 } 13290 13291 // Apply the init_seg attribute if this has an initializer. If the 13292 // initializer turns out to not be dynamic, we'll end up ignoring this 13293 // attribute. 13294 if (CurInitSeg && var->getInit()) 13295 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13296 CurInitSegLoc, 13297 AttributeCommonInfo::AS_Pragma)); 13298 } 13299 13300 // All the following checks are C++ only. 13301 if (!getLangOpts().CPlusPlus) { 13302 // If this variable must be emitted, add it as an initializer for the 13303 // current module. 13304 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13305 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13306 return; 13307 } 13308 13309 // Require the destructor. 13310 if (!type->isDependentType()) 13311 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13312 FinalizeVarWithDestructor(var, recordType); 13313 13314 // If this variable must be emitted, add it as an initializer for the current 13315 // module. 13316 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13317 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13318 13319 // Build the bindings if this is a structured binding declaration. 13320 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13321 CheckCompleteDecompositionDeclaration(DD); 13322 } 13323 13324 /// Check if VD needs to be dllexport/dllimport due to being in a 13325 /// dllexport/import function. 13326 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13327 assert(VD->isStaticLocal()); 13328 13329 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13330 13331 // Find outermost function when VD is in lambda function. 13332 while (FD && !getDLLAttr(FD) && 13333 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13334 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13335 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13336 } 13337 13338 if (!FD) 13339 return; 13340 13341 // Static locals inherit dll attributes from their function. 13342 if (Attr *A = getDLLAttr(FD)) { 13343 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13344 NewAttr->setInherited(true); 13345 VD->addAttr(NewAttr); 13346 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13347 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13348 NewAttr->setInherited(true); 13349 VD->addAttr(NewAttr); 13350 13351 // Export this function to enforce exporting this static variable even 13352 // if it is not used in this compilation unit. 13353 if (!FD->hasAttr<DLLExportAttr>()) 13354 FD->addAttr(NewAttr); 13355 13356 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13357 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13358 NewAttr->setInherited(true); 13359 VD->addAttr(NewAttr); 13360 } 13361 } 13362 13363 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13364 /// any semantic actions necessary after any initializer has been attached. 13365 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13366 // Note that we are no longer parsing the initializer for this declaration. 13367 ParsingInitForAutoVars.erase(ThisDecl); 13368 13369 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13370 if (!VD) 13371 return; 13372 13373 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13374 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13375 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13376 if (PragmaClangBSSSection.Valid) 13377 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13378 Context, PragmaClangBSSSection.SectionName, 13379 PragmaClangBSSSection.PragmaLocation, 13380 AttributeCommonInfo::AS_Pragma)); 13381 if (PragmaClangDataSection.Valid) 13382 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13383 Context, PragmaClangDataSection.SectionName, 13384 PragmaClangDataSection.PragmaLocation, 13385 AttributeCommonInfo::AS_Pragma)); 13386 if (PragmaClangRodataSection.Valid) 13387 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13388 Context, PragmaClangRodataSection.SectionName, 13389 PragmaClangRodataSection.PragmaLocation, 13390 AttributeCommonInfo::AS_Pragma)); 13391 if (PragmaClangRelroSection.Valid) 13392 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13393 Context, PragmaClangRelroSection.SectionName, 13394 PragmaClangRelroSection.PragmaLocation, 13395 AttributeCommonInfo::AS_Pragma)); 13396 } 13397 13398 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13399 for (auto *BD : DD->bindings()) { 13400 FinalizeDeclaration(BD); 13401 } 13402 } 13403 13404 checkAttributesAfterMerging(*this, *VD); 13405 13406 // Perform TLS alignment check here after attributes attached to the variable 13407 // which may affect the alignment have been processed. Only perform the check 13408 // if the target has a maximum TLS alignment (zero means no constraints). 13409 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13410 // Protect the check so that it's not performed on dependent types and 13411 // dependent alignments (we can't determine the alignment in that case). 13412 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13413 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13414 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13415 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13416 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13417 << (unsigned)MaxAlignChars.getQuantity(); 13418 } 13419 } 13420 } 13421 13422 if (VD->isStaticLocal()) 13423 CheckStaticLocalForDllExport(VD); 13424 13425 // Perform check for initializers of device-side global variables. 13426 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13427 // 7.5). We must also apply the same checks to all __shared__ 13428 // variables whether they are local or not. CUDA also allows 13429 // constant initializers for __constant__ and __device__ variables. 13430 if (getLangOpts().CUDA) 13431 checkAllowedCUDAInitializer(VD); 13432 13433 // Grab the dllimport or dllexport attribute off of the VarDecl. 13434 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13435 13436 // Imported static data members cannot be defined out-of-line. 13437 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13438 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13439 VD->isThisDeclarationADefinition()) { 13440 // We allow definitions of dllimport class template static data members 13441 // with a warning. 13442 CXXRecordDecl *Context = 13443 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13444 bool IsClassTemplateMember = 13445 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13446 Context->getDescribedClassTemplate(); 13447 13448 Diag(VD->getLocation(), 13449 IsClassTemplateMember 13450 ? diag::warn_attribute_dllimport_static_field_definition 13451 : diag::err_attribute_dllimport_static_field_definition); 13452 Diag(IA->getLocation(), diag::note_attribute); 13453 if (!IsClassTemplateMember) 13454 VD->setInvalidDecl(); 13455 } 13456 } 13457 13458 // dllimport/dllexport variables cannot be thread local, their TLS index 13459 // isn't exported with the variable. 13460 if (DLLAttr && VD->getTLSKind()) { 13461 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13462 if (F && getDLLAttr(F)) { 13463 assert(VD->isStaticLocal()); 13464 // But if this is a static local in a dlimport/dllexport function, the 13465 // function will never be inlined, which means the var would never be 13466 // imported, so having it marked import/export is safe. 13467 } else { 13468 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13469 << DLLAttr; 13470 VD->setInvalidDecl(); 13471 } 13472 } 13473 13474 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13475 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13476 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13477 << Attr; 13478 VD->dropAttr<UsedAttr>(); 13479 } 13480 } 13481 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13482 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13483 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13484 << Attr; 13485 VD->dropAttr<RetainAttr>(); 13486 } 13487 } 13488 13489 const DeclContext *DC = VD->getDeclContext(); 13490 // If there's a #pragma GCC visibility in scope, and this isn't a class 13491 // member, set the visibility of this variable. 13492 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13493 AddPushedVisibilityAttribute(VD); 13494 13495 // FIXME: Warn on unused var template partial specializations. 13496 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13497 MarkUnusedFileScopedDecl(VD); 13498 13499 // Now we have parsed the initializer and can update the table of magic 13500 // tag values. 13501 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13502 !VD->getType()->isIntegralOrEnumerationType()) 13503 return; 13504 13505 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13506 const Expr *MagicValueExpr = VD->getInit(); 13507 if (!MagicValueExpr) { 13508 continue; 13509 } 13510 Optional<llvm::APSInt> MagicValueInt; 13511 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13512 Diag(I->getRange().getBegin(), 13513 diag::err_type_tag_for_datatype_not_ice) 13514 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13515 continue; 13516 } 13517 if (MagicValueInt->getActiveBits() > 64) { 13518 Diag(I->getRange().getBegin(), 13519 diag::err_type_tag_for_datatype_too_large) 13520 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13521 continue; 13522 } 13523 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13524 RegisterTypeTagForDatatype(I->getArgumentKind(), 13525 MagicValue, 13526 I->getMatchingCType(), 13527 I->getLayoutCompatible(), 13528 I->getMustBeNull()); 13529 } 13530 } 13531 13532 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13533 auto *VD = dyn_cast<VarDecl>(DD); 13534 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13535 } 13536 13537 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13538 ArrayRef<Decl *> Group) { 13539 SmallVector<Decl*, 8> Decls; 13540 13541 if (DS.isTypeSpecOwned()) 13542 Decls.push_back(DS.getRepAsDecl()); 13543 13544 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13545 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13546 bool DiagnosedMultipleDecomps = false; 13547 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13548 bool DiagnosedNonDeducedAuto = false; 13549 13550 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13551 if (Decl *D = Group[i]) { 13552 // For declarators, there are some additional syntactic-ish checks we need 13553 // to perform. 13554 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13555 if (!FirstDeclaratorInGroup) 13556 FirstDeclaratorInGroup = DD; 13557 if (!FirstDecompDeclaratorInGroup) 13558 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13559 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13560 !hasDeducedAuto(DD)) 13561 FirstNonDeducedAutoInGroup = DD; 13562 13563 if (FirstDeclaratorInGroup != DD) { 13564 // A decomposition declaration cannot be combined with any other 13565 // declaration in the same group. 13566 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13567 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13568 diag::err_decomp_decl_not_alone) 13569 << FirstDeclaratorInGroup->getSourceRange() 13570 << DD->getSourceRange(); 13571 DiagnosedMultipleDecomps = true; 13572 } 13573 13574 // A declarator that uses 'auto' in any way other than to declare a 13575 // variable with a deduced type cannot be combined with any other 13576 // declarator in the same group. 13577 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13578 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13579 diag::err_auto_non_deduced_not_alone) 13580 << FirstNonDeducedAutoInGroup->getType() 13581 ->hasAutoForTrailingReturnType() 13582 << FirstDeclaratorInGroup->getSourceRange() 13583 << DD->getSourceRange(); 13584 DiagnosedNonDeducedAuto = true; 13585 } 13586 } 13587 } 13588 13589 Decls.push_back(D); 13590 } 13591 } 13592 13593 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13594 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13595 handleTagNumbering(Tag, S); 13596 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13597 getLangOpts().CPlusPlus) 13598 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13599 } 13600 } 13601 13602 return BuildDeclaratorGroup(Decls); 13603 } 13604 13605 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13606 /// group, performing any necessary semantic checking. 13607 Sema::DeclGroupPtrTy 13608 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13609 // C++14 [dcl.spec.auto]p7: (DR1347) 13610 // If the type that replaces the placeholder type is not the same in each 13611 // deduction, the program is ill-formed. 13612 if (Group.size() > 1) { 13613 QualType Deduced; 13614 VarDecl *DeducedDecl = nullptr; 13615 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13616 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13617 if (!D || D->isInvalidDecl()) 13618 break; 13619 DeducedType *DT = D->getType()->getContainedDeducedType(); 13620 if (!DT || DT->getDeducedType().isNull()) 13621 continue; 13622 if (Deduced.isNull()) { 13623 Deduced = DT->getDeducedType(); 13624 DeducedDecl = D; 13625 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13626 auto *AT = dyn_cast<AutoType>(DT); 13627 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13628 diag::err_auto_different_deductions) 13629 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13630 << DeducedDecl->getDeclName() << DT->getDeducedType() 13631 << D->getDeclName(); 13632 if (DeducedDecl->hasInit()) 13633 Dia << DeducedDecl->getInit()->getSourceRange(); 13634 if (D->getInit()) 13635 Dia << D->getInit()->getSourceRange(); 13636 D->setInvalidDecl(); 13637 break; 13638 } 13639 } 13640 } 13641 13642 ActOnDocumentableDecls(Group); 13643 13644 return DeclGroupPtrTy::make( 13645 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13646 } 13647 13648 void Sema::ActOnDocumentableDecl(Decl *D) { 13649 ActOnDocumentableDecls(D); 13650 } 13651 13652 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13653 // Don't parse the comment if Doxygen diagnostics are ignored. 13654 if (Group.empty() || !Group[0]) 13655 return; 13656 13657 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13658 Group[0]->getLocation()) && 13659 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13660 Group[0]->getLocation())) 13661 return; 13662 13663 if (Group.size() >= 2) { 13664 // This is a decl group. Normally it will contain only declarations 13665 // produced from declarator list. But in case we have any definitions or 13666 // additional declaration references: 13667 // 'typedef struct S {} S;' 13668 // 'typedef struct S *S;' 13669 // 'struct S *pS;' 13670 // FinalizeDeclaratorGroup adds these as separate declarations. 13671 Decl *MaybeTagDecl = Group[0]; 13672 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13673 Group = Group.slice(1); 13674 } 13675 } 13676 13677 // FIMXE: We assume every Decl in the group is in the same file. 13678 // This is false when preprocessor constructs the group from decls in 13679 // different files (e. g. macros or #include). 13680 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13681 } 13682 13683 /// Common checks for a parameter-declaration that should apply to both function 13684 /// parameters and non-type template parameters. 13685 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13686 // Check that there are no default arguments inside the type of this 13687 // parameter. 13688 if (getLangOpts().CPlusPlus) 13689 CheckExtraCXXDefaultArguments(D); 13690 13691 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13692 if (D.getCXXScopeSpec().isSet()) { 13693 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13694 << D.getCXXScopeSpec().getRange(); 13695 } 13696 13697 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13698 // simple identifier except [...irrelevant cases...]. 13699 switch (D.getName().getKind()) { 13700 case UnqualifiedIdKind::IK_Identifier: 13701 break; 13702 13703 case UnqualifiedIdKind::IK_OperatorFunctionId: 13704 case UnqualifiedIdKind::IK_ConversionFunctionId: 13705 case UnqualifiedIdKind::IK_LiteralOperatorId: 13706 case UnqualifiedIdKind::IK_ConstructorName: 13707 case UnqualifiedIdKind::IK_DestructorName: 13708 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13709 case UnqualifiedIdKind::IK_DeductionGuideName: 13710 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13711 << GetNameForDeclarator(D).getName(); 13712 break; 13713 13714 case UnqualifiedIdKind::IK_TemplateId: 13715 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13716 // GetNameForDeclarator would not produce a useful name in this case. 13717 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13718 break; 13719 } 13720 } 13721 13722 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13723 /// to introduce parameters into function prototype scope. 13724 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13725 const DeclSpec &DS = D.getDeclSpec(); 13726 13727 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13728 13729 // C++03 [dcl.stc]p2 also permits 'auto'. 13730 StorageClass SC = SC_None; 13731 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13732 SC = SC_Register; 13733 // In C++11, the 'register' storage class specifier is deprecated. 13734 // In C++17, it is not allowed, but we tolerate it as an extension. 13735 if (getLangOpts().CPlusPlus11) { 13736 Diag(DS.getStorageClassSpecLoc(), 13737 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13738 : diag::warn_deprecated_register) 13739 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13740 } 13741 } else if (getLangOpts().CPlusPlus && 13742 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13743 SC = SC_Auto; 13744 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13745 Diag(DS.getStorageClassSpecLoc(), 13746 diag::err_invalid_storage_class_in_func_decl); 13747 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13748 } 13749 13750 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13751 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13752 << DeclSpec::getSpecifierName(TSCS); 13753 if (DS.isInlineSpecified()) 13754 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13755 << getLangOpts().CPlusPlus17; 13756 if (DS.hasConstexprSpecifier()) 13757 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13758 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13759 13760 DiagnoseFunctionSpecifiers(DS); 13761 13762 CheckFunctionOrTemplateParamDeclarator(S, D); 13763 13764 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13765 QualType parmDeclType = TInfo->getType(); 13766 13767 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13768 IdentifierInfo *II = D.getIdentifier(); 13769 if (II) { 13770 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13771 ForVisibleRedeclaration); 13772 LookupName(R, S); 13773 if (R.isSingleResult()) { 13774 NamedDecl *PrevDecl = R.getFoundDecl(); 13775 if (PrevDecl->isTemplateParameter()) { 13776 // Maybe we will complain about the shadowed template parameter. 13777 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13778 // Just pretend that we didn't see the previous declaration. 13779 PrevDecl = nullptr; 13780 } else if (S->isDeclScope(PrevDecl)) { 13781 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13782 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13783 13784 // Recover by removing the name 13785 II = nullptr; 13786 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13787 D.setInvalidType(true); 13788 } 13789 } 13790 } 13791 13792 // Temporarily put parameter variables in the translation unit, not 13793 // the enclosing context. This prevents them from accidentally 13794 // looking like class members in C++. 13795 ParmVarDecl *New = 13796 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13797 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13798 13799 if (D.isInvalidType()) 13800 New->setInvalidDecl(); 13801 13802 assert(S->isFunctionPrototypeScope()); 13803 assert(S->getFunctionPrototypeDepth() >= 1); 13804 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13805 S->getNextFunctionPrototypeIndex()); 13806 13807 // Add the parameter declaration into this scope. 13808 S->AddDecl(New); 13809 if (II) 13810 IdResolver.AddDecl(New); 13811 13812 ProcessDeclAttributes(S, New, D); 13813 13814 if (D.getDeclSpec().isModulePrivateSpecified()) 13815 Diag(New->getLocation(), diag::err_module_private_local) 13816 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13817 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13818 13819 if (New->hasAttr<BlocksAttr>()) { 13820 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13821 } 13822 13823 if (getLangOpts().OpenCL) 13824 deduceOpenCLAddressSpace(New); 13825 13826 return New; 13827 } 13828 13829 /// Synthesizes a variable for a parameter arising from a 13830 /// typedef. 13831 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13832 SourceLocation Loc, 13833 QualType T) { 13834 /* FIXME: setting StartLoc == Loc. 13835 Would it be worth to modify callers so as to provide proper source 13836 location for the unnamed parameters, embedding the parameter's type? */ 13837 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13838 T, Context.getTrivialTypeSourceInfo(T, Loc), 13839 SC_None, nullptr); 13840 Param->setImplicit(); 13841 return Param; 13842 } 13843 13844 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13845 // Don't diagnose unused-parameter errors in template instantiations; we 13846 // will already have done so in the template itself. 13847 if (inTemplateInstantiation()) 13848 return; 13849 13850 for (const ParmVarDecl *Parameter : Parameters) { 13851 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13852 !Parameter->hasAttr<UnusedAttr>()) { 13853 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13854 << Parameter->getDeclName(); 13855 } 13856 } 13857 } 13858 13859 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13860 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13861 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13862 return; 13863 13864 // Warn if the return value is pass-by-value and larger than the specified 13865 // threshold. 13866 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13867 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13868 if (Size > LangOpts.NumLargeByValueCopy) 13869 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13870 } 13871 13872 // Warn if any parameter is pass-by-value and larger than the specified 13873 // threshold. 13874 for (const ParmVarDecl *Parameter : Parameters) { 13875 QualType T = Parameter->getType(); 13876 if (T->isDependentType() || !T.isPODType(Context)) 13877 continue; 13878 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13879 if (Size > LangOpts.NumLargeByValueCopy) 13880 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13881 << Parameter << Size; 13882 } 13883 } 13884 13885 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13886 SourceLocation NameLoc, IdentifierInfo *Name, 13887 QualType T, TypeSourceInfo *TSInfo, 13888 StorageClass SC) { 13889 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13890 if (getLangOpts().ObjCAutoRefCount && 13891 T.getObjCLifetime() == Qualifiers::OCL_None && 13892 T->isObjCLifetimeType()) { 13893 13894 Qualifiers::ObjCLifetime lifetime; 13895 13896 // Special cases for arrays: 13897 // - if it's const, use __unsafe_unretained 13898 // - otherwise, it's an error 13899 if (T->isArrayType()) { 13900 if (!T.isConstQualified()) { 13901 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13902 DelayedDiagnostics.add( 13903 sema::DelayedDiagnostic::makeForbiddenType( 13904 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13905 else 13906 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13907 << TSInfo->getTypeLoc().getSourceRange(); 13908 } 13909 lifetime = Qualifiers::OCL_ExplicitNone; 13910 } else { 13911 lifetime = T->getObjCARCImplicitLifetime(); 13912 } 13913 T = Context.getLifetimeQualifiedType(T, lifetime); 13914 } 13915 13916 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13917 Context.getAdjustedParameterType(T), 13918 TSInfo, SC, nullptr); 13919 13920 // Make a note if we created a new pack in the scope of a lambda, so that 13921 // we know that references to that pack must also be expanded within the 13922 // lambda scope. 13923 if (New->isParameterPack()) 13924 if (auto *LSI = getEnclosingLambda()) 13925 LSI->LocalPacks.push_back(New); 13926 13927 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13928 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13929 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13930 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13931 13932 // Parameters can not be abstract class types. 13933 // For record types, this is done by the AbstractClassUsageDiagnoser once 13934 // the class has been completely parsed. 13935 if (!CurContext->isRecord() && 13936 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13937 AbstractParamType)) 13938 New->setInvalidDecl(); 13939 13940 // Parameter declarators cannot be interface types. All ObjC objects are 13941 // passed by reference. 13942 if (T->isObjCObjectType()) { 13943 SourceLocation TypeEndLoc = 13944 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13945 Diag(NameLoc, 13946 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13947 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13948 T = Context.getObjCObjectPointerType(T); 13949 New->setType(T); 13950 } 13951 13952 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13953 // duration shall not be qualified by an address-space qualifier." 13954 // Since all parameters have automatic store duration, they can not have 13955 // an address space. 13956 if (T.getAddressSpace() != LangAS::Default && 13957 // OpenCL allows function arguments declared to be an array of a type 13958 // to be qualified with an address space. 13959 !(getLangOpts().OpenCL && 13960 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13961 Diag(NameLoc, diag::err_arg_with_address_space); 13962 New->setInvalidDecl(); 13963 } 13964 13965 // PPC MMA non-pointer types are not allowed as function argument types. 13966 if (Context.getTargetInfo().getTriple().isPPC64() && 13967 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13968 New->setInvalidDecl(); 13969 } 13970 13971 return New; 13972 } 13973 13974 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13975 SourceLocation LocAfterDecls) { 13976 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13977 13978 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13979 // for a K&R function. 13980 if (!FTI.hasPrototype) { 13981 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13982 --i; 13983 if (FTI.Params[i].Param == nullptr) { 13984 SmallString<256> Code; 13985 llvm::raw_svector_ostream(Code) 13986 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13987 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13988 << FTI.Params[i].Ident 13989 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13990 13991 // Implicitly declare the argument as type 'int' for lack of a better 13992 // type. 13993 AttributeFactory attrs; 13994 DeclSpec DS(attrs); 13995 const char* PrevSpec; // unused 13996 unsigned DiagID; // unused 13997 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13998 DiagID, Context.getPrintingPolicy()); 13999 // Use the identifier location for the type source range. 14000 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14001 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14002 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14003 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14004 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14005 } 14006 } 14007 } 14008 } 14009 14010 Decl * 14011 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14012 MultiTemplateParamsArg TemplateParameterLists, 14013 SkipBodyInfo *SkipBody) { 14014 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14015 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14016 Scope *ParentScope = FnBodyScope->getParent(); 14017 14018 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14019 // we define a non-templated function definition, we will create a declaration 14020 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14021 // The base function declaration will have the equivalent of an `omp declare 14022 // variant` annotation which specifies the mangled definition as a 14023 // specialization function under the OpenMP context defined as part of the 14024 // `omp begin declare variant`. 14025 SmallVector<FunctionDecl *, 4> Bases; 14026 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14027 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14028 ParentScope, D, TemplateParameterLists, Bases); 14029 14030 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14031 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14032 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14033 14034 if (!Bases.empty()) 14035 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14036 14037 return Dcl; 14038 } 14039 14040 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14041 Consumer.HandleInlineFunctionDefinition(D); 14042 } 14043 14044 static bool 14045 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14046 const FunctionDecl *&PossiblePrototype) { 14047 // Don't warn about invalid declarations. 14048 if (FD->isInvalidDecl()) 14049 return false; 14050 14051 // Or declarations that aren't global. 14052 if (!FD->isGlobal()) 14053 return false; 14054 14055 // Don't warn about C++ member functions. 14056 if (isa<CXXMethodDecl>(FD)) 14057 return false; 14058 14059 // Don't warn about 'main'. 14060 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14061 if (IdentifierInfo *II = FD->getIdentifier()) 14062 if (II->isStr("main") || II->isStr("efi_main")) 14063 return false; 14064 14065 // Don't warn about inline functions. 14066 if (FD->isInlined()) 14067 return false; 14068 14069 // Don't warn about function templates. 14070 if (FD->getDescribedFunctionTemplate()) 14071 return false; 14072 14073 // Don't warn about function template specializations. 14074 if (FD->isFunctionTemplateSpecialization()) 14075 return false; 14076 14077 // Don't warn for OpenCL kernels. 14078 if (FD->hasAttr<OpenCLKernelAttr>()) 14079 return false; 14080 14081 // Don't warn on explicitly deleted functions. 14082 if (FD->isDeleted()) 14083 return false; 14084 14085 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14086 Prev; Prev = Prev->getPreviousDecl()) { 14087 // Ignore any declarations that occur in function or method 14088 // scope, because they aren't visible from the header. 14089 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14090 continue; 14091 14092 PossiblePrototype = Prev; 14093 return Prev->getType()->isFunctionNoProtoType(); 14094 } 14095 14096 return true; 14097 } 14098 14099 void 14100 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14101 const FunctionDecl *EffectiveDefinition, 14102 SkipBodyInfo *SkipBody) { 14103 const FunctionDecl *Definition = EffectiveDefinition; 14104 if (!Definition && 14105 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14106 return; 14107 14108 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14109 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14110 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14111 // A merged copy of the same function, instantiated as a member of 14112 // the same class, is OK. 14113 if (declaresSameEntity(OrigFD, OrigDef) && 14114 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14115 cast<Decl>(FD->getLexicalDeclContext()))) 14116 return; 14117 } 14118 } 14119 } 14120 14121 if (canRedefineFunction(Definition, getLangOpts())) 14122 return; 14123 14124 // Don't emit an error when this is redefinition of a typo-corrected 14125 // definition. 14126 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14127 return; 14128 14129 // If we don't have a visible definition of the function, and it's inline or 14130 // a template, skip the new definition. 14131 if (SkipBody && !hasVisibleDefinition(Definition) && 14132 (Definition->getFormalLinkage() == InternalLinkage || 14133 Definition->isInlined() || 14134 Definition->getDescribedFunctionTemplate() || 14135 Definition->getNumTemplateParameterLists())) { 14136 SkipBody->ShouldSkip = true; 14137 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14138 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14139 makeMergedDefinitionVisible(TD); 14140 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14141 return; 14142 } 14143 14144 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14145 Definition->getStorageClass() == SC_Extern) 14146 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14147 << FD << getLangOpts().CPlusPlus; 14148 else 14149 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14150 14151 Diag(Definition->getLocation(), diag::note_previous_definition); 14152 FD->setInvalidDecl(); 14153 } 14154 14155 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14156 Sema &S) { 14157 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14158 14159 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14160 LSI->CallOperator = CallOperator; 14161 LSI->Lambda = LambdaClass; 14162 LSI->ReturnType = CallOperator->getReturnType(); 14163 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14164 14165 if (LCD == LCD_None) 14166 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14167 else if (LCD == LCD_ByCopy) 14168 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14169 else if (LCD == LCD_ByRef) 14170 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14171 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14172 14173 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14174 LSI->Mutable = !CallOperator->isConst(); 14175 14176 // Add the captures to the LSI so they can be noted as already 14177 // captured within tryCaptureVar. 14178 auto I = LambdaClass->field_begin(); 14179 for (const auto &C : LambdaClass->captures()) { 14180 if (C.capturesVariable()) { 14181 VarDecl *VD = C.getCapturedVar(); 14182 if (VD->isInitCapture()) 14183 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14184 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14185 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14186 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14187 /*EllipsisLoc*/C.isPackExpansion() 14188 ? C.getEllipsisLoc() : SourceLocation(), 14189 I->getType(), /*Invalid*/false); 14190 14191 } else if (C.capturesThis()) { 14192 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14193 C.getCaptureKind() == LCK_StarThis); 14194 } else { 14195 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14196 I->getType()); 14197 } 14198 ++I; 14199 } 14200 } 14201 14202 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14203 SkipBodyInfo *SkipBody) { 14204 if (!D) { 14205 // Parsing the function declaration failed in some way. Push on a fake scope 14206 // anyway so we can try to parse the function body. 14207 PushFunctionScope(); 14208 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14209 return D; 14210 } 14211 14212 FunctionDecl *FD = nullptr; 14213 14214 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14215 FD = FunTmpl->getTemplatedDecl(); 14216 else 14217 FD = cast<FunctionDecl>(D); 14218 14219 // Do not push if it is a lambda because one is already pushed when building 14220 // the lambda in ActOnStartOfLambdaDefinition(). 14221 if (!isLambdaCallOperator(FD)) 14222 PushExpressionEvaluationContext( 14223 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14224 : ExprEvalContexts.back().Context); 14225 14226 // Check for defining attributes before the check for redefinition. 14227 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14228 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14229 FD->dropAttr<AliasAttr>(); 14230 FD->setInvalidDecl(); 14231 } 14232 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14233 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14234 FD->dropAttr<IFuncAttr>(); 14235 FD->setInvalidDecl(); 14236 } 14237 14238 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14239 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14240 Ctor->isDefaultConstructor() && 14241 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14242 // If this is an MS ABI dllexport default constructor, instantiate any 14243 // default arguments. 14244 InstantiateDefaultCtorDefaultArgs(Ctor); 14245 } 14246 } 14247 14248 // See if this is a redefinition. If 'will have body' (or similar) is already 14249 // set, then these checks were already performed when it was set. 14250 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14251 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14252 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14253 14254 // If we're skipping the body, we're done. Don't enter the scope. 14255 if (SkipBody && SkipBody->ShouldSkip) 14256 return D; 14257 } 14258 14259 // Mark this function as "will have a body eventually". This lets users to 14260 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14261 // this function. 14262 FD->setWillHaveBody(); 14263 14264 // If we are instantiating a generic lambda call operator, push 14265 // a LambdaScopeInfo onto the function stack. But use the information 14266 // that's already been calculated (ActOnLambdaExpr) to prime the current 14267 // LambdaScopeInfo. 14268 // When the template operator is being specialized, the LambdaScopeInfo, 14269 // has to be properly restored so that tryCaptureVariable doesn't try 14270 // and capture any new variables. In addition when calculating potential 14271 // captures during transformation of nested lambdas, it is necessary to 14272 // have the LSI properly restored. 14273 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14274 assert(inTemplateInstantiation() && 14275 "There should be an active template instantiation on the stack " 14276 "when instantiating a generic lambda!"); 14277 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14278 } else { 14279 // Enter a new function scope 14280 PushFunctionScope(); 14281 } 14282 14283 // Builtin functions cannot be defined. 14284 if (unsigned BuiltinID = FD->getBuiltinID()) { 14285 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14286 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14287 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14288 FD->setInvalidDecl(); 14289 } 14290 } 14291 14292 // The return type of a function definition must be complete 14293 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14294 QualType ResultType = FD->getReturnType(); 14295 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14296 !FD->isInvalidDecl() && 14297 RequireCompleteType(FD->getLocation(), ResultType, 14298 diag::err_func_def_incomplete_result)) 14299 FD->setInvalidDecl(); 14300 14301 if (FnBodyScope) 14302 PushDeclContext(FnBodyScope, FD); 14303 14304 // Check the validity of our function parameters 14305 CheckParmsForFunctionDef(FD->parameters(), 14306 /*CheckParameterNames=*/true); 14307 14308 // Add non-parameter declarations already in the function to the current 14309 // scope. 14310 if (FnBodyScope) { 14311 for (Decl *NPD : FD->decls()) { 14312 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14313 if (!NonParmDecl) 14314 continue; 14315 assert(!isa<ParmVarDecl>(NonParmDecl) && 14316 "parameters should not be in newly created FD yet"); 14317 14318 // If the decl has a name, make it accessible in the current scope. 14319 if (NonParmDecl->getDeclName()) 14320 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14321 14322 // Similarly, dive into enums and fish their constants out, making them 14323 // accessible in this scope. 14324 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14325 for (auto *EI : ED->enumerators()) 14326 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14327 } 14328 } 14329 } 14330 14331 // Introduce our parameters into the function scope 14332 for (auto Param : FD->parameters()) { 14333 Param->setOwningFunction(FD); 14334 14335 // If this has an identifier, add it to the scope stack. 14336 if (Param->getIdentifier() && FnBodyScope) { 14337 CheckShadow(FnBodyScope, Param); 14338 14339 PushOnScopeChains(Param, FnBodyScope); 14340 } 14341 } 14342 14343 // Ensure that the function's exception specification is instantiated. 14344 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14345 ResolveExceptionSpec(D->getLocation(), FPT); 14346 14347 // dllimport cannot be applied to non-inline function definitions. 14348 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14349 !FD->isTemplateInstantiation()) { 14350 assert(!FD->hasAttr<DLLExportAttr>()); 14351 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14352 FD->setInvalidDecl(); 14353 return D; 14354 } 14355 // We want to attach documentation to original Decl (which might be 14356 // a function template). 14357 ActOnDocumentableDecl(D); 14358 if (getCurLexicalContext()->isObjCContainer() && 14359 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14360 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14361 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14362 14363 return D; 14364 } 14365 14366 /// Given the set of return statements within a function body, 14367 /// compute the variables that are subject to the named return value 14368 /// optimization. 14369 /// 14370 /// Each of the variables that is subject to the named return value 14371 /// optimization will be marked as NRVO variables in the AST, and any 14372 /// return statement that has a marked NRVO variable as its NRVO candidate can 14373 /// use the named return value optimization. 14374 /// 14375 /// This function applies a very simplistic algorithm for NRVO: if every return 14376 /// statement in the scope of a variable has the same NRVO candidate, that 14377 /// candidate is an NRVO variable. 14378 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14379 ReturnStmt **Returns = Scope->Returns.data(); 14380 14381 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14382 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14383 if (!NRVOCandidate->isNRVOVariable()) 14384 Returns[I]->setNRVOCandidate(nullptr); 14385 } 14386 } 14387 } 14388 14389 bool Sema::canDelayFunctionBody(const Declarator &D) { 14390 // We can't delay parsing the body of a constexpr function template (yet). 14391 if (D.getDeclSpec().hasConstexprSpecifier()) 14392 return false; 14393 14394 // We can't delay parsing the body of a function template with a deduced 14395 // return type (yet). 14396 if (D.getDeclSpec().hasAutoTypeSpec()) { 14397 // If the placeholder introduces a non-deduced trailing return type, 14398 // we can still delay parsing it. 14399 if (D.getNumTypeObjects()) { 14400 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14401 if (Outer.Kind == DeclaratorChunk::Function && 14402 Outer.Fun.hasTrailingReturnType()) { 14403 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14404 return Ty.isNull() || !Ty->isUndeducedType(); 14405 } 14406 } 14407 return false; 14408 } 14409 14410 return true; 14411 } 14412 14413 bool Sema::canSkipFunctionBody(Decl *D) { 14414 // We cannot skip the body of a function (or function template) which is 14415 // constexpr, since we may need to evaluate its body in order to parse the 14416 // rest of the file. 14417 // We cannot skip the body of a function with an undeduced return type, 14418 // because any callers of that function need to know the type. 14419 if (const FunctionDecl *FD = D->getAsFunction()) { 14420 if (FD->isConstexpr()) 14421 return false; 14422 // We can't simply call Type::isUndeducedType here, because inside template 14423 // auto can be deduced to a dependent type, which is not considered 14424 // "undeduced". 14425 if (FD->getReturnType()->getContainedDeducedType()) 14426 return false; 14427 } 14428 return Consumer.shouldSkipFunctionBody(D); 14429 } 14430 14431 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14432 if (!Decl) 14433 return nullptr; 14434 if (FunctionDecl *FD = Decl->getAsFunction()) 14435 FD->setHasSkippedBody(); 14436 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14437 MD->setHasSkippedBody(); 14438 return Decl; 14439 } 14440 14441 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14442 return ActOnFinishFunctionBody(D, BodyArg, false); 14443 } 14444 14445 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14446 /// body. 14447 class ExitFunctionBodyRAII { 14448 public: 14449 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14450 ~ExitFunctionBodyRAII() { 14451 if (!IsLambda) 14452 S.PopExpressionEvaluationContext(); 14453 } 14454 14455 private: 14456 Sema &S; 14457 bool IsLambda = false; 14458 }; 14459 14460 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14461 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14462 14463 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14464 if (EscapeInfo.count(BD)) 14465 return EscapeInfo[BD]; 14466 14467 bool R = false; 14468 const BlockDecl *CurBD = BD; 14469 14470 do { 14471 R = !CurBD->doesNotEscape(); 14472 if (R) 14473 break; 14474 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14475 } while (CurBD); 14476 14477 return EscapeInfo[BD] = R; 14478 }; 14479 14480 // If the location where 'self' is implicitly retained is inside a escaping 14481 // block, emit a diagnostic. 14482 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14483 S.ImplicitlyRetainedSelfLocs) 14484 if (IsOrNestedInEscapingBlock(P.second)) 14485 S.Diag(P.first, diag::warn_implicitly_retains_self) 14486 << FixItHint::CreateInsertion(P.first, "self->"); 14487 } 14488 14489 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14490 bool IsInstantiation) { 14491 FunctionScopeInfo *FSI = getCurFunction(); 14492 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14493 14494 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14495 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14496 14497 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14498 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14499 14500 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14501 CheckCompletedCoroutineBody(FD, Body); 14502 14503 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14504 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14505 // meant to pop the context added in ActOnStartOfFunctionDef(). 14506 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14507 14508 if (FD) { 14509 FD->setBody(Body); 14510 FD->setWillHaveBody(false); 14511 14512 if (getLangOpts().CPlusPlus14) { 14513 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14514 FD->getReturnType()->isUndeducedType()) { 14515 // If the function has a deduced result type but contains no 'return' 14516 // statements, the result type as written must be exactly 'auto', and 14517 // the deduced result type is 'void'. 14518 if (!FD->getReturnType()->getAs<AutoType>()) { 14519 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14520 << FD->getReturnType(); 14521 FD->setInvalidDecl(); 14522 } else { 14523 // Substitute 'void' for the 'auto' in the type. 14524 TypeLoc ResultType = getReturnTypeLoc(FD); 14525 Context.adjustDeducedFunctionResultType( 14526 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14527 } 14528 } 14529 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14530 // In C++11, we don't use 'auto' deduction rules for lambda call 14531 // operators because we don't support return type deduction. 14532 auto *LSI = getCurLambda(); 14533 if (LSI->HasImplicitReturnType) { 14534 deduceClosureReturnType(*LSI); 14535 14536 // C++11 [expr.prim.lambda]p4: 14537 // [...] if there are no return statements in the compound-statement 14538 // [the deduced type is] the type void 14539 QualType RetType = 14540 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14541 14542 // Update the return type to the deduced type. 14543 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14544 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14545 Proto->getExtProtoInfo())); 14546 } 14547 } 14548 14549 // If the function implicitly returns zero (like 'main') or is naked, 14550 // don't complain about missing return statements. 14551 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14552 WP.disableCheckFallThrough(); 14553 14554 // MSVC permits the use of pure specifier (=0) on function definition, 14555 // defined at class scope, warn about this non-standard construct. 14556 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14557 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14558 14559 if (!FD->isInvalidDecl()) { 14560 // Don't diagnose unused parameters of defaulted or deleted functions. 14561 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14562 DiagnoseUnusedParameters(FD->parameters()); 14563 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14564 FD->getReturnType(), FD); 14565 14566 // If this is a structor, we need a vtable. 14567 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14568 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14569 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14570 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14571 14572 // Try to apply the named return value optimization. We have to check 14573 // if we can do this here because lambdas keep return statements around 14574 // to deduce an implicit return type. 14575 if (FD->getReturnType()->isRecordType() && 14576 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14577 computeNRVO(Body, FSI); 14578 } 14579 14580 // GNU warning -Wmissing-prototypes: 14581 // Warn if a global function is defined without a previous 14582 // prototype declaration. This warning is issued even if the 14583 // definition itself provides a prototype. The aim is to detect 14584 // global functions that fail to be declared in header files. 14585 const FunctionDecl *PossiblePrototype = nullptr; 14586 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14587 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14588 14589 if (PossiblePrototype) { 14590 // We found a declaration that is not a prototype, 14591 // but that could be a zero-parameter prototype 14592 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14593 TypeLoc TL = TI->getTypeLoc(); 14594 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14595 Diag(PossiblePrototype->getLocation(), 14596 diag::note_declaration_not_a_prototype) 14597 << (FD->getNumParams() != 0) 14598 << (FD->getNumParams() == 0 14599 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14600 : FixItHint{}); 14601 } 14602 } else { 14603 // Returns true if the token beginning at this Loc is `const`. 14604 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14605 const LangOptions &LangOpts) { 14606 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14607 if (LocInfo.first.isInvalid()) 14608 return false; 14609 14610 bool Invalid = false; 14611 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14612 if (Invalid) 14613 return false; 14614 14615 if (LocInfo.second > Buffer.size()) 14616 return false; 14617 14618 const char *LexStart = Buffer.data() + LocInfo.second; 14619 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14620 14621 return StartTok.consume_front("const") && 14622 (StartTok.empty() || isWhitespace(StartTok[0]) || 14623 StartTok.startswith("/*") || StartTok.startswith("//")); 14624 }; 14625 14626 auto findBeginLoc = [&]() { 14627 // If the return type has `const` qualifier, we want to insert 14628 // `static` before `const` (and not before the typename). 14629 if ((FD->getReturnType()->isAnyPointerType() && 14630 FD->getReturnType()->getPointeeType().isConstQualified()) || 14631 FD->getReturnType().isConstQualified()) { 14632 // But only do this if we can determine where the `const` is. 14633 14634 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14635 getLangOpts())) 14636 14637 return FD->getBeginLoc(); 14638 } 14639 return FD->getTypeSpecStartLoc(); 14640 }; 14641 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14642 << /* function */ 1 14643 << (FD->getStorageClass() == SC_None 14644 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14645 : FixItHint{}); 14646 } 14647 14648 // GNU warning -Wstrict-prototypes 14649 // Warn if K&R function is defined without a previous declaration. 14650 // This warning is issued only if the definition itself does not provide 14651 // a prototype. Only K&R definitions do not provide a prototype. 14652 if (!FD->hasWrittenPrototype()) { 14653 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14654 TypeLoc TL = TI->getTypeLoc(); 14655 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14656 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14657 } 14658 } 14659 14660 // Warn on CPUDispatch with an actual body. 14661 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14662 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14663 if (!CmpndBody->body_empty()) 14664 Diag(CmpndBody->body_front()->getBeginLoc(), 14665 diag::warn_dispatch_body_ignored); 14666 14667 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14668 const CXXMethodDecl *KeyFunction; 14669 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14670 MD->isVirtual() && 14671 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14672 MD == KeyFunction->getCanonicalDecl()) { 14673 // Update the key-function state if necessary for this ABI. 14674 if (FD->isInlined() && 14675 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14676 Context.setNonKeyFunction(MD); 14677 14678 // If the newly-chosen key function is already defined, then we 14679 // need to mark the vtable as used retroactively. 14680 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14681 const FunctionDecl *Definition; 14682 if (KeyFunction && KeyFunction->isDefined(Definition)) 14683 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14684 } else { 14685 // We just defined they key function; mark the vtable as used. 14686 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14687 } 14688 } 14689 } 14690 14691 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14692 "Function parsing confused"); 14693 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14694 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14695 MD->setBody(Body); 14696 if (!MD->isInvalidDecl()) { 14697 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14698 MD->getReturnType(), MD); 14699 14700 if (Body) 14701 computeNRVO(Body, FSI); 14702 } 14703 if (FSI->ObjCShouldCallSuper) { 14704 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14705 << MD->getSelector().getAsString(); 14706 FSI->ObjCShouldCallSuper = false; 14707 } 14708 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14709 const ObjCMethodDecl *InitMethod = nullptr; 14710 bool isDesignated = 14711 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14712 assert(isDesignated && InitMethod); 14713 (void)isDesignated; 14714 14715 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14716 auto IFace = MD->getClassInterface(); 14717 if (!IFace) 14718 return false; 14719 auto SuperD = IFace->getSuperClass(); 14720 if (!SuperD) 14721 return false; 14722 return SuperD->getIdentifier() == 14723 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14724 }; 14725 // Don't issue this warning for unavailable inits or direct subclasses 14726 // of NSObject. 14727 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14728 Diag(MD->getLocation(), 14729 diag::warn_objc_designated_init_missing_super_call); 14730 Diag(InitMethod->getLocation(), 14731 diag::note_objc_designated_init_marked_here); 14732 } 14733 FSI->ObjCWarnForNoDesignatedInitChain = false; 14734 } 14735 if (FSI->ObjCWarnForNoInitDelegation) { 14736 // Don't issue this warning for unavaialable inits. 14737 if (!MD->isUnavailable()) 14738 Diag(MD->getLocation(), 14739 diag::warn_objc_secondary_init_missing_init_call); 14740 FSI->ObjCWarnForNoInitDelegation = false; 14741 } 14742 14743 diagnoseImplicitlyRetainedSelf(*this); 14744 } else { 14745 // Parsing the function declaration failed in some way. Pop the fake scope 14746 // we pushed on. 14747 PopFunctionScopeInfo(ActivePolicy, dcl); 14748 return nullptr; 14749 } 14750 14751 if (Body && FSI->HasPotentialAvailabilityViolations) 14752 DiagnoseUnguardedAvailabilityViolations(dcl); 14753 14754 assert(!FSI->ObjCShouldCallSuper && 14755 "This should only be set for ObjC methods, which should have been " 14756 "handled in the block above."); 14757 14758 // Verify and clean out per-function state. 14759 if (Body && (!FD || !FD->isDefaulted())) { 14760 // C++ constructors that have function-try-blocks can't have return 14761 // statements in the handlers of that block. (C++ [except.handle]p14) 14762 // Verify this. 14763 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14764 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14765 14766 // Verify that gotos and switch cases don't jump into scopes illegally. 14767 if (FSI->NeedsScopeChecking() && 14768 !PP.isCodeCompletionEnabled()) 14769 DiagnoseInvalidJumps(Body); 14770 14771 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14772 if (!Destructor->getParent()->isDependentType()) 14773 CheckDestructor(Destructor); 14774 14775 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14776 Destructor->getParent()); 14777 } 14778 14779 // If any errors have occurred, clear out any temporaries that may have 14780 // been leftover. This ensures that these temporaries won't be picked up for 14781 // deletion in some later function. 14782 if (hasUncompilableErrorOccurred() || 14783 getDiagnostics().getSuppressAllDiagnostics()) { 14784 DiscardCleanupsInEvaluationContext(); 14785 } 14786 if (!hasUncompilableErrorOccurred() && 14787 !isa<FunctionTemplateDecl>(dcl)) { 14788 // Since the body is valid, issue any analysis-based warnings that are 14789 // enabled. 14790 ActivePolicy = &WP; 14791 } 14792 14793 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14794 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14795 FD->setInvalidDecl(); 14796 14797 if (FD && FD->hasAttr<NakedAttr>()) { 14798 for (const Stmt *S : Body->children()) { 14799 // Allow local register variables without initializer as they don't 14800 // require prologue. 14801 bool RegisterVariables = false; 14802 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14803 for (const auto *Decl : DS->decls()) { 14804 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14805 RegisterVariables = 14806 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14807 if (!RegisterVariables) 14808 break; 14809 } 14810 } 14811 } 14812 if (RegisterVariables) 14813 continue; 14814 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14815 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14816 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14817 FD->setInvalidDecl(); 14818 break; 14819 } 14820 } 14821 } 14822 14823 assert(ExprCleanupObjects.size() == 14824 ExprEvalContexts.back().NumCleanupObjects && 14825 "Leftover temporaries in function"); 14826 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14827 assert(MaybeODRUseExprs.empty() && 14828 "Leftover expressions for odr-use checking"); 14829 } 14830 14831 if (!IsInstantiation) 14832 PopDeclContext(); 14833 14834 PopFunctionScopeInfo(ActivePolicy, dcl); 14835 // If any errors have occurred, clear out any temporaries that may have 14836 // been leftover. This ensures that these temporaries won't be picked up for 14837 // deletion in some later function. 14838 if (hasUncompilableErrorOccurred()) { 14839 DiscardCleanupsInEvaluationContext(); 14840 } 14841 14842 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14843 auto ES = getEmissionStatus(FD); 14844 if (ES == Sema::FunctionEmissionStatus::Emitted || 14845 ES == Sema::FunctionEmissionStatus::Unknown) 14846 DeclsToCheckForDeferredDiags.insert(FD); 14847 } 14848 14849 return dcl; 14850 } 14851 14852 /// When we finish delayed parsing of an attribute, we must attach it to the 14853 /// relevant Decl. 14854 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14855 ParsedAttributes &Attrs) { 14856 // Always attach attributes to the underlying decl. 14857 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14858 D = TD->getTemplatedDecl(); 14859 ProcessDeclAttributeList(S, D, Attrs); 14860 14861 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14862 if (Method->isStatic()) 14863 checkThisInStaticMemberFunctionAttributes(Method); 14864 } 14865 14866 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14867 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14868 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14869 IdentifierInfo &II, Scope *S) { 14870 // Find the scope in which the identifier is injected and the corresponding 14871 // DeclContext. 14872 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14873 // In that case, we inject the declaration into the translation unit scope 14874 // instead. 14875 Scope *BlockScope = S; 14876 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14877 BlockScope = BlockScope->getParent(); 14878 14879 Scope *ContextScope = BlockScope; 14880 while (!ContextScope->getEntity()) 14881 ContextScope = ContextScope->getParent(); 14882 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14883 14884 // Before we produce a declaration for an implicitly defined 14885 // function, see whether there was a locally-scoped declaration of 14886 // this name as a function or variable. If so, use that 14887 // (non-visible) declaration, and complain about it. 14888 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14889 if (ExternCPrev) { 14890 // We still need to inject the function into the enclosing block scope so 14891 // that later (non-call) uses can see it. 14892 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14893 14894 // C89 footnote 38: 14895 // If in fact it is not defined as having type "function returning int", 14896 // the behavior is undefined. 14897 if (!isa<FunctionDecl>(ExternCPrev) || 14898 !Context.typesAreCompatible( 14899 cast<FunctionDecl>(ExternCPrev)->getType(), 14900 Context.getFunctionNoProtoType(Context.IntTy))) { 14901 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14902 << ExternCPrev << !getLangOpts().C99; 14903 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14904 return ExternCPrev; 14905 } 14906 } 14907 14908 // Extension in C99. Legal in C90, but warn about it. 14909 unsigned diag_id; 14910 if (II.getName().startswith("__builtin_")) 14911 diag_id = diag::warn_builtin_unknown; 14912 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14913 else if (getLangOpts().OpenCL) 14914 diag_id = diag::err_opencl_implicit_function_decl; 14915 else if (getLangOpts().C99) 14916 diag_id = diag::ext_implicit_function_decl; 14917 else 14918 diag_id = diag::warn_implicit_function_decl; 14919 Diag(Loc, diag_id) << &II; 14920 14921 // If we found a prior declaration of this function, don't bother building 14922 // another one. We've already pushed that one into scope, so there's nothing 14923 // more to do. 14924 if (ExternCPrev) 14925 return ExternCPrev; 14926 14927 // Because typo correction is expensive, only do it if the implicit 14928 // function declaration is going to be treated as an error. 14929 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14930 TypoCorrection Corrected; 14931 DeclFilterCCC<FunctionDecl> CCC{}; 14932 if (S && (Corrected = 14933 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14934 S, nullptr, CCC, CTK_NonError))) 14935 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14936 /*ErrorRecovery*/false); 14937 } 14938 14939 // Set a Declarator for the implicit definition: int foo(); 14940 const char *Dummy; 14941 AttributeFactory attrFactory; 14942 DeclSpec DS(attrFactory); 14943 unsigned DiagID; 14944 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14945 Context.getPrintingPolicy()); 14946 (void)Error; // Silence warning. 14947 assert(!Error && "Error setting up implicit decl!"); 14948 SourceLocation NoLoc; 14949 Declarator D(DS, DeclaratorContext::Block); 14950 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14951 /*IsAmbiguous=*/false, 14952 /*LParenLoc=*/NoLoc, 14953 /*Params=*/nullptr, 14954 /*NumParams=*/0, 14955 /*EllipsisLoc=*/NoLoc, 14956 /*RParenLoc=*/NoLoc, 14957 /*RefQualifierIsLvalueRef=*/true, 14958 /*RefQualifierLoc=*/NoLoc, 14959 /*MutableLoc=*/NoLoc, EST_None, 14960 /*ESpecRange=*/SourceRange(), 14961 /*Exceptions=*/nullptr, 14962 /*ExceptionRanges=*/nullptr, 14963 /*NumExceptions=*/0, 14964 /*NoexceptExpr=*/nullptr, 14965 /*ExceptionSpecTokens=*/nullptr, 14966 /*DeclsInPrototype=*/None, Loc, 14967 Loc, D), 14968 std::move(DS.getAttributes()), SourceLocation()); 14969 D.SetIdentifier(&II, Loc); 14970 14971 // Insert this function into the enclosing block scope. 14972 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14973 FD->setImplicit(); 14974 14975 AddKnownFunctionAttributes(FD); 14976 14977 return FD; 14978 } 14979 14980 /// If this function is a C++ replaceable global allocation function 14981 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14982 /// adds any function attributes that we know a priori based on the standard. 14983 /// 14984 /// We need to check for duplicate attributes both here and where user-written 14985 /// attributes are applied to declarations. 14986 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14987 FunctionDecl *FD) { 14988 if (FD->isInvalidDecl()) 14989 return; 14990 14991 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14992 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14993 return; 14994 14995 Optional<unsigned> AlignmentParam; 14996 bool IsNothrow = false; 14997 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14998 return; 14999 15000 // C++2a [basic.stc.dynamic.allocation]p4: 15001 // An allocation function that has a non-throwing exception specification 15002 // indicates failure by returning a null pointer value. Any other allocation 15003 // function never returns a null pointer value and indicates failure only by 15004 // throwing an exception [...] 15005 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15006 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15007 15008 // C++2a [basic.stc.dynamic.allocation]p2: 15009 // An allocation function attempts to allocate the requested amount of 15010 // storage. [...] If the request succeeds, the value returned by a 15011 // replaceable allocation function is a [...] pointer value p0 different 15012 // from any previously returned value p1 [...] 15013 // 15014 // However, this particular information is being added in codegen, 15015 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15016 15017 // C++2a [basic.stc.dynamic.allocation]p2: 15018 // An allocation function attempts to allocate the requested amount of 15019 // storage. If it is successful, it returns the address of the start of a 15020 // block of storage whose length in bytes is at least as large as the 15021 // requested size. 15022 if (!FD->hasAttr<AllocSizeAttr>()) { 15023 FD->addAttr(AllocSizeAttr::CreateImplicit( 15024 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15025 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15026 } 15027 15028 // C++2a [basic.stc.dynamic.allocation]p3: 15029 // For an allocation function [...], the pointer returned on a successful 15030 // call shall represent the address of storage that is aligned as follows: 15031 // (3.1) If the allocation function takes an argument of type 15032 // std::align_val_t, the storage will have the alignment 15033 // specified by the value of this argument. 15034 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15035 FD->addAttr(AllocAlignAttr::CreateImplicit( 15036 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15037 } 15038 15039 // FIXME: 15040 // C++2a [basic.stc.dynamic.allocation]p3: 15041 // For an allocation function [...], the pointer returned on a successful 15042 // call shall represent the address of storage that is aligned as follows: 15043 // (3.2) Otherwise, if the allocation function is named operator new[], 15044 // the storage is aligned for any object that does not have 15045 // new-extended alignment ([basic.align]) and is no larger than the 15046 // requested size. 15047 // (3.3) Otherwise, the storage is aligned for any object that does not 15048 // have new-extended alignment and is of the requested size. 15049 } 15050 15051 /// Adds any function attributes that we know a priori based on 15052 /// the declaration of this function. 15053 /// 15054 /// These attributes can apply both to implicitly-declared builtins 15055 /// (like __builtin___printf_chk) or to library-declared functions 15056 /// like NSLog or printf. 15057 /// 15058 /// We need to check for duplicate attributes both here and where user-written 15059 /// attributes are applied to declarations. 15060 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15061 if (FD->isInvalidDecl()) 15062 return; 15063 15064 // If this is a built-in function, map its builtin attributes to 15065 // actual attributes. 15066 if (unsigned BuiltinID = FD->getBuiltinID()) { 15067 // Handle printf-formatting attributes. 15068 unsigned FormatIdx; 15069 bool HasVAListArg; 15070 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15071 if (!FD->hasAttr<FormatAttr>()) { 15072 const char *fmt = "printf"; 15073 unsigned int NumParams = FD->getNumParams(); 15074 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15075 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15076 fmt = "NSString"; 15077 FD->addAttr(FormatAttr::CreateImplicit(Context, 15078 &Context.Idents.get(fmt), 15079 FormatIdx+1, 15080 HasVAListArg ? 0 : FormatIdx+2, 15081 FD->getLocation())); 15082 } 15083 } 15084 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15085 HasVAListArg)) { 15086 if (!FD->hasAttr<FormatAttr>()) 15087 FD->addAttr(FormatAttr::CreateImplicit(Context, 15088 &Context.Idents.get("scanf"), 15089 FormatIdx+1, 15090 HasVAListArg ? 0 : FormatIdx+2, 15091 FD->getLocation())); 15092 } 15093 15094 // Handle automatically recognized callbacks. 15095 SmallVector<int, 4> Encoding; 15096 if (!FD->hasAttr<CallbackAttr>() && 15097 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15098 FD->addAttr(CallbackAttr::CreateImplicit( 15099 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15100 15101 // Mark const if we don't care about errno and that is the only thing 15102 // preventing the function from being const. This allows IRgen to use LLVM 15103 // intrinsics for such functions. 15104 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15105 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15106 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15107 15108 // We make "fma" on some platforms const because we know it does not set 15109 // errno in those environments even though it could set errno based on the 15110 // C standard. 15111 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15112 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 15113 !FD->hasAttr<ConstAttr>()) { 15114 switch (BuiltinID) { 15115 case Builtin::BI__builtin_fma: 15116 case Builtin::BI__builtin_fmaf: 15117 case Builtin::BI__builtin_fmal: 15118 case Builtin::BIfma: 15119 case Builtin::BIfmaf: 15120 case Builtin::BIfmal: 15121 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15122 break; 15123 default: 15124 break; 15125 } 15126 } 15127 15128 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15129 !FD->hasAttr<ReturnsTwiceAttr>()) 15130 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15131 FD->getLocation())); 15132 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15133 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15134 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15135 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15136 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15137 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15138 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15139 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15140 // Add the appropriate attribute, depending on the CUDA compilation mode 15141 // and which target the builtin belongs to. For example, during host 15142 // compilation, aux builtins are __device__, while the rest are __host__. 15143 if (getLangOpts().CUDAIsDevice != 15144 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15145 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15146 else 15147 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15148 } 15149 15150 // Add known guaranteed alignment for allocation functions. 15151 switch (BuiltinID) { 15152 case Builtin::BIaligned_alloc: 15153 if (!FD->hasAttr<AllocAlignAttr>()) 15154 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15155 FD->getLocation())); 15156 LLVM_FALLTHROUGH; 15157 case Builtin::BIcalloc: 15158 case Builtin::BImalloc: 15159 case Builtin::BImemalign: 15160 case Builtin::BIrealloc: 15161 case Builtin::BIstrdup: 15162 case Builtin::BIstrndup: { 15163 if (!FD->hasAttr<AssumeAlignedAttr>()) { 15164 unsigned NewAlign = Context.getTargetInfo().getNewAlign() / 15165 Context.getTargetInfo().getCharWidth(); 15166 IntegerLiteral *Alignment = IntegerLiteral::Create( 15167 Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy), 15168 Context.UnsignedIntTy, FD->getLocation()); 15169 FD->addAttr(AssumeAlignedAttr::CreateImplicit( 15170 Context, Alignment, /*Offset=*/nullptr, FD->getLocation())); 15171 } 15172 break; 15173 } 15174 default: 15175 break; 15176 } 15177 } 15178 15179 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15180 15181 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15182 // throw, add an implicit nothrow attribute to any extern "C" function we come 15183 // across. 15184 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15185 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15186 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15187 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15188 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15189 } 15190 15191 IdentifierInfo *Name = FD->getIdentifier(); 15192 if (!Name) 15193 return; 15194 if ((!getLangOpts().CPlusPlus && 15195 FD->getDeclContext()->isTranslationUnit()) || 15196 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15197 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15198 LinkageSpecDecl::lang_c)) { 15199 // Okay: this could be a libc/libm/Objective-C function we know 15200 // about. 15201 } else 15202 return; 15203 15204 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15205 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15206 // target-specific builtins, perhaps? 15207 if (!FD->hasAttr<FormatAttr>()) 15208 FD->addAttr(FormatAttr::CreateImplicit(Context, 15209 &Context.Idents.get("printf"), 2, 15210 Name->isStr("vasprintf") ? 0 : 3, 15211 FD->getLocation())); 15212 } 15213 15214 if (Name->isStr("__CFStringMakeConstantString")) { 15215 // We already have a __builtin___CFStringMakeConstantString, 15216 // but builds that use -fno-constant-cfstrings don't go through that. 15217 if (!FD->hasAttr<FormatArgAttr>()) 15218 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15219 FD->getLocation())); 15220 } 15221 } 15222 15223 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15224 TypeSourceInfo *TInfo) { 15225 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15226 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15227 15228 if (!TInfo) { 15229 assert(D.isInvalidType() && "no declarator info for valid type"); 15230 TInfo = Context.getTrivialTypeSourceInfo(T); 15231 } 15232 15233 // Scope manipulation handled by caller. 15234 TypedefDecl *NewTD = 15235 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15236 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15237 15238 // Bail out immediately if we have an invalid declaration. 15239 if (D.isInvalidType()) { 15240 NewTD->setInvalidDecl(); 15241 return NewTD; 15242 } 15243 15244 if (D.getDeclSpec().isModulePrivateSpecified()) { 15245 if (CurContext->isFunctionOrMethod()) 15246 Diag(NewTD->getLocation(), diag::err_module_private_local) 15247 << 2 << NewTD 15248 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15249 << FixItHint::CreateRemoval( 15250 D.getDeclSpec().getModulePrivateSpecLoc()); 15251 else 15252 NewTD->setModulePrivate(); 15253 } 15254 15255 // C++ [dcl.typedef]p8: 15256 // If the typedef declaration defines an unnamed class (or 15257 // enum), the first typedef-name declared by the declaration 15258 // to be that class type (or enum type) is used to denote the 15259 // class type (or enum type) for linkage purposes only. 15260 // We need to check whether the type was declared in the declaration. 15261 switch (D.getDeclSpec().getTypeSpecType()) { 15262 case TST_enum: 15263 case TST_struct: 15264 case TST_interface: 15265 case TST_union: 15266 case TST_class: { 15267 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15268 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15269 break; 15270 } 15271 15272 default: 15273 break; 15274 } 15275 15276 return NewTD; 15277 } 15278 15279 /// Check that this is a valid underlying type for an enum declaration. 15280 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15281 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15282 QualType T = TI->getType(); 15283 15284 if (T->isDependentType()) 15285 return false; 15286 15287 // This doesn't use 'isIntegralType' despite the error message mentioning 15288 // integral type because isIntegralType would also allow enum types in C. 15289 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15290 if (BT->isInteger()) 15291 return false; 15292 15293 if (T->isExtIntType()) 15294 return false; 15295 15296 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15297 } 15298 15299 /// Check whether this is a valid redeclaration of a previous enumeration. 15300 /// \return true if the redeclaration was invalid. 15301 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15302 QualType EnumUnderlyingTy, bool IsFixed, 15303 const EnumDecl *Prev) { 15304 if (IsScoped != Prev->isScoped()) { 15305 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15306 << Prev->isScoped(); 15307 Diag(Prev->getLocation(), diag::note_previous_declaration); 15308 return true; 15309 } 15310 15311 if (IsFixed && Prev->isFixed()) { 15312 if (!EnumUnderlyingTy->isDependentType() && 15313 !Prev->getIntegerType()->isDependentType() && 15314 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15315 Prev->getIntegerType())) { 15316 // TODO: Highlight the underlying type of the redeclaration. 15317 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15318 << EnumUnderlyingTy << Prev->getIntegerType(); 15319 Diag(Prev->getLocation(), diag::note_previous_declaration) 15320 << Prev->getIntegerTypeRange(); 15321 return true; 15322 } 15323 } else if (IsFixed != Prev->isFixed()) { 15324 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15325 << Prev->isFixed(); 15326 Diag(Prev->getLocation(), diag::note_previous_declaration); 15327 return true; 15328 } 15329 15330 return false; 15331 } 15332 15333 /// Get diagnostic %select index for tag kind for 15334 /// redeclaration diagnostic message. 15335 /// WARNING: Indexes apply to particular diagnostics only! 15336 /// 15337 /// \returns diagnostic %select index. 15338 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15339 switch (Tag) { 15340 case TTK_Struct: return 0; 15341 case TTK_Interface: return 1; 15342 case TTK_Class: return 2; 15343 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15344 } 15345 } 15346 15347 /// Determine if tag kind is a class-key compatible with 15348 /// class for redeclaration (class, struct, or __interface). 15349 /// 15350 /// \returns true iff the tag kind is compatible. 15351 static bool isClassCompatTagKind(TagTypeKind Tag) 15352 { 15353 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15354 } 15355 15356 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15357 TagTypeKind TTK) { 15358 if (isa<TypedefDecl>(PrevDecl)) 15359 return NTK_Typedef; 15360 else if (isa<TypeAliasDecl>(PrevDecl)) 15361 return NTK_TypeAlias; 15362 else if (isa<ClassTemplateDecl>(PrevDecl)) 15363 return NTK_Template; 15364 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15365 return NTK_TypeAliasTemplate; 15366 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15367 return NTK_TemplateTemplateArgument; 15368 switch (TTK) { 15369 case TTK_Struct: 15370 case TTK_Interface: 15371 case TTK_Class: 15372 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15373 case TTK_Union: 15374 return NTK_NonUnion; 15375 case TTK_Enum: 15376 return NTK_NonEnum; 15377 } 15378 llvm_unreachable("invalid TTK"); 15379 } 15380 15381 /// Determine whether a tag with a given kind is acceptable 15382 /// as a redeclaration of the given tag declaration. 15383 /// 15384 /// \returns true if the new tag kind is acceptable, false otherwise. 15385 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15386 TagTypeKind NewTag, bool isDefinition, 15387 SourceLocation NewTagLoc, 15388 const IdentifierInfo *Name) { 15389 // C++ [dcl.type.elab]p3: 15390 // The class-key or enum keyword present in the 15391 // elaborated-type-specifier shall agree in kind with the 15392 // declaration to which the name in the elaborated-type-specifier 15393 // refers. This rule also applies to the form of 15394 // elaborated-type-specifier that declares a class-name or 15395 // friend class since it can be construed as referring to the 15396 // definition of the class. Thus, in any 15397 // elaborated-type-specifier, the enum keyword shall be used to 15398 // refer to an enumeration (7.2), the union class-key shall be 15399 // used to refer to a union (clause 9), and either the class or 15400 // struct class-key shall be used to refer to a class (clause 9) 15401 // declared using the class or struct class-key. 15402 TagTypeKind OldTag = Previous->getTagKind(); 15403 if (OldTag != NewTag && 15404 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15405 return false; 15406 15407 // Tags are compatible, but we might still want to warn on mismatched tags. 15408 // Non-class tags can't be mismatched at this point. 15409 if (!isClassCompatTagKind(NewTag)) 15410 return true; 15411 15412 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15413 // by our warning analysis. We don't want to warn about mismatches with (eg) 15414 // declarations in system headers that are designed to be specialized, but if 15415 // a user asks us to warn, we should warn if their code contains mismatched 15416 // declarations. 15417 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15418 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15419 Loc); 15420 }; 15421 if (IsIgnoredLoc(NewTagLoc)) 15422 return true; 15423 15424 auto IsIgnored = [&](const TagDecl *Tag) { 15425 return IsIgnoredLoc(Tag->getLocation()); 15426 }; 15427 while (IsIgnored(Previous)) { 15428 Previous = Previous->getPreviousDecl(); 15429 if (!Previous) 15430 return true; 15431 OldTag = Previous->getTagKind(); 15432 } 15433 15434 bool isTemplate = false; 15435 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15436 isTemplate = Record->getDescribedClassTemplate(); 15437 15438 if (inTemplateInstantiation()) { 15439 if (OldTag != NewTag) { 15440 // In a template instantiation, do not offer fix-its for tag mismatches 15441 // since they usually mess up the template instead of fixing the problem. 15442 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15443 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15444 << getRedeclDiagFromTagKind(OldTag); 15445 // FIXME: Note previous location? 15446 } 15447 return true; 15448 } 15449 15450 if (isDefinition) { 15451 // On definitions, check all previous tags and issue a fix-it for each 15452 // one that doesn't match the current tag. 15453 if (Previous->getDefinition()) { 15454 // Don't suggest fix-its for redefinitions. 15455 return true; 15456 } 15457 15458 bool previousMismatch = false; 15459 for (const TagDecl *I : Previous->redecls()) { 15460 if (I->getTagKind() != NewTag) { 15461 // Ignore previous declarations for which the warning was disabled. 15462 if (IsIgnored(I)) 15463 continue; 15464 15465 if (!previousMismatch) { 15466 previousMismatch = true; 15467 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15468 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15469 << getRedeclDiagFromTagKind(I->getTagKind()); 15470 } 15471 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15472 << getRedeclDiagFromTagKind(NewTag) 15473 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15474 TypeWithKeyword::getTagTypeKindName(NewTag)); 15475 } 15476 } 15477 return true; 15478 } 15479 15480 // Identify the prevailing tag kind: this is the kind of the definition (if 15481 // there is a non-ignored definition), or otherwise the kind of the prior 15482 // (non-ignored) declaration. 15483 const TagDecl *PrevDef = Previous->getDefinition(); 15484 if (PrevDef && IsIgnored(PrevDef)) 15485 PrevDef = nullptr; 15486 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15487 if (Redecl->getTagKind() != NewTag) { 15488 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15489 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15490 << getRedeclDiagFromTagKind(OldTag); 15491 Diag(Redecl->getLocation(), diag::note_previous_use); 15492 15493 // If there is a previous definition, suggest a fix-it. 15494 if (PrevDef) { 15495 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15496 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15497 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15498 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15499 } 15500 } 15501 15502 return true; 15503 } 15504 15505 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15506 /// from an outer enclosing namespace or file scope inside a friend declaration. 15507 /// This should provide the commented out code in the following snippet: 15508 /// namespace N { 15509 /// struct X; 15510 /// namespace M { 15511 /// struct Y { friend struct /*N::*/ X; }; 15512 /// } 15513 /// } 15514 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15515 SourceLocation NameLoc) { 15516 // While the decl is in a namespace, do repeated lookup of that name and see 15517 // if we get the same namespace back. If we do not, continue until 15518 // translation unit scope, at which point we have a fully qualified NNS. 15519 SmallVector<IdentifierInfo *, 4> Namespaces; 15520 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15521 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15522 // This tag should be declared in a namespace, which can only be enclosed by 15523 // other namespaces. Bail if there's an anonymous namespace in the chain. 15524 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15525 if (!Namespace || Namespace->isAnonymousNamespace()) 15526 return FixItHint(); 15527 IdentifierInfo *II = Namespace->getIdentifier(); 15528 Namespaces.push_back(II); 15529 NamedDecl *Lookup = SemaRef.LookupSingleName( 15530 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15531 if (Lookup == Namespace) 15532 break; 15533 } 15534 15535 // Once we have all the namespaces, reverse them to go outermost first, and 15536 // build an NNS. 15537 SmallString<64> Insertion; 15538 llvm::raw_svector_ostream OS(Insertion); 15539 if (DC->isTranslationUnit()) 15540 OS << "::"; 15541 std::reverse(Namespaces.begin(), Namespaces.end()); 15542 for (auto *II : Namespaces) 15543 OS << II->getName() << "::"; 15544 return FixItHint::CreateInsertion(NameLoc, Insertion); 15545 } 15546 15547 /// Determine whether a tag originally declared in context \p OldDC can 15548 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15549 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15550 /// using-declaration). 15551 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15552 DeclContext *NewDC) { 15553 OldDC = OldDC->getRedeclContext(); 15554 NewDC = NewDC->getRedeclContext(); 15555 15556 if (OldDC->Equals(NewDC)) 15557 return true; 15558 15559 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15560 // encloses the other). 15561 if (S.getLangOpts().MSVCCompat && 15562 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15563 return true; 15564 15565 return false; 15566 } 15567 15568 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15569 /// former case, Name will be non-null. In the later case, Name will be null. 15570 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15571 /// reference/declaration/definition of a tag. 15572 /// 15573 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15574 /// trailing-type-specifier) other than one in an alias-declaration. 15575 /// 15576 /// \param SkipBody If non-null, will be set to indicate if the caller should 15577 /// skip the definition of this tag and treat it as if it were a declaration. 15578 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15579 SourceLocation KWLoc, CXXScopeSpec &SS, 15580 IdentifierInfo *Name, SourceLocation NameLoc, 15581 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15582 SourceLocation ModulePrivateLoc, 15583 MultiTemplateParamsArg TemplateParameterLists, 15584 bool &OwnedDecl, bool &IsDependent, 15585 SourceLocation ScopedEnumKWLoc, 15586 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15587 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15588 SkipBodyInfo *SkipBody) { 15589 // If this is not a definition, it must have a name. 15590 IdentifierInfo *OrigName = Name; 15591 assert((Name != nullptr || TUK == TUK_Definition) && 15592 "Nameless record must be a definition!"); 15593 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15594 15595 OwnedDecl = false; 15596 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15597 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15598 15599 // FIXME: Check member specializations more carefully. 15600 bool isMemberSpecialization = false; 15601 bool Invalid = false; 15602 15603 // We only need to do this matching if we have template parameters 15604 // or a scope specifier, which also conveniently avoids this work 15605 // for non-C++ cases. 15606 if (TemplateParameterLists.size() > 0 || 15607 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15608 if (TemplateParameterList *TemplateParams = 15609 MatchTemplateParametersToScopeSpecifier( 15610 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15611 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15612 if (Kind == TTK_Enum) { 15613 Diag(KWLoc, diag::err_enum_template); 15614 return nullptr; 15615 } 15616 15617 if (TemplateParams->size() > 0) { 15618 // This is a declaration or definition of a class template (which may 15619 // be a member of another template). 15620 15621 if (Invalid) 15622 return nullptr; 15623 15624 OwnedDecl = false; 15625 DeclResult Result = CheckClassTemplate( 15626 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15627 AS, ModulePrivateLoc, 15628 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15629 TemplateParameterLists.data(), SkipBody); 15630 return Result.get(); 15631 } else { 15632 // The "template<>" header is extraneous. 15633 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15634 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15635 isMemberSpecialization = true; 15636 } 15637 } 15638 15639 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15640 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15641 return nullptr; 15642 } 15643 15644 // Figure out the underlying type if this a enum declaration. We need to do 15645 // this early, because it's needed to detect if this is an incompatible 15646 // redeclaration. 15647 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15648 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15649 15650 if (Kind == TTK_Enum) { 15651 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15652 // No underlying type explicitly specified, or we failed to parse the 15653 // type, default to int. 15654 EnumUnderlying = Context.IntTy.getTypePtr(); 15655 } else if (UnderlyingType.get()) { 15656 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15657 // integral type; any cv-qualification is ignored. 15658 TypeSourceInfo *TI = nullptr; 15659 GetTypeFromParser(UnderlyingType.get(), &TI); 15660 EnumUnderlying = TI; 15661 15662 if (CheckEnumUnderlyingType(TI)) 15663 // Recover by falling back to int. 15664 EnumUnderlying = Context.IntTy.getTypePtr(); 15665 15666 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15667 UPPC_FixedUnderlyingType)) 15668 EnumUnderlying = Context.IntTy.getTypePtr(); 15669 15670 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15671 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15672 // of 'int'. However, if this is an unfixed forward declaration, don't set 15673 // the underlying type unless the user enables -fms-compatibility. This 15674 // makes unfixed forward declared enums incomplete and is more conforming. 15675 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15676 EnumUnderlying = Context.IntTy.getTypePtr(); 15677 } 15678 } 15679 15680 DeclContext *SearchDC = CurContext; 15681 DeclContext *DC = CurContext; 15682 bool isStdBadAlloc = false; 15683 bool isStdAlignValT = false; 15684 15685 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15686 if (TUK == TUK_Friend || TUK == TUK_Reference) 15687 Redecl = NotForRedeclaration; 15688 15689 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15690 /// implemented asks for structural equivalence checking, the returned decl 15691 /// here is passed back to the parser, allowing the tag body to be parsed. 15692 auto createTagFromNewDecl = [&]() -> TagDecl * { 15693 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15694 // If there is an identifier, use the location of the identifier as the 15695 // location of the decl, otherwise use the location of the struct/union 15696 // keyword. 15697 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15698 TagDecl *New = nullptr; 15699 15700 if (Kind == TTK_Enum) { 15701 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15702 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15703 // If this is an undefined enum, bail. 15704 if (TUK != TUK_Definition && !Invalid) 15705 return nullptr; 15706 if (EnumUnderlying) { 15707 EnumDecl *ED = cast<EnumDecl>(New); 15708 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15709 ED->setIntegerTypeSourceInfo(TI); 15710 else 15711 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15712 ED->setPromotionType(ED->getIntegerType()); 15713 } 15714 } else { // struct/union 15715 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15716 nullptr); 15717 } 15718 15719 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15720 // Add alignment attributes if necessary; these attributes are checked 15721 // when the ASTContext lays out the structure. 15722 // 15723 // It is important for implementing the correct semantics that this 15724 // happen here (in ActOnTag). The #pragma pack stack is 15725 // maintained as a result of parser callbacks which can occur at 15726 // many points during the parsing of a struct declaration (because 15727 // the #pragma tokens are effectively skipped over during the 15728 // parsing of the struct). 15729 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15730 AddAlignmentAttributesForRecord(RD); 15731 AddMsStructLayoutForRecord(RD); 15732 } 15733 } 15734 New->setLexicalDeclContext(CurContext); 15735 return New; 15736 }; 15737 15738 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15739 if (Name && SS.isNotEmpty()) { 15740 // We have a nested-name tag ('struct foo::bar'). 15741 15742 // Check for invalid 'foo::'. 15743 if (SS.isInvalid()) { 15744 Name = nullptr; 15745 goto CreateNewDecl; 15746 } 15747 15748 // If this is a friend or a reference to a class in a dependent 15749 // context, don't try to make a decl for it. 15750 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15751 DC = computeDeclContext(SS, false); 15752 if (!DC) { 15753 IsDependent = true; 15754 return nullptr; 15755 } 15756 } else { 15757 DC = computeDeclContext(SS, true); 15758 if (!DC) { 15759 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15760 << SS.getRange(); 15761 return nullptr; 15762 } 15763 } 15764 15765 if (RequireCompleteDeclContext(SS, DC)) 15766 return nullptr; 15767 15768 SearchDC = DC; 15769 // Look-up name inside 'foo::'. 15770 LookupQualifiedName(Previous, DC); 15771 15772 if (Previous.isAmbiguous()) 15773 return nullptr; 15774 15775 if (Previous.empty()) { 15776 // Name lookup did not find anything. However, if the 15777 // nested-name-specifier refers to the current instantiation, 15778 // and that current instantiation has any dependent base 15779 // classes, we might find something at instantiation time: treat 15780 // this as a dependent elaborated-type-specifier. 15781 // But this only makes any sense for reference-like lookups. 15782 if (Previous.wasNotFoundInCurrentInstantiation() && 15783 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15784 IsDependent = true; 15785 return nullptr; 15786 } 15787 15788 // A tag 'foo::bar' must already exist. 15789 Diag(NameLoc, diag::err_not_tag_in_scope) 15790 << Kind << Name << DC << SS.getRange(); 15791 Name = nullptr; 15792 Invalid = true; 15793 goto CreateNewDecl; 15794 } 15795 } else if (Name) { 15796 // C++14 [class.mem]p14: 15797 // If T is the name of a class, then each of the following shall have a 15798 // name different from T: 15799 // -- every member of class T that is itself a type 15800 if (TUK != TUK_Reference && TUK != TUK_Friend && 15801 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15802 return nullptr; 15803 15804 // If this is a named struct, check to see if there was a previous forward 15805 // declaration or definition. 15806 // FIXME: We're looking into outer scopes here, even when we 15807 // shouldn't be. Doing so can result in ambiguities that we 15808 // shouldn't be diagnosing. 15809 LookupName(Previous, S); 15810 15811 // When declaring or defining a tag, ignore ambiguities introduced 15812 // by types using'ed into this scope. 15813 if (Previous.isAmbiguous() && 15814 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15815 LookupResult::Filter F = Previous.makeFilter(); 15816 while (F.hasNext()) { 15817 NamedDecl *ND = F.next(); 15818 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15819 SearchDC->getRedeclContext())) 15820 F.erase(); 15821 } 15822 F.done(); 15823 } 15824 15825 // C++11 [namespace.memdef]p3: 15826 // If the name in a friend declaration is neither qualified nor 15827 // a template-id and the declaration is a function or an 15828 // elaborated-type-specifier, the lookup to determine whether 15829 // the entity has been previously declared shall not consider 15830 // any scopes outside the innermost enclosing namespace. 15831 // 15832 // MSVC doesn't implement the above rule for types, so a friend tag 15833 // declaration may be a redeclaration of a type declared in an enclosing 15834 // scope. They do implement this rule for friend functions. 15835 // 15836 // Does it matter that this should be by scope instead of by 15837 // semantic context? 15838 if (!Previous.empty() && TUK == TUK_Friend) { 15839 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15840 LookupResult::Filter F = Previous.makeFilter(); 15841 bool FriendSawTagOutsideEnclosingNamespace = false; 15842 while (F.hasNext()) { 15843 NamedDecl *ND = F.next(); 15844 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15845 if (DC->isFileContext() && 15846 !EnclosingNS->Encloses(ND->getDeclContext())) { 15847 if (getLangOpts().MSVCCompat) 15848 FriendSawTagOutsideEnclosingNamespace = true; 15849 else 15850 F.erase(); 15851 } 15852 } 15853 F.done(); 15854 15855 // Diagnose this MSVC extension in the easy case where lookup would have 15856 // unambiguously found something outside the enclosing namespace. 15857 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15858 NamedDecl *ND = Previous.getFoundDecl(); 15859 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15860 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15861 } 15862 } 15863 15864 // Note: there used to be some attempt at recovery here. 15865 if (Previous.isAmbiguous()) 15866 return nullptr; 15867 15868 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15869 // FIXME: This makes sure that we ignore the contexts associated 15870 // with C structs, unions, and enums when looking for a matching 15871 // tag declaration or definition. See the similar lookup tweak 15872 // in Sema::LookupName; is there a better way to deal with this? 15873 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15874 SearchDC = SearchDC->getParent(); 15875 } 15876 } 15877 15878 if (Previous.isSingleResult() && 15879 Previous.getFoundDecl()->isTemplateParameter()) { 15880 // Maybe we will complain about the shadowed template parameter. 15881 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15882 // Just pretend that we didn't see the previous declaration. 15883 Previous.clear(); 15884 } 15885 15886 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15887 DC->Equals(getStdNamespace())) { 15888 if (Name->isStr("bad_alloc")) { 15889 // This is a declaration of or a reference to "std::bad_alloc". 15890 isStdBadAlloc = true; 15891 15892 // If std::bad_alloc has been implicitly declared (but made invisible to 15893 // name lookup), fill in this implicit declaration as the previous 15894 // declaration, so that the declarations get chained appropriately. 15895 if (Previous.empty() && StdBadAlloc) 15896 Previous.addDecl(getStdBadAlloc()); 15897 } else if (Name->isStr("align_val_t")) { 15898 isStdAlignValT = true; 15899 if (Previous.empty() && StdAlignValT) 15900 Previous.addDecl(getStdAlignValT()); 15901 } 15902 } 15903 15904 // If we didn't find a previous declaration, and this is a reference 15905 // (or friend reference), move to the correct scope. In C++, we 15906 // also need to do a redeclaration lookup there, just in case 15907 // there's a shadow friend decl. 15908 if (Name && Previous.empty() && 15909 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15910 if (Invalid) goto CreateNewDecl; 15911 assert(SS.isEmpty()); 15912 15913 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15914 // C++ [basic.scope.pdecl]p5: 15915 // -- for an elaborated-type-specifier of the form 15916 // 15917 // class-key identifier 15918 // 15919 // if the elaborated-type-specifier is used in the 15920 // decl-specifier-seq or parameter-declaration-clause of a 15921 // function defined in namespace scope, the identifier is 15922 // declared as a class-name in the namespace that contains 15923 // the declaration; otherwise, except as a friend 15924 // declaration, the identifier is declared in the smallest 15925 // non-class, non-function-prototype scope that contains the 15926 // declaration. 15927 // 15928 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15929 // C structs and unions. 15930 // 15931 // It is an error in C++ to declare (rather than define) an enum 15932 // type, including via an elaborated type specifier. We'll 15933 // diagnose that later; for now, declare the enum in the same 15934 // scope as we would have picked for any other tag type. 15935 // 15936 // GNU C also supports this behavior as part of its incomplete 15937 // enum types extension, while GNU C++ does not. 15938 // 15939 // Find the context where we'll be declaring the tag. 15940 // FIXME: We would like to maintain the current DeclContext as the 15941 // lexical context, 15942 SearchDC = getTagInjectionContext(SearchDC); 15943 15944 // Find the scope where we'll be declaring the tag. 15945 S = getTagInjectionScope(S, getLangOpts()); 15946 } else { 15947 assert(TUK == TUK_Friend); 15948 // C++ [namespace.memdef]p3: 15949 // If a friend declaration in a non-local class first declares a 15950 // class or function, the friend class or function is a member of 15951 // the innermost enclosing namespace. 15952 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15953 } 15954 15955 // In C++, we need to do a redeclaration lookup to properly 15956 // diagnose some problems. 15957 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15958 // hidden declaration so that we don't get ambiguity errors when using a 15959 // type declared by an elaborated-type-specifier. In C that is not correct 15960 // and we should instead merge compatible types found by lookup. 15961 if (getLangOpts().CPlusPlus) { 15962 // FIXME: This can perform qualified lookups into function contexts, 15963 // which are meaningless. 15964 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15965 LookupQualifiedName(Previous, SearchDC); 15966 } else { 15967 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15968 LookupName(Previous, S); 15969 } 15970 } 15971 15972 // If we have a known previous declaration to use, then use it. 15973 if (Previous.empty() && SkipBody && SkipBody->Previous) 15974 Previous.addDecl(SkipBody->Previous); 15975 15976 if (!Previous.empty()) { 15977 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15978 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15979 15980 // It's okay to have a tag decl in the same scope as a typedef 15981 // which hides a tag decl in the same scope. Finding this 15982 // insanity with a redeclaration lookup can only actually happen 15983 // in C++. 15984 // 15985 // This is also okay for elaborated-type-specifiers, which is 15986 // technically forbidden by the current standard but which is 15987 // okay according to the likely resolution of an open issue; 15988 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15989 if (getLangOpts().CPlusPlus) { 15990 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15991 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15992 TagDecl *Tag = TT->getDecl(); 15993 if (Tag->getDeclName() == Name && 15994 Tag->getDeclContext()->getRedeclContext() 15995 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15996 PrevDecl = Tag; 15997 Previous.clear(); 15998 Previous.addDecl(Tag); 15999 Previous.resolveKind(); 16000 } 16001 } 16002 } 16003 } 16004 16005 // If this is a redeclaration of a using shadow declaration, it must 16006 // declare a tag in the same context. In MSVC mode, we allow a 16007 // redefinition if either context is within the other. 16008 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16009 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16010 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16011 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16012 !(OldTag && isAcceptableTagRedeclContext( 16013 *this, OldTag->getDeclContext(), SearchDC))) { 16014 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16015 Diag(Shadow->getTargetDecl()->getLocation(), 16016 diag::note_using_decl_target); 16017 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16018 << 0; 16019 // Recover by ignoring the old declaration. 16020 Previous.clear(); 16021 goto CreateNewDecl; 16022 } 16023 } 16024 16025 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16026 // If this is a use of a previous tag, or if the tag is already declared 16027 // in the same scope (so that the definition/declaration completes or 16028 // rementions the tag), reuse the decl. 16029 if (TUK == TUK_Reference || TUK == TUK_Friend || 16030 isDeclInScope(DirectPrevDecl, SearchDC, S, 16031 SS.isNotEmpty() || isMemberSpecialization)) { 16032 // Make sure that this wasn't declared as an enum and now used as a 16033 // struct or something similar. 16034 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16035 TUK == TUK_Definition, KWLoc, 16036 Name)) { 16037 bool SafeToContinue 16038 = (PrevTagDecl->getTagKind() != TTK_Enum && 16039 Kind != TTK_Enum); 16040 if (SafeToContinue) 16041 Diag(KWLoc, diag::err_use_with_wrong_tag) 16042 << Name 16043 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16044 PrevTagDecl->getKindName()); 16045 else 16046 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16047 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16048 16049 if (SafeToContinue) 16050 Kind = PrevTagDecl->getTagKind(); 16051 else { 16052 // Recover by making this an anonymous redefinition. 16053 Name = nullptr; 16054 Previous.clear(); 16055 Invalid = true; 16056 } 16057 } 16058 16059 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16060 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16061 if (TUK == TUK_Reference || TUK == TUK_Friend) 16062 return PrevTagDecl; 16063 16064 QualType EnumUnderlyingTy; 16065 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16066 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16067 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16068 EnumUnderlyingTy = QualType(T, 0); 16069 16070 // All conflicts with previous declarations are recovered by 16071 // returning the previous declaration, unless this is a definition, 16072 // in which case we want the caller to bail out. 16073 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16074 ScopedEnum, EnumUnderlyingTy, 16075 IsFixed, PrevEnum)) 16076 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16077 } 16078 16079 // C++11 [class.mem]p1: 16080 // A member shall not be declared twice in the member-specification, 16081 // except that a nested class or member class template can be declared 16082 // and then later defined. 16083 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16084 S->isDeclScope(PrevDecl)) { 16085 Diag(NameLoc, diag::ext_member_redeclared); 16086 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16087 } 16088 16089 if (!Invalid) { 16090 // If this is a use, just return the declaration we found, unless 16091 // we have attributes. 16092 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16093 if (!Attrs.empty()) { 16094 // FIXME: Diagnose these attributes. For now, we create a new 16095 // declaration to hold them. 16096 } else if (TUK == TUK_Reference && 16097 (PrevTagDecl->getFriendObjectKind() == 16098 Decl::FOK_Undeclared || 16099 PrevDecl->getOwningModule() != getCurrentModule()) && 16100 SS.isEmpty()) { 16101 // This declaration is a reference to an existing entity, but 16102 // has different visibility from that entity: it either makes 16103 // a friend visible or it makes a type visible in a new module. 16104 // In either case, create a new declaration. We only do this if 16105 // the declaration would have meant the same thing if no prior 16106 // declaration were found, that is, if it was found in the same 16107 // scope where we would have injected a declaration. 16108 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16109 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16110 return PrevTagDecl; 16111 // This is in the injected scope, create a new declaration in 16112 // that scope. 16113 S = getTagInjectionScope(S, getLangOpts()); 16114 } else { 16115 return PrevTagDecl; 16116 } 16117 } 16118 16119 // Diagnose attempts to redefine a tag. 16120 if (TUK == TUK_Definition) { 16121 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16122 // If we're defining a specialization and the previous definition 16123 // is from an implicit instantiation, don't emit an error 16124 // here; we'll catch this in the general case below. 16125 bool IsExplicitSpecializationAfterInstantiation = false; 16126 if (isMemberSpecialization) { 16127 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16128 IsExplicitSpecializationAfterInstantiation = 16129 RD->getTemplateSpecializationKind() != 16130 TSK_ExplicitSpecialization; 16131 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16132 IsExplicitSpecializationAfterInstantiation = 16133 ED->getTemplateSpecializationKind() != 16134 TSK_ExplicitSpecialization; 16135 } 16136 16137 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16138 // not keep more that one definition around (merge them). However, 16139 // ensure the decl passes the structural compatibility check in 16140 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16141 NamedDecl *Hidden = nullptr; 16142 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16143 // There is a definition of this tag, but it is not visible. We 16144 // explicitly make use of C++'s one definition rule here, and 16145 // assume that this definition is identical to the hidden one 16146 // we already have. Make the existing definition visible and 16147 // use it in place of this one. 16148 if (!getLangOpts().CPlusPlus) { 16149 // Postpone making the old definition visible until after we 16150 // complete parsing the new one and do the structural 16151 // comparison. 16152 SkipBody->CheckSameAsPrevious = true; 16153 SkipBody->New = createTagFromNewDecl(); 16154 SkipBody->Previous = Def; 16155 return Def; 16156 } else { 16157 SkipBody->ShouldSkip = true; 16158 SkipBody->Previous = Def; 16159 makeMergedDefinitionVisible(Hidden); 16160 // Carry on and handle it like a normal definition. We'll 16161 // skip starting the definitiion later. 16162 } 16163 } else if (!IsExplicitSpecializationAfterInstantiation) { 16164 // A redeclaration in function prototype scope in C isn't 16165 // visible elsewhere, so merely issue a warning. 16166 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16167 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16168 else 16169 Diag(NameLoc, diag::err_redefinition) << Name; 16170 notePreviousDefinition(Def, 16171 NameLoc.isValid() ? NameLoc : KWLoc); 16172 // If this is a redefinition, recover by making this 16173 // struct be anonymous, which will make any later 16174 // references get the previous definition. 16175 Name = nullptr; 16176 Previous.clear(); 16177 Invalid = true; 16178 } 16179 } else { 16180 // If the type is currently being defined, complain 16181 // about a nested redefinition. 16182 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16183 if (TD->isBeingDefined()) { 16184 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16185 Diag(PrevTagDecl->getLocation(), 16186 diag::note_previous_definition); 16187 Name = nullptr; 16188 Previous.clear(); 16189 Invalid = true; 16190 } 16191 } 16192 16193 // Okay, this is definition of a previously declared or referenced 16194 // tag. We're going to create a new Decl for it. 16195 } 16196 16197 // Okay, we're going to make a redeclaration. If this is some kind 16198 // of reference, make sure we build the redeclaration in the same DC 16199 // as the original, and ignore the current access specifier. 16200 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16201 SearchDC = PrevTagDecl->getDeclContext(); 16202 AS = AS_none; 16203 } 16204 } 16205 // If we get here we have (another) forward declaration or we 16206 // have a definition. Just create a new decl. 16207 16208 } else { 16209 // If we get here, this is a definition of a new tag type in a nested 16210 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16211 // new decl/type. We set PrevDecl to NULL so that the entities 16212 // have distinct types. 16213 Previous.clear(); 16214 } 16215 // If we get here, we're going to create a new Decl. If PrevDecl 16216 // is non-NULL, it's a definition of the tag declared by 16217 // PrevDecl. If it's NULL, we have a new definition. 16218 16219 // Otherwise, PrevDecl is not a tag, but was found with tag 16220 // lookup. This is only actually possible in C++, where a few 16221 // things like templates still live in the tag namespace. 16222 } else { 16223 // Use a better diagnostic if an elaborated-type-specifier 16224 // found the wrong kind of type on the first 16225 // (non-redeclaration) lookup. 16226 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16227 !Previous.isForRedeclaration()) { 16228 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16229 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16230 << Kind; 16231 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16232 Invalid = true; 16233 16234 // Otherwise, only diagnose if the declaration is in scope. 16235 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16236 SS.isNotEmpty() || isMemberSpecialization)) { 16237 // do nothing 16238 16239 // Diagnose implicit declarations introduced by elaborated types. 16240 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16241 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16242 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16243 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16244 Invalid = true; 16245 16246 // Otherwise it's a declaration. Call out a particularly common 16247 // case here. 16248 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16249 unsigned Kind = 0; 16250 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16251 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16252 << Name << Kind << TND->getUnderlyingType(); 16253 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16254 Invalid = true; 16255 16256 // Otherwise, diagnose. 16257 } else { 16258 // The tag name clashes with something else in the target scope, 16259 // issue an error and recover by making this tag be anonymous. 16260 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16261 notePreviousDefinition(PrevDecl, NameLoc); 16262 Name = nullptr; 16263 Invalid = true; 16264 } 16265 16266 // The existing declaration isn't relevant to us; we're in a 16267 // new scope, so clear out the previous declaration. 16268 Previous.clear(); 16269 } 16270 } 16271 16272 CreateNewDecl: 16273 16274 TagDecl *PrevDecl = nullptr; 16275 if (Previous.isSingleResult()) 16276 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16277 16278 // If there is an identifier, use the location of the identifier as the 16279 // location of the decl, otherwise use the location of the struct/union 16280 // keyword. 16281 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16282 16283 // Otherwise, create a new declaration. If there is a previous 16284 // declaration of the same entity, the two will be linked via 16285 // PrevDecl. 16286 TagDecl *New; 16287 16288 if (Kind == TTK_Enum) { 16289 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16290 // enum X { A, B, C } D; D should chain to X. 16291 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16292 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16293 ScopedEnumUsesClassTag, IsFixed); 16294 16295 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16296 StdAlignValT = cast<EnumDecl>(New); 16297 16298 // If this is an undefined enum, warn. 16299 if (TUK != TUK_Definition && !Invalid) { 16300 TagDecl *Def; 16301 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16302 // C++0x: 7.2p2: opaque-enum-declaration. 16303 // Conflicts are diagnosed above. Do nothing. 16304 } 16305 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16306 Diag(Loc, diag::ext_forward_ref_enum_def) 16307 << New; 16308 Diag(Def->getLocation(), diag::note_previous_definition); 16309 } else { 16310 unsigned DiagID = diag::ext_forward_ref_enum; 16311 if (getLangOpts().MSVCCompat) 16312 DiagID = diag::ext_ms_forward_ref_enum; 16313 else if (getLangOpts().CPlusPlus) 16314 DiagID = diag::err_forward_ref_enum; 16315 Diag(Loc, DiagID); 16316 } 16317 } 16318 16319 if (EnumUnderlying) { 16320 EnumDecl *ED = cast<EnumDecl>(New); 16321 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16322 ED->setIntegerTypeSourceInfo(TI); 16323 else 16324 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16325 ED->setPromotionType(ED->getIntegerType()); 16326 assert(ED->isComplete() && "enum with type should be complete"); 16327 } 16328 } else { 16329 // struct/union/class 16330 16331 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16332 // struct X { int A; } D; D should chain to X. 16333 if (getLangOpts().CPlusPlus) { 16334 // FIXME: Look for a way to use RecordDecl for simple structs. 16335 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16336 cast_or_null<CXXRecordDecl>(PrevDecl)); 16337 16338 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16339 StdBadAlloc = cast<CXXRecordDecl>(New); 16340 } else 16341 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16342 cast_or_null<RecordDecl>(PrevDecl)); 16343 } 16344 16345 // C++11 [dcl.type]p3: 16346 // A type-specifier-seq shall not define a class or enumeration [...]. 16347 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16348 TUK == TUK_Definition) { 16349 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16350 << Context.getTagDeclType(New); 16351 Invalid = true; 16352 } 16353 16354 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16355 DC->getDeclKind() == Decl::Enum) { 16356 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16357 << Context.getTagDeclType(New); 16358 Invalid = true; 16359 } 16360 16361 // Maybe add qualifier info. 16362 if (SS.isNotEmpty()) { 16363 if (SS.isSet()) { 16364 // If this is either a declaration or a definition, check the 16365 // nested-name-specifier against the current context. 16366 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16367 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16368 isMemberSpecialization)) 16369 Invalid = true; 16370 16371 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16372 if (TemplateParameterLists.size() > 0) { 16373 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16374 } 16375 } 16376 else 16377 Invalid = true; 16378 } 16379 16380 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16381 // Add alignment attributes if necessary; these attributes are checked when 16382 // the ASTContext lays out the structure. 16383 // 16384 // It is important for implementing the correct semantics that this 16385 // happen here (in ActOnTag). The #pragma pack stack is 16386 // maintained as a result of parser callbacks which can occur at 16387 // many points during the parsing of a struct declaration (because 16388 // the #pragma tokens are effectively skipped over during the 16389 // parsing of the struct). 16390 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16391 AddAlignmentAttributesForRecord(RD); 16392 AddMsStructLayoutForRecord(RD); 16393 } 16394 } 16395 16396 if (ModulePrivateLoc.isValid()) { 16397 if (isMemberSpecialization) 16398 Diag(New->getLocation(), diag::err_module_private_specialization) 16399 << 2 16400 << FixItHint::CreateRemoval(ModulePrivateLoc); 16401 // __module_private__ does not apply to local classes. However, we only 16402 // diagnose this as an error when the declaration specifiers are 16403 // freestanding. Here, we just ignore the __module_private__. 16404 else if (!SearchDC->isFunctionOrMethod()) 16405 New->setModulePrivate(); 16406 } 16407 16408 // If this is a specialization of a member class (of a class template), 16409 // check the specialization. 16410 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16411 Invalid = true; 16412 16413 // If we're declaring or defining a tag in function prototype scope in C, 16414 // note that this type can only be used within the function and add it to 16415 // the list of decls to inject into the function definition scope. 16416 if ((Name || Kind == TTK_Enum) && 16417 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16418 if (getLangOpts().CPlusPlus) { 16419 // C++ [dcl.fct]p6: 16420 // Types shall not be defined in return or parameter types. 16421 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16422 Diag(Loc, diag::err_type_defined_in_param_type) 16423 << Name; 16424 Invalid = true; 16425 } 16426 } else if (!PrevDecl) { 16427 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16428 } 16429 } 16430 16431 if (Invalid) 16432 New->setInvalidDecl(); 16433 16434 // Set the lexical context. If the tag has a C++ scope specifier, the 16435 // lexical context will be different from the semantic context. 16436 New->setLexicalDeclContext(CurContext); 16437 16438 // Mark this as a friend decl if applicable. 16439 // In Microsoft mode, a friend declaration also acts as a forward 16440 // declaration so we always pass true to setObjectOfFriendDecl to make 16441 // the tag name visible. 16442 if (TUK == TUK_Friend) 16443 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16444 16445 // Set the access specifier. 16446 if (!Invalid && SearchDC->isRecord()) 16447 SetMemberAccessSpecifier(New, PrevDecl, AS); 16448 16449 if (PrevDecl) 16450 CheckRedeclarationModuleOwnership(New, PrevDecl); 16451 16452 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16453 New->startDefinition(); 16454 16455 ProcessDeclAttributeList(S, New, Attrs); 16456 AddPragmaAttributes(S, New); 16457 16458 // If this has an identifier, add it to the scope stack. 16459 if (TUK == TUK_Friend) { 16460 // We might be replacing an existing declaration in the lookup tables; 16461 // if so, borrow its access specifier. 16462 if (PrevDecl) 16463 New->setAccess(PrevDecl->getAccess()); 16464 16465 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16466 DC->makeDeclVisibleInContext(New); 16467 if (Name) // can be null along some error paths 16468 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16469 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16470 } else if (Name) { 16471 S = getNonFieldDeclScope(S); 16472 PushOnScopeChains(New, S, true); 16473 } else { 16474 CurContext->addDecl(New); 16475 } 16476 16477 // If this is the C FILE type, notify the AST context. 16478 if (IdentifierInfo *II = New->getIdentifier()) 16479 if (!New->isInvalidDecl() && 16480 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16481 II->isStr("FILE")) 16482 Context.setFILEDecl(New); 16483 16484 if (PrevDecl) 16485 mergeDeclAttributes(New, PrevDecl); 16486 16487 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16488 inferGslOwnerPointerAttribute(CXXRD); 16489 16490 // If there's a #pragma GCC visibility in scope, set the visibility of this 16491 // record. 16492 AddPushedVisibilityAttribute(New); 16493 16494 if (isMemberSpecialization && !New->isInvalidDecl()) 16495 CompleteMemberSpecialization(New, Previous); 16496 16497 OwnedDecl = true; 16498 // In C++, don't return an invalid declaration. We can't recover well from 16499 // the cases where we make the type anonymous. 16500 if (Invalid && getLangOpts().CPlusPlus) { 16501 if (New->isBeingDefined()) 16502 if (auto RD = dyn_cast<RecordDecl>(New)) 16503 RD->completeDefinition(); 16504 return nullptr; 16505 } else if (SkipBody && SkipBody->ShouldSkip) { 16506 return SkipBody->Previous; 16507 } else { 16508 return New; 16509 } 16510 } 16511 16512 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16513 AdjustDeclIfTemplate(TagD); 16514 TagDecl *Tag = cast<TagDecl>(TagD); 16515 16516 // Enter the tag context. 16517 PushDeclContext(S, Tag); 16518 16519 ActOnDocumentableDecl(TagD); 16520 16521 // If there's a #pragma GCC visibility in scope, set the visibility of this 16522 // record. 16523 AddPushedVisibilityAttribute(Tag); 16524 } 16525 16526 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16527 SkipBodyInfo &SkipBody) { 16528 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16529 return false; 16530 16531 // Make the previous decl visible. 16532 makeMergedDefinitionVisible(SkipBody.Previous); 16533 return true; 16534 } 16535 16536 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16537 assert(isa<ObjCContainerDecl>(IDecl) && 16538 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16539 DeclContext *OCD = cast<DeclContext>(IDecl); 16540 assert(OCD->getLexicalParent() == CurContext && 16541 "The next DeclContext should be lexically contained in the current one."); 16542 CurContext = OCD; 16543 return IDecl; 16544 } 16545 16546 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16547 SourceLocation FinalLoc, 16548 bool IsFinalSpelledSealed, 16549 bool IsAbstract, 16550 SourceLocation LBraceLoc) { 16551 AdjustDeclIfTemplate(TagD); 16552 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16553 16554 FieldCollector->StartClass(); 16555 16556 if (!Record->getIdentifier()) 16557 return; 16558 16559 if (IsAbstract) 16560 Record->markAbstract(); 16561 16562 if (FinalLoc.isValid()) { 16563 Record->addAttr(FinalAttr::Create( 16564 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16565 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16566 } 16567 // C++ [class]p2: 16568 // [...] The class-name is also inserted into the scope of the 16569 // class itself; this is known as the injected-class-name. For 16570 // purposes of access checking, the injected-class-name is treated 16571 // as if it were a public member name. 16572 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16573 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16574 Record->getLocation(), Record->getIdentifier(), 16575 /*PrevDecl=*/nullptr, 16576 /*DelayTypeCreation=*/true); 16577 Context.getTypeDeclType(InjectedClassName, Record); 16578 InjectedClassName->setImplicit(); 16579 InjectedClassName->setAccess(AS_public); 16580 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16581 InjectedClassName->setDescribedClassTemplate(Template); 16582 PushOnScopeChains(InjectedClassName, S); 16583 assert(InjectedClassName->isInjectedClassName() && 16584 "Broken injected-class-name"); 16585 } 16586 16587 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16588 SourceRange BraceRange) { 16589 AdjustDeclIfTemplate(TagD); 16590 TagDecl *Tag = cast<TagDecl>(TagD); 16591 Tag->setBraceRange(BraceRange); 16592 16593 // Make sure we "complete" the definition even it is invalid. 16594 if (Tag->isBeingDefined()) { 16595 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16596 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16597 RD->completeDefinition(); 16598 } 16599 16600 if (isa<CXXRecordDecl>(Tag)) { 16601 FieldCollector->FinishClass(); 16602 } 16603 16604 // Exit this scope of this tag's definition. 16605 PopDeclContext(); 16606 16607 if (getCurLexicalContext()->isObjCContainer() && 16608 Tag->getDeclContext()->isFileContext()) 16609 Tag->setTopLevelDeclInObjCContainer(); 16610 16611 // Notify the consumer that we've defined a tag. 16612 if (!Tag->isInvalidDecl()) 16613 Consumer.HandleTagDeclDefinition(Tag); 16614 } 16615 16616 void Sema::ActOnObjCContainerFinishDefinition() { 16617 // Exit this scope of this interface definition. 16618 PopDeclContext(); 16619 } 16620 16621 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16622 assert(DC == CurContext && "Mismatch of container contexts"); 16623 OriginalLexicalContext = DC; 16624 ActOnObjCContainerFinishDefinition(); 16625 } 16626 16627 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16628 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16629 OriginalLexicalContext = nullptr; 16630 } 16631 16632 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16633 AdjustDeclIfTemplate(TagD); 16634 TagDecl *Tag = cast<TagDecl>(TagD); 16635 Tag->setInvalidDecl(); 16636 16637 // Make sure we "complete" the definition even it is invalid. 16638 if (Tag->isBeingDefined()) { 16639 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16640 RD->completeDefinition(); 16641 } 16642 16643 // We're undoing ActOnTagStartDefinition here, not 16644 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16645 // the FieldCollector. 16646 16647 PopDeclContext(); 16648 } 16649 16650 // Note that FieldName may be null for anonymous bitfields. 16651 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16652 IdentifierInfo *FieldName, 16653 QualType FieldTy, bool IsMsStruct, 16654 Expr *BitWidth, bool *ZeroWidth) { 16655 assert(BitWidth); 16656 if (BitWidth->containsErrors()) 16657 return ExprError(); 16658 16659 // Default to true; that shouldn't confuse checks for emptiness 16660 if (ZeroWidth) 16661 *ZeroWidth = true; 16662 16663 // C99 6.7.2.1p4 - verify the field type. 16664 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16665 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16666 // Handle incomplete and sizeless types with a specific error. 16667 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16668 diag::err_field_incomplete_or_sizeless)) 16669 return ExprError(); 16670 if (FieldName) 16671 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16672 << FieldName << FieldTy << BitWidth->getSourceRange(); 16673 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16674 << FieldTy << BitWidth->getSourceRange(); 16675 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16676 UPPC_BitFieldWidth)) 16677 return ExprError(); 16678 16679 // If the bit-width is type- or value-dependent, don't try to check 16680 // it now. 16681 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16682 return BitWidth; 16683 16684 llvm::APSInt Value; 16685 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16686 if (ICE.isInvalid()) 16687 return ICE; 16688 BitWidth = ICE.get(); 16689 16690 if (Value != 0 && ZeroWidth) 16691 *ZeroWidth = false; 16692 16693 // Zero-width bitfield is ok for anonymous field. 16694 if (Value == 0 && FieldName) 16695 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16696 16697 if (Value.isSigned() && Value.isNegative()) { 16698 if (FieldName) 16699 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16700 << FieldName << toString(Value, 10); 16701 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16702 << toString(Value, 10); 16703 } 16704 16705 // The size of the bit-field must not exceed our maximum permitted object 16706 // size. 16707 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16708 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16709 << !FieldName << FieldName << toString(Value, 10); 16710 } 16711 16712 if (!FieldTy->isDependentType()) { 16713 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16714 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16715 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16716 16717 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16718 // ABI. 16719 bool CStdConstraintViolation = 16720 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16721 bool MSBitfieldViolation = 16722 Value.ugt(TypeStorageSize) && 16723 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16724 if (CStdConstraintViolation || MSBitfieldViolation) { 16725 unsigned DiagWidth = 16726 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16727 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16728 << (bool)FieldName << FieldName << toString(Value, 10) 16729 << !CStdConstraintViolation << DiagWidth; 16730 } 16731 16732 // Warn on types where the user might conceivably expect to get all 16733 // specified bits as value bits: that's all integral types other than 16734 // 'bool'. 16735 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16736 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16737 << FieldName << toString(Value, 10) 16738 << (unsigned)TypeWidth; 16739 } 16740 } 16741 16742 return BitWidth; 16743 } 16744 16745 /// ActOnField - Each field of a C struct/union is passed into this in order 16746 /// to create a FieldDecl object for it. 16747 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16748 Declarator &D, Expr *BitfieldWidth) { 16749 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16750 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16751 /*InitStyle=*/ICIS_NoInit, AS_public); 16752 return Res; 16753 } 16754 16755 /// HandleField - Analyze a field of a C struct or a C++ data member. 16756 /// 16757 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16758 SourceLocation DeclStart, 16759 Declarator &D, Expr *BitWidth, 16760 InClassInitStyle InitStyle, 16761 AccessSpecifier AS) { 16762 if (D.isDecompositionDeclarator()) { 16763 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16764 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16765 << Decomp.getSourceRange(); 16766 return nullptr; 16767 } 16768 16769 IdentifierInfo *II = D.getIdentifier(); 16770 SourceLocation Loc = DeclStart; 16771 if (II) Loc = D.getIdentifierLoc(); 16772 16773 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16774 QualType T = TInfo->getType(); 16775 if (getLangOpts().CPlusPlus) { 16776 CheckExtraCXXDefaultArguments(D); 16777 16778 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16779 UPPC_DataMemberType)) { 16780 D.setInvalidType(); 16781 T = Context.IntTy; 16782 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16783 } 16784 } 16785 16786 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16787 16788 if (D.getDeclSpec().isInlineSpecified()) 16789 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16790 << getLangOpts().CPlusPlus17; 16791 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16792 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16793 diag::err_invalid_thread) 16794 << DeclSpec::getSpecifierName(TSCS); 16795 16796 // Check to see if this name was declared as a member previously 16797 NamedDecl *PrevDecl = nullptr; 16798 LookupResult Previous(*this, II, Loc, LookupMemberName, 16799 ForVisibleRedeclaration); 16800 LookupName(Previous, S); 16801 switch (Previous.getResultKind()) { 16802 case LookupResult::Found: 16803 case LookupResult::FoundUnresolvedValue: 16804 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16805 break; 16806 16807 case LookupResult::FoundOverloaded: 16808 PrevDecl = Previous.getRepresentativeDecl(); 16809 break; 16810 16811 case LookupResult::NotFound: 16812 case LookupResult::NotFoundInCurrentInstantiation: 16813 case LookupResult::Ambiguous: 16814 break; 16815 } 16816 Previous.suppressDiagnostics(); 16817 16818 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16819 // Maybe we will complain about the shadowed template parameter. 16820 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16821 // Just pretend that we didn't see the previous declaration. 16822 PrevDecl = nullptr; 16823 } 16824 16825 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16826 PrevDecl = nullptr; 16827 16828 bool Mutable 16829 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16830 SourceLocation TSSL = D.getBeginLoc(); 16831 FieldDecl *NewFD 16832 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16833 TSSL, AS, PrevDecl, &D); 16834 16835 if (NewFD->isInvalidDecl()) 16836 Record->setInvalidDecl(); 16837 16838 if (D.getDeclSpec().isModulePrivateSpecified()) 16839 NewFD->setModulePrivate(); 16840 16841 if (NewFD->isInvalidDecl() && PrevDecl) { 16842 // Don't introduce NewFD into scope; there's already something 16843 // with the same name in the same scope. 16844 } else if (II) { 16845 PushOnScopeChains(NewFD, S); 16846 } else 16847 Record->addDecl(NewFD); 16848 16849 return NewFD; 16850 } 16851 16852 /// Build a new FieldDecl and check its well-formedness. 16853 /// 16854 /// This routine builds a new FieldDecl given the fields name, type, 16855 /// record, etc. \p PrevDecl should refer to any previous declaration 16856 /// with the same name and in the same scope as the field to be 16857 /// created. 16858 /// 16859 /// \returns a new FieldDecl. 16860 /// 16861 /// \todo The Declarator argument is a hack. It will be removed once 16862 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16863 TypeSourceInfo *TInfo, 16864 RecordDecl *Record, SourceLocation Loc, 16865 bool Mutable, Expr *BitWidth, 16866 InClassInitStyle InitStyle, 16867 SourceLocation TSSL, 16868 AccessSpecifier AS, NamedDecl *PrevDecl, 16869 Declarator *D) { 16870 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16871 bool InvalidDecl = false; 16872 if (D) InvalidDecl = D->isInvalidType(); 16873 16874 // If we receive a broken type, recover by assuming 'int' and 16875 // marking this declaration as invalid. 16876 if (T.isNull() || T->containsErrors()) { 16877 InvalidDecl = true; 16878 T = Context.IntTy; 16879 } 16880 16881 QualType EltTy = Context.getBaseElementType(T); 16882 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16883 if (RequireCompleteSizedType(Loc, EltTy, 16884 diag::err_field_incomplete_or_sizeless)) { 16885 // Fields of incomplete type force their record to be invalid. 16886 Record->setInvalidDecl(); 16887 InvalidDecl = true; 16888 } else { 16889 NamedDecl *Def; 16890 EltTy->isIncompleteType(&Def); 16891 if (Def && Def->isInvalidDecl()) { 16892 Record->setInvalidDecl(); 16893 InvalidDecl = true; 16894 } 16895 } 16896 } 16897 16898 // TR 18037 does not allow fields to be declared with address space 16899 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16900 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16901 Diag(Loc, diag::err_field_with_address_space); 16902 Record->setInvalidDecl(); 16903 InvalidDecl = true; 16904 } 16905 16906 if (LangOpts.OpenCL) { 16907 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16908 // used as structure or union field: image, sampler, event or block types. 16909 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16910 T->isBlockPointerType()) { 16911 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16912 Record->setInvalidDecl(); 16913 InvalidDecl = true; 16914 } 16915 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 16916 // is enabled. 16917 if (BitWidth && !getOpenCLOptions().isAvailableOption( 16918 "__cl_clang_bitfields", LangOpts)) { 16919 Diag(Loc, diag::err_opencl_bitfields); 16920 InvalidDecl = true; 16921 } 16922 } 16923 16924 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16925 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16926 T.hasQualifiers()) { 16927 InvalidDecl = true; 16928 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16929 } 16930 16931 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16932 // than a variably modified type. 16933 if (!InvalidDecl && T->isVariablyModifiedType()) { 16934 if (!tryToFixVariablyModifiedVarType( 16935 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16936 InvalidDecl = true; 16937 } 16938 16939 // Fields can not have abstract class types 16940 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16941 diag::err_abstract_type_in_decl, 16942 AbstractFieldType)) 16943 InvalidDecl = true; 16944 16945 bool ZeroWidth = false; 16946 if (InvalidDecl) 16947 BitWidth = nullptr; 16948 // If this is declared as a bit-field, check the bit-field. 16949 if (BitWidth) { 16950 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16951 &ZeroWidth).get(); 16952 if (!BitWidth) { 16953 InvalidDecl = true; 16954 BitWidth = nullptr; 16955 ZeroWidth = false; 16956 } 16957 } 16958 16959 // Check that 'mutable' is consistent with the type of the declaration. 16960 if (!InvalidDecl && Mutable) { 16961 unsigned DiagID = 0; 16962 if (T->isReferenceType()) 16963 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16964 : diag::err_mutable_reference; 16965 else if (T.isConstQualified()) 16966 DiagID = diag::err_mutable_const; 16967 16968 if (DiagID) { 16969 SourceLocation ErrLoc = Loc; 16970 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16971 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16972 Diag(ErrLoc, DiagID); 16973 if (DiagID != diag::ext_mutable_reference) { 16974 Mutable = false; 16975 InvalidDecl = true; 16976 } 16977 } 16978 } 16979 16980 // C++11 [class.union]p8 (DR1460): 16981 // At most one variant member of a union may have a 16982 // brace-or-equal-initializer. 16983 if (InitStyle != ICIS_NoInit) 16984 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16985 16986 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16987 BitWidth, Mutable, InitStyle); 16988 if (InvalidDecl) 16989 NewFD->setInvalidDecl(); 16990 16991 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16992 Diag(Loc, diag::err_duplicate_member) << II; 16993 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16994 NewFD->setInvalidDecl(); 16995 } 16996 16997 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16998 if (Record->isUnion()) { 16999 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17000 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17001 if (RDecl->getDefinition()) { 17002 // C++ [class.union]p1: An object of a class with a non-trivial 17003 // constructor, a non-trivial copy constructor, a non-trivial 17004 // destructor, or a non-trivial copy assignment operator 17005 // cannot be a member of a union, nor can an array of such 17006 // objects. 17007 if (CheckNontrivialField(NewFD)) 17008 NewFD->setInvalidDecl(); 17009 } 17010 } 17011 17012 // C++ [class.union]p1: If a union contains a member of reference type, 17013 // the program is ill-formed, except when compiling with MSVC extensions 17014 // enabled. 17015 if (EltTy->isReferenceType()) { 17016 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17017 diag::ext_union_member_of_reference_type : 17018 diag::err_union_member_of_reference_type) 17019 << NewFD->getDeclName() << EltTy; 17020 if (!getLangOpts().MicrosoftExt) 17021 NewFD->setInvalidDecl(); 17022 } 17023 } 17024 } 17025 17026 // FIXME: We need to pass in the attributes given an AST 17027 // representation, not a parser representation. 17028 if (D) { 17029 // FIXME: The current scope is almost... but not entirely... correct here. 17030 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17031 17032 if (NewFD->hasAttrs()) 17033 CheckAlignasUnderalignment(NewFD); 17034 } 17035 17036 // In auto-retain/release, infer strong retension for fields of 17037 // retainable type. 17038 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17039 NewFD->setInvalidDecl(); 17040 17041 if (T.isObjCGCWeak()) 17042 Diag(Loc, diag::warn_attribute_weak_on_field); 17043 17044 // PPC MMA non-pointer types are not allowed as field types. 17045 if (Context.getTargetInfo().getTriple().isPPC64() && 17046 CheckPPCMMAType(T, NewFD->getLocation())) 17047 NewFD->setInvalidDecl(); 17048 17049 NewFD->setAccess(AS); 17050 return NewFD; 17051 } 17052 17053 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17054 assert(FD); 17055 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17056 17057 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17058 return false; 17059 17060 QualType EltTy = Context.getBaseElementType(FD->getType()); 17061 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17062 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17063 if (RDecl->getDefinition()) { 17064 // We check for copy constructors before constructors 17065 // because otherwise we'll never get complaints about 17066 // copy constructors. 17067 17068 CXXSpecialMember member = CXXInvalid; 17069 // We're required to check for any non-trivial constructors. Since the 17070 // implicit default constructor is suppressed if there are any 17071 // user-declared constructors, we just need to check that there is a 17072 // trivial default constructor and a trivial copy constructor. (We don't 17073 // worry about move constructors here, since this is a C++98 check.) 17074 if (RDecl->hasNonTrivialCopyConstructor()) 17075 member = CXXCopyConstructor; 17076 else if (!RDecl->hasTrivialDefaultConstructor()) 17077 member = CXXDefaultConstructor; 17078 else if (RDecl->hasNonTrivialCopyAssignment()) 17079 member = CXXCopyAssignment; 17080 else if (RDecl->hasNonTrivialDestructor()) 17081 member = CXXDestructor; 17082 17083 if (member != CXXInvalid) { 17084 if (!getLangOpts().CPlusPlus11 && 17085 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17086 // Objective-C++ ARC: it is an error to have a non-trivial field of 17087 // a union. However, system headers in Objective-C programs 17088 // occasionally have Objective-C lifetime objects within unions, 17089 // and rather than cause the program to fail, we make those 17090 // members unavailable. 17091 SourceLocation Loc = FD->getLocation(); 17092 if (getSourceManager().isInSystemHeader(Loc)) { 17093 if (!FD->hasAttr<UnavailableAttr>()) 17094 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17095 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17096 return false; 17097 } 17098 } 17099 17100 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17101 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17102 diag::err_illegal_union_or_anon_struct_member) 17103 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17104 DiagnoseNontrivial(RDecl, member); 17105 return !getLangOpts().CPlusPlus11; 17106 } 17107 } 17108 } 17109 17110 return false; 17111 } 17112 17113 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17114 /// AST enum value. 17115 static ObjCIvarDecl::AccessControl 17116 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17117 switch (ivarVisibility) { 17118 default: llvm_unreachable("Unknown visitibility kind"); 17119 case tok::objc_private: return ObjCIvarDecl::Private; 17120 case tok::objc_public: return ObjCIvarDecl::Public; 17121 case tok::objc_protected: return ObjCIvarDecl::Protected; 17122 case tok::objc_package: return ObjCIvarDecl::Package; 17123 } 17124 } 17125 17126 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17127 /// in order to create an IvarDecl object for it. 17128 Decl *Sema::ActOnIvar(Scope *S, 17129 SourceLocation DeclStart, 17130 Declarator &D, Expr *BitfieldWidth, 17131 tok::ObjCKeywordKind Visibility) { 17132 17133 IdentifierInfo *II = D.getIdentifier(); 17134 Expr *BitWidth = (Expr*)BitfieldWidth; 17135 SourceLocation Loc = DeclStart; 17136 if (II) Loc = D.getIdentifierLoc(); 17137 17138 // FIXME: Unnamed fields can be handled in various different ways, for 17139 // example, unnamed unions inject all members into the struct namespace! 17140 17141 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17142 QualType T = TInfo->getType(); 17143 17144 if (BitWidth) { 17145 // 6.7.2.1p3, 6.7.2.1p4 17146 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17147 if (!BitWidth) 17148 D.setInvalidType(); 17149 } else { 17150 // Not a bitfield. 17151 17152 // validate II. 17153 17154 } 17155 if (T->isReferenceType()) { 17156 Diag(Loc, diag::err_ivar_reference_type); 17157 D.setInvalidType(); 17158 } 17159 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17160 // than a variably modified type. 17161 else if (T->isVariablyModifiedType()) { 17162 if (!tryToFixVariablyModifiedVarType( 17163 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17164 D.setInvalidType(); 17165 } 17166 17167 // Get the visibility (access control) for this ivar. 17168 ObjCIvarDecl::AccessControl ac = 17169 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17170 : ObjCIvarDecl::None; 17171 // Must set ivar's DeclContext to its enclosing interface. 17172 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17173 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17174 return nullptr; 17175 ObjCContainerDecl *EnclosingContext; 17176 if (ObjCImplementationDecl *IMPDecl = 17177 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17178 if (LangOpts.ObjCRuntime.isFragile()) { 17179 // Case of ivar declared in an implementation. Context is that of its class. 17180 EnclosingContext = IMPDecl->getClassInterface(); 17181 assert(EnclosingContext && "Implementation has no class interface!"); 17182 } 17183 else 17184 EnclosingContext = EnclosingDecl; 17185 } else { 17186 if (ObjCCategoryDecl *CDecl = 17187 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17188 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17189 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17190 return nullptr; 17191 } 17192 } 17193 EnclosingContext = EnclosingDecl; 17194 } 17195 17196 // Construct the decl. 17197 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17198 DeclStart, Loc, II, T, 17199 TInfo, ac, (Expr *)BitfieldWidth); 17200 17201 if (II) { 17202 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17203 ForVisibleRedeclaration); 17204 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17205 && !isa<TagDecl>(PrevDecl)) { 17206 Diag(Loc, diag::err_duplicate_member) << II; 17207 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17208 NewID->setInvalidDecl(); 17209 } 17210 } 17211 17212 // Process attributes attached to the ivar. 17213 ProcessDeclAttributes(S, NewID, D); 17214 17215 if (D.isInvalidType()) 17216 NewID->setInvalidDecl(); 17217 17218 // In ARC, infer 'retaining' for ivars of retainable type. 17219 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17220 NewID->setInvalidDecl(); 17221 17222 if (D.getDeclSpec().isModulePrivateSpecified()) 17223 NewID->setModulePrivate(); 17224 17225 if (II) { 17226 // FIXME: When interfaces are DeclContexts, we'll need to add 17227 // these to the interface. 17228 S->AddDecl(NewID); 17229 IdResolver.AddDecl(NewID); 17230 } 17231 17232 if (LangOpts.ObjCRuntime.isNonFragile() && 17233 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17234 Diag(Loc, diag::warn_ivars_in_interface); 17235 17236 return NewID; 17237 } 17238 17239 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17240 /// class and class extensions. For every class \@interface and class 17241 /// extension \@interface, if the last ivar is a bitfield of any type, 17242 /// then add an implicit `char :0` ivar to the end of that interface. 17243 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17244 SmallVectorImpl<Decl *> &AllIvarDecls) { 17245 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17246 return; 17247 17248 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17249 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17250 17251 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17252 return; 17253 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17254 if (!ID) { 17255 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17256 if (!CD->IsClassExtension()) 17257 return; 17258 } 17259 // No need to add this to end of @implementation. 17260 else 17261 return; 17262 } 17263 // All conditions are met. Add a new bitfield to the tail end of ivars. 17264 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17265 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17266 17267 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17268 DeclLoc, DeclLoc, nullptr, 17269 Context.CharTy, 17270 Context.getTrivialTypeSourceInfo(Context.CharTy, 17271 DeclLoc), 17272 ObjCIvarDecl::Private, BW, 17273 true); 17274 AllIvarDecls.push_back(Ivar); 17275 } 17276 17277 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17278 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17279 SourceLocation RBrac, 17280 const ParsedAttributesView &Attrs) { 17281 assert(EnclosingDecl && "missing record or interface decl"); 17282 17283 // If this is an Objective-C @implementation or category and we have 17284 // new fields here we should reset the layout of the interface since 17285 // it will now change. 17286 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17287 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17288 switch (DC->getKind()) { 17289 default: break; 17290 case Decl::ObjCCategory: 17291 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17292 break; 17293 case Decl::ObjCImplementation: 17294 Context. 17295 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17296 break; 17297 } 17298 } 17299 17300 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17301 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17302 17303 // Start counting up the number of named members; make sure to include 17304 // members of anonymous structs and unions in the total. 17305 unsigned NumNamedMembers = 0; 17306 if (Record) { 17307 for (const auto *I : Record->decls()) { 17308 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17309 if (IFD->getDeclName()) 17310 ++NumNamedMembers; 17311 } 17312 } 17313 17314 // Verify that all the fields are okay. 17315 SmallVector<FieldDecl*, 32> RecFields; 17316 17317 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17318 i != end; ++i) { 17319 FieldDecl *FD = cast<FieldDecl>(*i); 17320 17321 // Get the type for the field. 17322 const Type *FDTy = FD->getType().getTypePtr(); 17323 17324 if (!FD->isAnonymousStructOrUnion()) { 17325 // Remember all fields written by the user. 17326 RecFields.push_back(FD); 17327 } 17328 17329 // If the field is already invalid for some reason, don't emit more 17330 // diagnostics about it. 17331 if (FD->isInvalidDecl()) { 17332 EnclosingDecl->setInvalidDecl(); 17333 continue; 17334 } 17335 17336 // C99 6.7.2.1p2: 17337 // A structure or union shall not contain a member with 17338 // incomplete or function type (hence, a structure shall not 17339 // contain an instance of itself, but may contain a pointer to 17340 // an instance of itself), except that the last member of a 17341 // structure with more than one named member may have incomplete 17342 // array type; such a structure (and any union containing, 17343 // possibly recursively, a member that is such a structure) 17344 // shall not be a member of a structure or an element of an 17345 // array. 17346 bool IsLastField = (i + 1 == Fields.end()); 17347 if (FDTy->isFunctionType()) { 17348 // Field declared as a function. 17349 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17350 << FD->getDeclName(); 17351 FD->setInvalidDecl(); 17352 EnclosingDecl->setInvalidDecl(); 17353 continue; 17354 } else if (FDTy->isIncompleteArrayType() && 17355 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17356 if (Record) { 17357 // Flexible array member. 17358 // Microsoft and g++ is more permissive regarding flexible array. 17359 // It will accept flexible array in union and also 17360 // as the sole element of a struct/class. 17361 unsigned DiagID = 0; 17362 if (!Record->isUnion() && !IsLastField) { 17363 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17364 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17365 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17366 FD->setInvalidDecl(); 17367 EnclosingDecl->setInvalidDecl(); 17368 continue; 17369 } else if (Record->isUnion()) 17370 DiagID = getLangOpts().MicrosoftExt 17371 ? diag::ext_flexible_array_union_ms 17372 : getLangOpts().CPlusPlus 17373 ? diag::ext_flexible_array_union_gnu 17374 : diag::err_flexible_array_union; 17375 else if (NumNamedMembers < 1) 17376 DiagID = getLangOpts().MicrosoftExt 17377 ? diag::ext_flexible_array_empty_aggregate_ms 17378 : getLangOpts().CPlusPlus 17379 ? diag::ext_flexible_array_empty_aggregate_gnu 17380 : diag::err_flexible_array_empty_aggregate; 17381 17382 if (DiagID) 17383 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17384 << Record->getTagKind(); 17385 // While the layout of types that contain virtual bases is not specified 17386 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17387 // virtual bases after the derived members. This would make a flexible 17388 // array member declared at the end of an object not adjacent to the end 17389 // of the type. 17390 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17391 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17392 << FD->getDeclName() << Record->getTagKind(); 17393 if (!getLangOpts().C99) 17394 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17395 << FD->getDeclName() << Record->getTagKind(); 17396 17397 // If the element type has a non-trivial destructor, we would not 17398 // implicitly destroy the elements, so disallow it for now. 17399 // 17400 // FIXME: GCC allows this. We should probably either implicitly delete 17401 // the destructor of the containing class, or just allow this. 17402 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17403 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17404 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17405 << FD->getDeclName() << FD->getType(); 17406 FD->setInvalidDecl(); 17407 EnclosingDecl->setInvalidDecl(); 17408 continue; 17409 } 17410 // Okay, we have a legal flexible array member at the end of the struct. 17411 Record->setHasFlexibleArrayMember(true); 17412 } else { 17413 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17414 // unless they are followed by another ivar. That check is done 17415 // elsewhere, after synthesized ivars are known. 17416 } 17417 } else if (!FDTy->isDependentType() && 17418 RequireCompleteSizedType( 17419 FD->getLocation(), FD->getType(), 17420 diag::err_field_incomplete_or_sizeless)) { 17421 // Incomplete type 17422 FD->setInvalidDecl(); 17423 EnclosingDecl->setInvalidDecl(); 17424 continue; 17425 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17426 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17427 // A type which contains a flexible array member is considered to be a 17428 // flexible array member. 17429 Record->setHasFlexibleArrayMember(true); 17430 if (!Record->isUnion()) { 17431 // If this is a struct/class and this is not the last element, reject 17432 // it. Note that GCC supports variable sized arrays in the middle of 17433 // structures. 17434 if (!IsLastField) 17435 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17436 << FD->getDeclName() << FD->getType(); 17437 else { 17438 // We support flexible arrays at the end of structs in 17439 // other structs as an extension. 17440 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17441 << FD->getDeclName(); 17442 } 17443 } 17444 } 17445 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17446 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17447 diag::err_abstract_type_in_decl, 17448 AbstractIvarType)) { 17449 // Ivars can not have abstract class types 17450 FD->setInvalidDecl(); 17451 } 17452 if (Record && FDTTy->getDecl()->hasObjectMember()) 17453 Record->setHasObjectMember(true); 17454 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17455 Record->setHasVolatileMember(true); 17456 } else if (FDTy->isObjCObjectType()) { 17457 /// A field cannot be an Objective-c object 17458 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17459 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17460 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17461 FD->setType(T); 17462 } else if (Record && Record->isUnion() && 17463 FD->getType().hasNonTrivialObjCLifetime() && 17464 getSourceManager().isInSystemHeader(FD->getLocation()) && 17465 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17466 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17467 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17468 // For backward compatibility, fields of C unions declared in system 17469 // headers that have non-trivial ObjC ownership qualifications are marked 17470 // as unavailable unless the qualifier is explicit and __strong. This can 17471 // break ABI compatibility between programs compiled with ARC and MRR, but 17472 // is a better option than rejecting programs using those unions under 17473 // ARC. 17474 FD->addAttr(UnavailableAttr::CreateImplicit( 17475 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17476 FD->getLocation())); 17477 } else if (getLangOpts().ObjC && 17478 getLangOpts().getGC() != LangOptions::NonGC && Record && 17479 !Record->hasObjectMember()) { 17480 if (FD->getType()->isObjCObjectPointerType() || 17481 FD->getType().isObjCGCStrong()) 17482 Record->setHasObjectMember(true); 17483 else if (Context.getAsArrayType(FD->getType())) { 17484 QualType BaseType = Context.getBaseElementType(FD->getType()); 17485 if (BaseType->isRecordType() && 17486 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17487 Record->setHasObjectMember(true); 17488 else if (BaseType->isObjCObjectPointerType() || 17489 BaseType.isObjCGCStrong()) 17490 Record->setHasObjectMember(true); 17491 } 17492 } 17493 17494 if (Record && !getLangOpts().CPlusPlus && 17495 !shouldIgnoreForRecordTriviality(FD)) { 17496 QualType FT = FD->getType(); 17497 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17498 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17499 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17500 Record->isUnion()) 17501 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17502 } 17503 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17504 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17505 Record->setNonTrivialToPrimitiveCopy(true); 17506 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17507 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17508 } 17509 if (FT.isDestructedType()) { 17510 Record->setNonTrivialToPrimitiveDestroy(true); 17511 Record->setParamDestroyedInCallee(true); 17512 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17513 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17514 } 17515 17516 if (const auto *RT = FT->getAs<RecordType>()) { 17517 if (RT->getDecl()->getArgPassingRestrictions() == 17518 RecordDecl::APK_CanNeverPassInRegs) 17519 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17520 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17521 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17522 } 17523 17524 if (Record && FD->getType().isVolatileQualified()) 17525 Record->setHasVolatileMember(true); 17526 // Keep track of the number of named members. 17527 if (FD->getIdentifier()) 17528 ++NumNamedMembers; 17529 } 17530 17531 // Okay, we successfully defined 'Record'. 17532 if (Record) { 17533 bool Completed = false; 17534 if (CXXRecord) { 17535 if (!CXXRecord->isInvalidDecl()) { 17536 // Set access bits correctly on the directly-declared conversions. 17537 for (CXXRecordDecl::conversion_iterator 17538 I = CXXRecord->conversion_begin(), 17539 E = CXXRecord->conversion_end(); I != E; ++I) 17540 I.setAccess((*I)->getAccess()); 17541 } 17542 17543 // Add any implicitly-declared members to this class. 17544 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17545 17546 if (!CXXRecord->isDependentType()) { 17547 if (!CXXRecord->isInvalidDecl()) { 17548 // If we have virtual base classes, we may end up finding multiple 17549 // final overriders for a given virtual function. Check for this 17550 // problem now. 17551 if (CXXRecord->getNumVBases()) { 17552 CXXFinalOverriderMap FinalOverriders; 17553 CXXRecord->getFinalOverriders(FinalOverriders); 17554 17555 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17556 MEnd = FinalOverriders.end(); 17557 M != MEnd; ++M) { 17558 for (OverridingMethods::iterator SO = M->second.begin(), 17559 SOEnd = M->second.end(); 17560 SO != SOEnd; ++SO) { 17561 assert(SO->second.size() > 0 && 17562 "Virtual function without overriding functions?"); 17563 if (SO->second.size() == 1) 17564 continue; 17565 17566 // C++ [class.virtual]p2: 17567 // In a derived class, if a virtual member function of a base 17568 // class subobject has more than one final overrider the 17569 // program is ill-formed. 17570 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17571 << (const NamedDecl *)M->first << Record; 17572 Diag(M->first->getLocation(), 17573 diag::note_overridden_virtual_function); 17574 for (OverridingMethods::overriding_iterator 17575 OM = SO->second.begin(), 17576 OMEnd = SO->second.end(); 17577 OM != OMEnd; ++OM) 17578 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17579 << (const NamedDecl *)M->first << OM->Method->getParent(); 17580 17581 Record->setInvalidDecl(); 17582 } 17583 } 17584 CXXRecord->completeDefinition(&FinalOverriders); 17585 Completed = true; 17586 } 17587 } 17588 } 17589 } 17590 17591 if (!Completed) 17592 Record->completeDefinition(); 17593 17594 // Handle attributes before checking the layout. 17595 ProcessDeclAttributeList(S, Record, Attrs); 17596 17597 // We may have deferred checking for a deleted destructor. Check now. 17598 if (CXXRecord) { 17599 auto *Dtor = CXXRecord->getDestructor(); 17600 if (Dtor && Dtor->isImplicit() && 17601 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17602 CXXRecord->setImplicitDestructorIsDeleted(); 17603 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17604 } 17605 } 17606 17607 if (Record->hasAttrs()) { 17608 CheckAlignasUnderalignment(Record); 17609 17610 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17611 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17612 IA->getRange(), IA->getBestCase(), 17613 IA->getInheritanceModel()); 17614 } 17615 17616 // Check if the structure/union declaration is a type that can have zero 17617 // size in C. For C this is a language extension, for C++ it may cause 17618 // compatibility problems. 17619 bool CheckForZeroSize; 17620 if (!getLangOpts().CPlusPlus) { 17621 CheckForZeroSize = true; 17622 } else { 17623 // For C++ filter out types that cannot be referenced in C code. 17624 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17625 CheckForZeroSize = 17626 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17627 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17628 CXXRecord->isCLike(); 17629 } 17630 if (CheckForZeroSize) { 17631 bool ZeroSize = true; 17632 bool IsEmpty = true; 17633 unsigned NonBitFields = 0; 17634 for (RecordDecl::field_iterator I = Record->field_begin(), 17635 E = Record->field_end(); 17636 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17637 IsEmpty = false; 17638 if (I->isUnnamedBitfield()) { 17639 if (!I->isZeroLengthBitField(Context)) 17640 ZeroSize = false; 17641 } else { 17642 ++NonBitFields; 17643 QualType FieldType = I->getType(); 17644 if (FieldType->isIncompleteType() || 17645 !Context.getTypeSizeInChars(FieldType).isZero()) 17646 ZeroSize = false; 17647 } 17648 } 17649 17650 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17651 // allowed in C++, but warn if its declaration is inside 17652 // extern "C" block. 17653 if (ZeroSize) { 17654 Diag(RecLoc, getLangOpts().CPlusPlus ? 17655 diag::warn_zero_size_struct_union_in_extern_c : 17656 diag::warn_zero_size_struct_union_compat) 17657 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17658 } 17659 17660 // Structs without named members are extension in C (C99 6.7.2.1p7), 17661 // but are accepted by GCC. 17662 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17663 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17664 diag::ext_no_named_members_in_struct_union) 17665 << Record->isUnion(); 17666 } 17667 } 17668 } else { 17669 ObjCIvarDecl **ClsFields = 17670 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17671 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17672 ID->setEndOfDefinitionLoc(RBrac); 17673 // Add ivar's to class's DeclContext. 17674 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17675 ClsFields[i]->setLexicalDeclContext(ID); 17676 ID->addDecl(ClsFields[i]); 17677 } 17678 // Must enforce the rule that ivars in the base classes may not be 17679 // duplicates. 17680 if (ID->getSuperClass()) 17681 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17682 } else if (ObjCImplementationDecl *IMPDecl = 17683 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17684 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17685 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17686 // Ivar declared in @implementation never belongs to the implementation. 17687 // Only it is in implementation's lexical context. 17688 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17689 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17690 IMPDecl->setIvarLBraceLoc(LBrac); 17691 IMPDecl->setIvarRBraceLoc(RBrac); 17692 } else if (ObjCCategoryDecl *CDecl = 17693 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17694 // case of ivars in class extension; all other cases have been 17695 // reported as errors elsewhere. 17696 // FIXME. Class extension does not have a LocEnd field. 17697 // CDecl->setLocEnd(RBrac); 17698 // Add ivar's to class extension's DeclContext. 17699 // Diagnose redeclaration of private ivars. 17700 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17701 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17702 if (IDecl) { 17703 if (const ObjCIvarDecl *ClsIvar = 17704 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17705 Diag(ClsFields[i]->getLocation(), 17706 diag::err_duplicate_ivar_declaration); 17707 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17708 continue; 17709 } 17710 for (const auto *Ext : IDecl->known_extensions()) { 17711 if (const ObjCIvarDecl *ClsExtIvar 17712 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17713 Diag(ClsFields[i]->getLocation(), 17714 diag::err_duplicate_ivar_declaration); 17715 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17716 continue; 17717 } 17718 } 17719 } 17720 ClsFields[i]->setLexicalDeclContext(CDecl); 17721 CDecl->addDecl(ClsFields[i]); 17722 } 17723 CDecl->setIvarLBraceLoc(LBrac); 17724 CDecl->setIvarRBraceLoc(RBrac); 17725 } 17726 } 17727 } 17728 17729 /// Determine whether the given integral value is representable within 17730 /// the given type T. 17731 static bool isRepresentableIntegerValue(ASTContext &Context, 17732 llvm::APSInt &Value, 17733 QualType T) { 17734 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17735 "Integral type required!"); 17736 unsigned BitWidth = Context.getIntWidth(T); 17737 17738 if (Value.isUnsigned() || Value.isNonNegative()) { 17739 if (T->isSignedIntegerOrEnumerationType()) 17740 --BitWidth; 17741 return Value.getActiveBits() <= BitWidth; 17742 } 17743 return Value.getMinSignedBits() <= BitWidth; 17744 } 17745 17746 // Given an integral type, return the next larger integral type 17747 // (or a NULL type of no such type exists). 17748 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17749 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17750 // enum checking below. 17751 assert((T->isIntegralType(Context) || 17752 T->isEnumeralType()) && "Integral type required!"); 17753 const unsigned NumTypes = 4; 17754 QualType SignedIntegralTypes[NumTypes] = { 17755 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17756 }; 17757 QualType UnsignedIntegralTypes[NumTypes] = { 17758 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17759 Context.UnsignedLongLongTy 17760 }; 17761 17762 unsigned BitWidth = Context.getTypeSize(T); 17763 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17764 : UnsignedIntegralTypes; 17765 for (unsigned I = 0; I != NumTypes; ++I) 17766 if (Context.getTypeSize(Types[I]) > BitWidth) 17767 return Types[I]; 17768 17769 return QualType(); 17770 } 17771 17772 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17773 EnumConstantDecl *LastEnumConst, 17774 SourceLocation IdLoc, 17775 IdentifierInfo *Id, 17776 Expr *Val) { 17777 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17778 llvm::APSInt EnumVal(IntWidth); 17779 QualType EltTy; 17780 17781 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17782 Val = nullptr; 17783 17784 if (Val) 17785 Val = DefaultLvalueConversion(Val).get(); 17786 17787 if (Val) { 17788 if (Enum->isDependentType() || Val->isTypeDependent()) 17789 EltTy = Context.DependentTy; 17790 else { 17791 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17792 // underlying type, but do allow it in all other contexts. 17793 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17794 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17795 // constant-expression in the enumerator-definition shall be a converted 17796 // constant expression of the underlying type. 17797 EltTy = Enum->getIntegerType(); 17798 ExprResult Converted = 17799 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17800 CCEK_Enumerator); 17801 if (Converted.isInvalid()) 17802 Val = nullptr; 17803 else 17804 Val = Converted.get(); 17805 } else if (!Val->isValueDependent() && 17806 !(Val = 17807 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17808 .get())) { 17809 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17810 } else { 17811 if (Enum->isComplete()) { 17812 EltTy = Enum->getIntegerType(); 17813 17814 // In Obj-C and Microsoft mode, require the enumeration value to be 17815 // representable in the underlying type of the enumeration. In C++11, 17816 // we perform a non-narrowing conversion as part of converted constant 17817 // expression checking. 17818 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17819 if (Context.getTargetInfo() 17820 .getTriple() 17821 .isWindowsMSVCEnvironment()) { 17822 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17823 } else { 17824 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17825 } 17826 } 17827 17828 // Cast to the underlying type. 17829 Val = ImpCastExprToType(Val, EltTy, 17830 EltTy->isBooleanType() ? CK_IntegralToBoolean 17831 : CK_IntegralCast) 17832 .get(); 17833 } else if (getLangOpts().CPlusPlus) { 17834 // C++11 [dcl.enum]p5: 17835 // If the underlying type is not fixed, the type of each enumerator 17836 // is the type of its initializing value: 17837 // - If an initializer is specified for an enumerator, the 17838 // initializing value has the same type as the expression. 17839 EltTy = Val->getType(); 17840 } else { 17841 // C99 6.7.2.2p2: 17842 // The expression that defines the value of an enumeration constant 17843 // shall be an integer constant expression that has a value 17844 // representable as an int. 17845 17846 // Complain if the value is not representable in an int. 17847 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17848 Diag(IdLoc, diag::ext_enum_value_not_int) 17849 << toString(EnumVal, 10) << Val->getSourceRange() 17850 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17851 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17852 // Force the type of the expression to 'int'. 17853 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17854 } 17855 EltTy = Val->getType(); 17856 } 17857 } 17858 } 17859 } 17860 17861 if (!Val) { 17862 if (Enum->isDependentType()) 17863 EltTy = Context.DependentTy; 17864 else if (!LastEnumConst) { 17865 // C++0x [dcl.enum]p5: 17866 // If the underlying type is not fixed, the type of each enumerator 17867 // is the type of its initializing value: 17868 // - If no initializer is specified for the first enumerator, the 17869 // initializing value has an unspecified integral type. 17870 // 17871 // GCC uses 'int' for its unspecified integral type, as does 17872 // C99 6.7.2.2p3. 17873 if (Enum->isFixed()) { 17874 EltTy = Enum->getIntegerType(); 17875 } 17876 else { 17877 EltTy = Context.IntTy; 17878 } 17879 } else { 17880 // Assign the last value + 1. 17881 EnumVal = LastEnumConst->getInitVal(); 17882 ++EnumVal; 17883 EltTy = LastEnumConst->getType(); 17884 17885 // Check for overflow on increment. 17886 if (EnumVal < LastEnumConst->getInitVal()) { 17887 // C++0x [dcl.enum]p5: 17888 // If the underlying type is not fixed, the type of each enumerator 17889 // is the type of its initializing value: 17890 // 17891 // - Otherwise the type of the initializing value is the same as 17892 // the type of the initializing value of the preceding enumerator 17893 // unless the incremented value is not representable in that type, 17894 // in which case the type is an unspecified integral type 17895 // sufficient to contain the incremented value. If no such type 17896 // exists, the program is ill-formed. 17897 QualType T = getNextLargerIntegralType(Context, EltTy); 17898 if (T.isNull() || Enum->isFixed()) { 17899 // There is no integral type larger enough to represent this 17900 // value. Complain, then allow the value to wrap around. 17901 EnumVal = LastEnumConst->getInitVal(); 17902 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17903 ++EnumVal; 17904 if (Enum->isFixed()) 17905 // When the underlying type is fixed, this is ill-formed. 17906 Diag(IdLoc, diag::err_enumerator_wrapped) 17907 << toString(EnumVal, 10) 17908 << EltTy; 17909 else 17910 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17911 << toString(EnumVal, 10); 17912 } else { 17913 EltTy = T; 17914 } 17915 17916 // Retrieve the last enumerator's value, extent that type to the 17917 // type that is supposed to be large enough to represent the incremented 17918 // value, then increment. 17919 EnumVal = LastEnumConst->getInitVal(); 17920 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17921 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17922 ++EnumVal; 17923 17924 // If we're not in C++, diagnose the overflow of enumerator values, 17925 // which in C99 means that the enumerator value is not representable in 17926 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17927 // permits enumerator values that are representable in some larger 17928 // integral type. 17929 if (!getLangOpts().CPlusPlus && !T.isNull()) 17930 Diag(IdLoc, diag::warn_enum_value_overflow); 17931 } else if (!getLangOpts().CPlusPlus && 17932 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17933 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17934 Diag(IdLoc, diag::ext_enum_value_not_int) 17935 << toString(EnumVal, 10) << 1; 17936 } 17937 } 17938 } 17939 17940 if (!EltTy->isDependentType()) { 17941 // Make the enumerator value match the signedness and size of the 17942 // enumerator's type. 17943 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17944 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17945 } 17946 17947 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17948 Val, EnumVal); 17949 } 17950 17951 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17952 SourceLocation IILoc) { 17953 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17954 !getLangOpts().CPlusPlus) 17955 return SkipBodyInfo(); 17956 17957 // We have an anonymous enum definition. Look up the first enumerator to 17958 // determine if we should merge the definition with an existing one and 17959 // skip the body. 17960 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17961 forRedeclarationInCurContext()); 17962 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17963 if (!PrevECD) 17964 return SkipBodyInfo(); 17965 17966 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17967 NamedDecl *Hidden; 17968 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17969 SkipBodyInfo Skip; 17970 Skip.Previous = Hidden; 17971 return Skip; 17972 } 17973 17974 return SkipBodyInfo(); 17975 } 17976 17977 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17978 SourceLocation IdLoc, IdentifierInfo *Id, 17979 const ParsedAttributesView &Attrs, 17980 SourceLocation EqualLoc, Expr *Val) { 17981 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17982 EnumConstantDecl *LastEnumConst = 17983 cast_or_null<EnumConstantDecl>(lastEnumConst); 17984 17985 // The scope passed in may not be a decl scope. Zip up the scope tree until 17986 // we find one that is. 17987 S = getNonFieldDeclScope(S); 17988 17989 // Verify that there isn't already something declared with this name in this 17990 // scope. 17991 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17992 LookupName(R, S); 17993 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17994 17995 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17996 // Maybe we will complain about the shadowed template parameter. 17997 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17998 // Just pretend that we didn't see the previous declaration. 17999 PrevDecl = nullptr; 18000 } 18001 18002 // C++ [class.mem]p15: 18003 // If T is the name of a class, then each of the following shall have a name 18004 // different from T: 18005 // - every enumerator of every member of class T that is an unscoped 18006 // enumerated type 18007 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18008 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18009 DeclarationNameInfo(Id, IdLoc)); 18010 18011 EnumConstantDecl *New = 18012 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18013 if (!New) 18014 return nullptr; 18015 18016 if (PrevDecl) { 18017 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18018 // Check for other kinds of shadowing not already handled. 18019 CheckShadow(New, PrevDecl, R); 18020 } 18021 18022 // When in C++, we may get a TagDecl with the same name; in this case the 18023 // enum constant will 'hide' the tag. 18024 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18025 "Received TagDecl when not in C++!"); 18026 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18027 if (isa<EnumConstantDecl>(PrevDecl)) 18028 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18029 else 18030 Diag(IdLoc, diag::err_redefinition) << Id; 18031 notePreviousDefinition(PrevDecl, IdLoc); 18032 return nullptr; 18033 } 18034 } 18035 18036 // Process attributes. 18037 ProcessDeclAttributeList(S, New, Attrs); 18038 AddPragmaAttributes(S, New); 18039 18040 // Register this decl in the current scope stack. 18041 New->setAccess(TheEnumDecl->getAccess()); 18042 PushOnScopeChains(New, S); 18043 18044 ActOnDocumentableDecl(New); 18045 18046 return New; 18047 } 18048 18049 // Returns true when the enum initial expression does not trigger the 18050 // duplicate enum warning. A few common cases are exempted as follows: 18051 // Element2 = Element1 18052 // Element2 = Element1 + 1 18053 // Element2 = Element1 - 1 18054 // Where Element2 and Element1 are from the same enum. 18055 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18056 Expr *InitExpr = ECD->getInitExpr(); 18057 if (!InitExpr) 18058 return true; 18059 InitExpr = InitExpr->IgnoreImpCasts(); 18060 18061 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18062 if (!BO->isAdditiveOp()) 18063 return true; 18064 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18065 if (!IL) 18066 return true; 18067 if (IL->getValue() != 1) 18068 return true; 18069 18070 InitExpr = BO->getLHS(); 18071 } 18072 18073 // This checks if the elements are from the same enum. 18074 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18075 if (!DRE) 18076 return true; 18077 18078 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18079 if (!EnumConstant) 18080 return true; 18081 18082 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18083 Enum) 18084 return true; 18085 18086 return false; 18087 } 18088 18089 // Emits a warning when an element is implicitly set a value that 18090 // a previous element has already been set to. 18091 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18092 EnumDecl *Enum, QualType EnumType) { 18093 // Avoid anonymous enums 18094 if (!Enum->getIdentifier()) 18095 return; 18096 18097 // Only check for small enums. 18098 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18099 return; 18100 18101 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18102 return; 18103 18104 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18105 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18106 18107 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18108 18109 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18110 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18111 18112 // Use int64_t as a key to avoid needing special handling for map keys. 18113 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18114 llvm::APSInt Val = D->getInitVal(); 18115 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18116 }; 18117 18118 DuplicatesVector DupVector; 18119 ValueToVectorMap EnumMap; 18120 18121 // Populate the EnumMap with all values represented by enum constants without 18122 // an initializer. 18123 for (auto *Element : Elements) { 18124 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18125 18126 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18127 // this constant. Skip this enum since it may be ill-formed. 18128 if (!ECD) { 18129 return; 18130 } 18131 18132 // Constants with initalizers are handled in the next loop. 18133 if (ECD->getInitExpr()) 18134 continue; 18135 18136 // Duplicate values are handled in the next loop. 18137 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18138 } 18139 18140 if (EnumMap.size() == 0) 18141 return; 18142 18143 // Create vectors for any values that has duplicates. 18144 for (auto *Element : Elements) { 18145 // The last loop returned if any constant was null. 18146 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18147 if (!ValidDuplicateEnum(ECD, Enum)) 18148 continue; 18149 18150 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18151 if (Iter == EnumMap.end()) 18152 continue; 18153 18154 DeclOrVector& Entry = Iter->second; 18155 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18156 // Ensure constants are different. 18157 if (D == ECD) 18158 continue; 18159 18160 // Create new vector and push values onto it. 18161 auto Vec = std::make_unique<ECDVector>(); 18162 Vec->push_back(D); 18163 Vec->push_back(ECD); 18164 18165 // Update entry to point to the duplicates vector. 18166 Entry = Vec.get(); 18167 18168 // Store the vector somewhere we can consult later for quick emission of 18169 // diagnostics. 18170 DupVector.emplace_back(std::move(Vec)); 18171 continue; 18172 } 18173 18174 ECDVector *Vec = Entry.get<ECDVector*>(); 18175 // Make sure constants are not added more than once. 18176 if (*Vec->begin() == ECD) 18177 continue; 18178 18179 Vec->push_back(ECD); 18180 } 18181 18182 // Emit diagnostics. 18183 for (const auto &Vec : DupVector) { 18184 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18185 18186 // Emit warning for one enum constant. 18187 auto *FirstECD = Vec->front(); 18188 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18189 << FirstECD << toString(FirstECD->getInitVal(), 10) 18190 << FirstECD->getSourceRange(); 18191 18192 // Emit one note for each of the remaining enum constants with 18193 // the same value. 18194 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 18195 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18196 << ECD << toString(ECD->getInitVal(), 10) 18197 << ECD->getSourceRange(); 18198 } 18199 } 18200 18201 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18202 bool AllowMask) const { 18203 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18204 assert(ED->isCompleteDefinition() && "expected enum definition"); 18205 18206 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18207 llvm::APInt &FlagBits = R.first->second; 18208 18209 if (R.second) { 18210 for (auto *E : ED->enumerators()) { 18211 const auto &EVal = E->getInitVal(); 18212 // Only single-bit enumerators introduce new flag values. 18213 if (EVal.isPowerOf2()) 18214 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18215 } 18216 } 18217 18218 // A value is in a flag enum if either its bits are a subset of the enum's 18219 // flag bits (the first condition) or we are allowing masks and the same is 18220 // true of its complement (the second condition). When masks are allowed, we 18221 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18222 // 18223 // While it's true that any value could be used as a mask, the assumption is 18224 // that a mask will have all of the insignificant bits set. Anything else is 18225 // likely a logic error. 18226 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18227 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18228 } 18229 18230 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18231 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18232 const ParsedAttributesView &Attrs) { 18233 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18234 QualType EnumType = Context.getTypeDeclType(Enum); 18235 18236 ProcessDeclAttributeList(S, Enum, Attrs); 18237 18238 if (Enum->isDependentType()) { 18239 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18240 EnumConstantDecl *ECD = 18241 cast_or_null<EnumConstantDecl>(Elements[i]); 18242 if (!ECD) continue; 18243 18244 ECD->setType(EnumType); 18245 } 18246 18247 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18248 return; 18249 } 18250 18251 // TODO: If the result value doesn't fit in an int, it must be a long or long 18252 // long value. ISO C does not support this, but GCC does as an extension, 18253 // emit a warning. 18254 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18255 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18256 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18257 18258 // Verify that all the values are okay, compute the size of the values, and 18259 // reverse the list. 18260 unsigned NumNegativeBits = 0; 18261 unsigned NumPositiveBits = 0; 18262 18263 // Keep track of whether all elements have type int. 18264 bool AllElementsInt = true; 18265 18266 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18267 EnumConstantDecl *ECD = 18268 cast_or_null<EnumConstantDecl>(Elements[i]); 18269 if (!ECD) continue; // Already issued a diagnostic. 18270 18271 const llvm::APSInt &InitVal = ECD->getInitVal(); 18272 18273 // Keep track of the size of positive and negative values. 18274 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18275 NumPositiveBits = std::max(NumPositiveBits, 18276 (unsigned)InitVal.getActiveBits()); 18277 else 18278 NumNegativeBits = std::max(NumNegativeBits, 18279 (unsigned)InitVal.getMinSignedBits()); 18280 18281 // Keep track of whether every enum element has type int (very common). 18282 if (AllElementsInt) 18283 AllElementsInt = ECD->getType() == Context.IntTy; 18284 } 18285 18286 // Figure out the type that should be used for this enum. 18287 QualType BestType; 18288 unsigned BestWidth; 18289 18290 // C++0x N3000 [conv.prom]p3: 18291 // An rvalue of an unscoped enumeration type whose underlying 18292 // type is not fixed can be converted to an rvalue of the first 18293 // of the following types that can represent all the values of 18294 // the enumeration: int, unsigned int, long int, unsigned long 18295 // int, long long int, or unsigned long long int. 18296 // C99 6.4.4.3p2: 18297 // An identifier declared as an enumeration constant has type int. 18298 // The C99 rule is modified by a gcc extension 18299 QualType BestPromotionType; 18300 18301 bool Packed = Enum->hasAttr<PackedAttr>(); 18302 // -fshort-enums is the equivalent to specifying the packed attribute on all 18303 // enum definitions. 18304 if (LangOpts.ShortEnums) 18305 Packed = true; 18306 18307 // If the enum already has a type because it is fixed or dictated by the 18308 // target, promote that type instead of analyzing the enumerators. 18309 if (Enum->isComplete()) { 18310 BestType = Enum->getIntegerType(); 18311 if (BestType->isPromotableIntegerType()) 18312 BestPromotionType = Context.getPromotedIntegerType(BestType); 18313 else 18314 BestPromotionType = BestType; 18315 18316 BestWidth = Context.getIntWidth(BestType); 18317 } 18318 else if (NumNegativeBits) { 18319 // If there is a negative value, figure out the smallest integer type (of 18320 // int/long/longlong) that fits. 18321 // If it's packed, check also if it fits a char or a short. 18322 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18323 BestType = Context.SignedCharTy; 18324 BestWidth = CharWidth; 18325 } else if (Packed && NumNegativeBits <= ShortWidth && 18326 NumPositiveBits < ShortWidth) { 18327 BestType = Context.ShortTy; 18328 BestWidth = ShortWidth; 18329 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18330 BestType = Context.IntTy; 18331 BestWidth = IntWidth; 18332 } else { 18333 BestWidth = Context.getTargetInfo().getLongWidth(); 18334 18335 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18336 BestType = Context.LongTy; 18337 } else { 18338 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18339 18340 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18341 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18342 BestType = Context.LongLongTy; 18343 } 18344 } 18345 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18346 } else { 18347 // If there is no negative value, figure out the smallest type that fits 18348 // all of the enumerator values. 18349 // If it's packed, check also if it fits a char or a short. 18350 if (Packed && NumPositiveBits <= CharWidth) { 18351 BestType = Context.UnsignedCharTy; 18352 BestPromotionType = Context.IntTy; 18353 BestWidth = CharWidth; 18354 } else if (Packed && NumPositiveBits <= ShortWidth) { 18355 BestType = Context.UnsignedShortTy; 18356 BestPromotionType = Context.IntTy; 18357 BestWidth = ShortWidth; 18358 } else if (NumPositiveBits <= IntWidth) { 18359 BestType = Context.UnsignedIntTy; 18360 BestWidth = IntWidth; 18361 BestPromotionType 18362 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18363 ? Context.UnsignedIntTy : Context.IntTy; 18364 } else if (NumPositiveBits <= 18365 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18366 BestType = Context.UnsignedLongTy; 18367 BestPromotionType 18368 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18369 ? Context.UnsignedLongTy : Context.LongTy; 18370 } else { 18371 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18372 assert(NumPositiveBits <= BestWidth && 18373 "How could an initializer get larger than ULL?"); 18374 BestType = Context.UnsignedLongLongTy; 18375 BestPromotionType 18376 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18377 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18378 } 18379 } 18380 18381 // Loop over all of the enumerator constants, changing their types to match 18382 // the type of the enum if needed. 18383 for (auto *D : Elements) { 18384 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18385 if (!ECD) continue; // Already issued a diagnostic. 18386 18387 // Standard C says the enumerators have int type, but we allow, as an 18388 // extension, the enumerators to be larger than int size. If each 18389 // enumerator value fits in an int, type it as an int, otherwise type it the 18390 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18391 // that X has type 'int', not 'unsigned'. 18392 18393 // Determine whether the value fits into an int. 18394 llvm::APSInt InitVal = ECD->getInitVal(); 18395 18396 // If it fits into an integer type, force it. Otherwise force it to match 18397 // the enum decl type. 18398 QualType NewTy; 18399 unsigned NewWidth; 18400 bool NewSign; 18401 if (!getLangOpts().CPlusPlus && 18402 !Enum->isFixed() && 18403 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18404 NewTy = Context.IntTy; 18405 NewWidth = IntWidth; 18406 NewSign = true; 18407 } else if (ECD->getType() == BestType) { 18408 // Already the right type! 18409 if (getLangOpts().CPlusPlus) 18410 // C++ [dcl.enum]p4: Following the closing brace of an 18411 // enum-specifier, each enumerator has the type of its 18412 // enumeration. 18413 ECD->setType(EnumType); 18414 continue; 18415 } else { 18416 NewTy = BestType; 18417 NewWidth = BestWidth; 18418 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18419 } 18420 18421 // Adjust the APSInt value. 18422 InitVal = InitVal.extOrTrunc(NewWidth); 18423 InitVal.setIsSigned(NewSign); 18424 ECD->setInitVal(InitVal); 18425 18426 // Adjust the Expr initializer and type. 18427 if (ECD->getInitExpr() && 18428 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18429 ECD->setInitExpr(ImplicitCastExpr::Create( 18430 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18431 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18432 if (getLangOpts().CPlusPlus) 18433 // C++ [dcl.enum]p4: Following the closing brace of an 18434 // enum-specifier, each enumerator has the type of its 18435 // enumeration. 18436 ECD->setType(EnumType); 18437 else 18438 ECD->setType(NewTy); 18439 } 18440 18441 Enum->completeDefinition(BestType, BestPromotionType, 18442 NumPositiveBits, NumNegativeBits); 18443 18444 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18445 18446 if (Enum->isClosedFlag()) { 18447 for (Decl *D : Elements) { 18448 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18449 if (!ECD) continue; // Already issued a diagnostic. 18450 18451 llvm::APSInt InitVal = ECD->getInitVal(); 18452 if (InitVal != 0 && !InitVal.isPowerOf2() && 18453 !IsValueInFlagEnum(Enum, InitVal, true)) 18454 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18455 << ECD << Enum; 18456 } 18457 } 18458 18459 // Now that the enum type is defined, ensure it's not been underaligned. 18460 if (Enum->hasAttrs()) 18461 CheckAlignasUnderalignment(Enum); 18462 } 18463 18464 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18465 SourceLocation StartLoc, 18466 SourceLocation EndLoc) { 18467 StringLiteral *AsmString = cast<StringLiteral>(expr); 18468 18469 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18470 AsmString, StartLoc, 18471 EndLoc); 18472 CurContext->addDecl(New); 18473 return New; 18474 } 18475 18476 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18477 IdentifierInfo* AliasName, 18478 SourceLocation PragmaLoc, 18479 SourceLocation NameLoc, 18480 SourceLocation AliasNameLoc) { 18481 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18482 LookupOrdinaryName); 18483 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18484 AttributeCommonInfo::AS_Pragma); 18485 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18486 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18487 18488 // If a declaration that: 18489 // 1) declares a function or a variable 18490 // 2) has external linkage 18491 // already exists, add a label attribute to it. 18492 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18493 if (isDeclExternC(PrevDecl)) 18494 PrevDecl->addAttr(Attr); 18495 else 18496 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18497 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18498 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18499 } else 18500 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18501 } 18502 18503 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18504 SourceLocation PragmaLoc, 18505 SourceLocation NameLoc) { 18506 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18507 18508 if (PrevDecl) { 18509 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18510 } else { 18511 (void)WeakUndeclaredIdentifiers.insert( 18512 std::pair<IdentifierInfo*,WeakInfo> 18513 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18514 } 18515 } 18516 18517 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18518 IdentifierInfo* AliasName, 18519 SourceLocation PragmaLoc, 18520 SourceLocation NameLoc, 18521 SourceLocation AliasNameLoc) { 18522 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18523 LookupOrdinaryName); 18524 WeakInfo W = WeakInfo(Name, NameLoc); 18525 18526 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18527 if (!PrevDecl->hasAttr<AliasAttr>()) 18528 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18529 DeclApplyPragmaWeak(TUScope, ND, W); 18530 } else { 18531 (void)WeakUndeclaredIdentifiers.insert( 18532 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18533 } 18534 } 18535 18536 Decl *Sema::getObjCDeclContext() const { 18537 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18538 } 18539 18540 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18541 bool Final) { 18542 assert(FD && "Expected non-null FunctionDecl"); 18543 18544 // SYCL functions can be template, so we check if they have appropriate 18545 // attribute prior to checking if it is a template. 18546 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18547 return FunctionEmissionStatus::Emitted; 18548 18549 // Templates are emitted when they're instantiated. 18550 if (FD->isDependentContext()) 18551 return FunctionEmissionStatus::TemplateDiscarded; 18552 18553 // Check whether this function is an externally visible definition. 18554 auto IsEmittedForExternalSymbol = [this, FD]() { 18555 // We have to check the GVA linkage of the function's *definition* -- if we 18556 // only have a declaration, we don't know whether or not the function will 18557 // be emitted, because (say) the definition could include "inline". 18558 FunctionDecl *Def = FD->getDefinition(); 18559 18560 return Def && !isDiscardableGVALinkage( 18561 getASTContext().GetGVALinkageForFunction(Def)); 18562 }; 18563 18564 if (LangOpts.OpenMPIsDevice) { 18565 // In OpenMP device mode we will not emit host only functions, or functions 18566 // we don't need due to their linkage. 18567 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18568 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18569 // DevTy may be changed later by 18570 // #pragma omp declare target to(*) device_type(*). 18571 // Therefore DevTy having no value does not imply host. The emission status 18572 // will be checked again at the end of compilation unit with Final = true. 18573 if (DevTy.hasValue()) 18574 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18575 return FunctionEmissionStatus::OMPDiscarded; 18576 // If we have an explicit value for the device type, or we are in a target 18577 // declare context, we need to emit all extern and used symbols. 18578 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18579 if (IsEmittedForExternalSymbol()) 18580 return FunctionEmissionStatus::Emitted; 18581 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18582 // we'll omit it. 18583 if (Final) 18584 return FunctionEmissionStatus::OMPDiscarded; 18585 } else if (LangOpts.OpenMP > 45) { 18586 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18587 // function. In 5.0, no_host was introduced which might cause a function to 18588 // be ommitted. 18589 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18590 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18591 if (DevTy.hasValue()) 18592 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18593 return FunctionEmissionStatus::OMPDiscarded; 18594 } 18595 18596 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18597 return FunctionEmissionStatus::Emitted; 18598 18599 if (LangOpts.CUDA) { 18600 // When compiling for device, host functions are never emitted. Similarly, 18601 // when compiling for host, device and global functions are never emitted. 18602 // (Technically, we do emit a host-side stub for global functions, but this 18603 // doesn't count for our purposes here.) 18604 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18605 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18606 return FunctionEmissionStatus::CUDADiscarded; 18607 if (!LangOpts.CUDAIsDevice && 18608 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18609 return FunctionEmissionStatus::CUDADiscarded; 18610 18611 if (IsEmittedForExternalSymbol()) 18612 return FunctionEmissionStatus::Emitted; 18613 } 18614 18615 // Otherwise, the function is known-emitted if it's in our set of 18616 // known-emitted functions. 18617 return FunctionEmissionStatus::Unknown; 18618 } 18619 18620 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18621 // Host-side references to a __global__ function refer to the stub, so the 18622 // function itself is never emitted and therefore should not be marked. 18623 // If we have host fn calls kernel fn calls host+device, the HD function 18624 // does not get instantiated on the host. We model this by omitting at the 18625 // call to the kernel from the callgraph. This ensures that, when compiling 18626 // for host, only HD functions actually called from the host get marked as 18627 // known-emitted. 18628 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18629 IdentifyCUDATarget(Callee) == CFT_Global; 18630 } 18631